Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7019 Articles
article-image-understanding-and-developing-node-modules
Packt
11 Aug 2011
5 min read
Save for later

Understanding and Developing Node Modules

Packt
11 Aug 2011
5 min read
Node Web Development A practical introduction to Node, the exciting new server-side JavaScript web development stack What's a module? Modules are the basic building block of constructing Node applications. We have already seen modules in action; every JavaScript file we use in Node is itself a module. It's time to see what they are and how they work. The following code to pull in the fs module, gives us access to its functions: var fs = require('fs'); The require function searches for modules, and loads the module definition into the Node runtime, making its functions available. The fs object (in this case) contains the code (and data) exported by the fs module. Let's look at a brief example of this before we start diving into the details. Ponder over this module, simple.js: var count = 0; exports.next = function() { return count++; } This defines an exported function and a local variable. Now let's use it: The object returned from require('./simple') is the same object, exports, we assigned a function to inside simple.js. Each call to s.next calls the function next in simple.js, which returns (and increments) the value of the count variable, explaining why s.next returns progressively bigger numbers. The rule is that, anything (functions, objects) assigned as a field of exports is exported from the module, and objects inside the module but not assigned to exports are not visible to any code outside the module. This is an example of encapsulation. Now that we've got a taste of modules, let's take a deeper look. Node modules Node's module implementation is strongly inspired by, but not identical to, the CommonJS module specification. The differences between them might only be important if you need to share code between Node and other CommonJS systems. A quick scan of the Modules/1.1.1 spec indicates that the differences are minor, and for our purposes it's enough to just get on with the task of learning to use Node without dwelling too long on the differences. How does Node resolve require('module')? In Node, modules are stored in files, one module per file. There are several ways to specify module names, and several ways to organize the deployment of modules in the file system. It's quite flexible, especially when used with npm, the de-facto standard package manager for Node. Module identifiers and path names Generally speaking the module name is a path name, but with the file extension removed. That is, when we write require('./simple'), Node knows to add .js to the file name and load in simple.js. Modules whose file names end in .js are of course expected to be written in JavaScript. Node also supports binary code native libraries as Node modules. In this case the file name extension to use is .node. It's outside our scope to discuss implementation of a native code Node module, but this gives you enough knowledge to recognize them when you come across them. Some Node modules are not files in the file system, but are baked into the Node executable. These are the Core modules, the ones documented on nodejs.org. Their original existence is as files in the Node source tree but the build process compiles them into the binary Node executable. There are three types of module identifiers: relative, absolute, and top-level. Relative module identifiers begin with "./" or "../" and absolute identifiers begin with "/". These are identical with POSIX file system semantics with path names being relative to the file being executed. Absolute module identifiers obviously are relative to the root of the file system. Top-level module identifiers do not begin with "." , "..", or "/" and instead are simply the module name. These modules are stored in one of several directories, such as a node_modules directory, or those directories listed in the array require.paths, designated by Node to hold these modules. Local modules within your application The universe of all possible modules is split neatly into two kinds, those modules that are part of a specific application, and those modules that aren't. Hopefully the modules that aren't part of a specific application were written to serve a generalized purpose. Let's begin with implementation of modules used within your application. Typically your application will have a directory structure of module files sitting next to each other in the source control system, and then deployed to servers. These modules will know the relative path to their sibling modules within the application, and should use that knowledge to refer to each other using relative module identifiers. For example, to help us understand this, let's look at the structure of an existing Node package, the Express web application framework. It includes several modules structured in a hierarchy that the Express developers found to be useful. You can imagine creating a similar hierarchy for applications reaching a certain level of complexity, subdividing the application into chunks larger than a module but smaller than an application. Unfortunately there isn't a word to describe this, in Node, so we're left with a clumsy phrase like "subdivide into chunks larger than a module". Each subdivided chunk would be implemented as a directory with a few modules in it. In this example, the most likely relative module reference is to utils.js. Depending on the source file which wants to use utils.js it would use one of the following require statements: var utils = require('./lib/utils'); var utils = require('./utils'); var utils = require('../utils');  
Read more
  • 0
  • 0
  • 3473

article-image-python-testing-coverage-analysis
Packt
01 Jun 2011
13 min read
Save for later

Python Testing: Coverage Analysis

Packt
01 Jun 2011
13 min read
Python Testing Cookbook Over 70 simple but incredibly effective recipes for taking control of automated testing using powerful Python testing tools Introduction A coverage analyzer can be used while running a system in production, but what are the pros and cons, if we used it this way? What about using a coverage analyzer when running test suites? What benefits would this approach provide compared to checking systems in production? Coverage helps us to see if we are adequately testing our system. But it must be performed with a certain amount of skepticism. This is because, even if we achieve 100 percent coverage, meaning every line of our system was exercised, in no way does this guarantee us having no bugs. A quick example involves a code we write and what it processes is the return value from a system call. What if there are three possible values, but we only handle two of them? We may write two test cases covering our handling of it, and this could certainly achieve 100 percent statement coverage. However, it doesn't mean we have handled the third possible return value; thus, leaving us with a potentially undiscovered bug. 100 percent code coverage can also be obtained by condition coverage but may not be achieved with statement coverage. The kind of coverage we are planning to target should be clear. Another key point is that not all testing is aimed at bug fixing. Another key purpose is to make sure that the application meets our customer's needs. This means that, even if we have 100 percent code coverage, we can't guarantee that we are covering all the scenarios expected by our users. This is the difference between 'building it right' and 'building the right thing'. In this article, we will explore various recipes to build a network management application, run coverage tools, and harvest the results. We will discuss how coverage can introduce noise, and show us more than we need to know, as well as introduce performance issues when it instruments our code. We will also see how to trim out information we don't need to get a concise, targeted view of things. This article uses several third-party tools in many recipes. Spring Python (http://springpython.webfactional.com) contains many useful abstractions. The one used in this article is its DatabaseTemplate, which offers easy ways to write SQL queries and updates without having to deal with Python's verbose API. Install it by typing pip install springpython. Install the coverage tool by typing pip install coverage. This may fail because other plugins may install an older version of coverage. If so, uninstall coverage by typing pip uninstall coverage, and then install it again with pip install coverage. Nose is a useful test runner.   Building a network management application For this article, we will build a very simple network management application, and then write different types of tests and check their coverage. This network management application is focused on digesting alarms, also referred to as network events. This is different from certain other network management tools that focus on gathering SNMP alarms from devices. For reasons of simplicity, this correlation engine doesn't contain complex rules, but instead contains simple mapping of network events onto equipment and customer service inventory. We'll explore this in the next few paragraphs as we dig through the code. How to do it... With the following steps, we will build a simple network management application. Create a file called network.py to store the network application. Create a class definition to represent a network event. class Event(object): def __init__(self, hostname, condition, severity, event_time): self.hostname = hostname self.condition = condition self.severity = severity self.id = -1 def __str__(self): return "(ID:%s) %s:%s - %s" % (self.id, self.hostname, self.condition, self.severity) hostname: It is assumed that all network alarms originate from pieces of equipment that have a hostname. condition: Indicates the type of alarm being generated. Two different alarming conditions can come from the same device. severity: 1 indicates a clear, green status; and 5 indicates a faulty, red status. id: The primary key value used when the event is stored in a database. Create a new file called network.sql to contain the SQL code. Create a SQL script that sets up the database and adds the definition for storing network events. CREATE TABLE EVENTS ( ID INTEGER PRIMARY KEY, HOST_NAME TEXT, SEVERITY INTEGER, EVENT_CONDITION TEXT ); Code a high-level algorithm where events are assessed for impact to equipment and customer services and add it to network.py. from springpython.database.core import* class EventCorrelator(object): def __init__(self, factory): self.dt = DatabaseTemplate(factory) def __del__(self): del(self.dt) def process(self, event): stored_event, is_active = self.store_event(event) affected_services, affected_equip = self.impact(event) updated_services = [ self.update_service(service, event) for service in affected_services] updated_equipment = [ self.update_equipment(equip, event) for equip in affected_equip] return (stored_event, is_active, updated_services, updated_equipment) The __init__ method contains some setup code to create a DatabaseTemplate. This is a Spring Python utility class used for database operations. See http://static.springsource.org/spring- python/1.2.x/sphinx/html/dao.html for more details. We are also using sqlite3 as our database engine, since it is a standard part of Python. The process method contains some simple steps to process an incoming event. We first need to store the event in the EVENTS table. This includes evaluating whether or not it is an active event, meaning that it is actively impacting a piece of equipment. Then we determine what equipment and what services the event impacts. Next, we update the affected services by determining whether it causes any service outages or restorations. Then we update the affected equipment by determining whether it fails or clears a device. Finally, we return a tuple containing all the affected assets to support any screen interfaces that could be developed on top of this. Implement the store_event algorithm. def store_event(self, event): try: max_id = self.dt.query_for_int("""select max(ID) from EVENTS""") except DataAccessException, e: max_id = 0 event.id = max_id+1 self.dt.update("""insert into EVENTS (ID, HOST_NAME, SEVERITY, EVENT_CONDITION) values (?,?,?,?)""", (event.id, event.hostname, event.severity, event.condition)) is_active = self.add_or_remove_from_active_events(event) return (event, is_active) This method stores every event that is processed. This supports many things including data mining and post mortem analysis of outages. It is also the authoritative place where other event-related data can point back using a foreign key. The store_event method looks up the maximum primary key value from the EVENTS table. It increments it by one. It assigns it to event.id. It then inserts it into the EVENTS table. Next, it calls a method to evaluate whether or not the event should be add to the list of active events, or if it clears out existing active events. Active events are events that are actively causing a piece of equipment to be unclear. Finally, it returns a tuple containing the event and whether or not it was classified as an active event. For a more sophisticated system, some sort of partitioning solution needs to be implemented. Querying against a table containing millions of rows is very inefficient. However, this is for demonstration purposes only, so we will skip scaling as well as performance and security. Implement the method to evaluate whether to add or remove active events. def add_or_remove_from_active_events(self, event): """Active events are current ones that cause equipment and/or services to be down.""" if event.severity == 1: self.dt.update("""delete from ACTIVE_EVENTS where EVENT_FK in ( select ID from EVENTS where HOST_NAME = ? and EVENT_CONDITION = ?)""", (event.hostname,event.condition)) return False else: self.dt.execute("""insert into ACTIVE_EVENTS (EVENT_FK) values (?)""", (event.id,)) return True When a device fails, it sends a severity 5 event. This is an active event and in this method, a row is inserted into the ACTIVE_EVENTS table, with a foreign key pointing back to the EVENTS table. Then we return back True, indicating this is an active event. Add the table definition for ACTIVE_EVENTS to the SQL script. CREATE TABLE ACTIVE_EVENTS ( ID INTEGER PRIMARY KEY, EVENT_FK, FOREIGN KEY(EVENT_FK) REFERENCES EVENTS(ID) ); This table makes it easy to query what events are currently causing equipment failures. Later, when the failing condition on the device clears, it sends a severity 1 event. This means that severity 1 events are never active, since they aren't contributing to a piece of equipment being down. In our previous method, we search for any active events that have the same hostname and condition, and delete them. Then we return False, indicating this is not an active event. Write the method that evaluates the services and pieces of equipment that are affected by the network event. def impact(self, event): """Look up this event has impact on either equipment or services.""" affected_equipment = self.dt.query( """select * from EQUIPMENT where HOST_NAME = ?""", (event.hostname,), rowhandler=DictionaryRowMapper()) affected_services = self.dt.query( """select SERVICE.* from SERVICE join SERVICE_MAPPING SM on (SERVICE.ID = SM.SERVICE_FK) join EQUIPMENT on (SM.EQUIPMENT_FK = EQUIPMENT.ID where EQUIPMENT.HOST_NAME = ?""", (event.hostname,), rowhandler=DictionaryRowMapper()) return (affected_services, affected_equipment) We first query the EQUIPMENT table to see if event.hostname matches anything. Next, we join the SERVICE table to the EQUIPMENT table through a many-to many relationship tracked by the SERVICE_MAPPING table. Any service that is related to the equipment that the event was reported on is captured. Finally, we return a tuple containing both the list of equipment and list of services that are potentially impacted. Spring Python provides a convenient query operation that returns a list of objects mapped to every row of the query. It also provides an out-of-the-box DictionaryRowMapper that converts each row into a Python dictionary, with the keys matching the column names. Add the table definitions to the SQL script for EQUIPMENT, SERVICE, and SERVICE_MAPPING. CREATE TABLE EQUIPMENT ( ID INTEGER PRIMARY KEY, HOST_NAME TEXT UNIQUE, STATUS INTEGER ); CREATE TABLE SERVICE ( ID INTEGER PRIMARY KEY, NAME TEXT UNIQUE, STATUS TEXT ); CREATE TABLE SERVICE_MAPPING ( ID INTEGER PRIMARY KEY, SERVICE_FK, EQUIPMENT_FK, FOREIGN KEY(SERVICE_FK) REFERENCES SERVICE(ID), FOREIGN KEY(EQUIPMENT_FK) REFERENCES EQUIPMENT(ID) ); Write the update_service method that stores or clears service-related even and then updates the service's status based on the remaining active events. def update_service(self, service, event): if event.severity == 1: self.dt.update("""delete from SERVICE_EVENTS where EVENT_FK in ( select ID from EVENTS where HOST_NAME = ? and EVENT_CONDITION = ?)""", (event.hostname,event.condition)) else: self.dt.execute("""insert into SERVICE_EVENTS (EVENT_FK, SERVICE_FK) values (?,?)""", (event.id,service["ID"])) try: max = self.dt.query_for_int( """select max(EVENTS.SEVERITY) from SERVICE_EVENTS SE join EVENTS on (EVENTS.ID = SE.EVENT_FK) join SERVICE on (SERVICE.ID = SE.SERVICE_FK) where SERVICE.NAME = ?""", (service["NAME"],)) except DataAccessException, e: max = 1 if max > 1 and service["STATUS"] == "Operational": service["STATUS"] = "Outage" self.dt.update("""update SERVICE set STATUS = ? where ID = ?""", (service["STATUS"], service["ID"])) if max == 1 and service["STATUS"] == "Outage": service["STATUS"] = "Operational" self.dt.update("""update SERVICE set STATUS = ? where ID = ?""", (service["STATUS"], service["ID"])) if event.severity == 1: return {"service":service, "is_active":False} else: return {"service":service, "is_active":True} Service-related events are active events related to a service. A single event can be related to many services. For example, what if we were monitoring a wireless router that provided Internet service to a lot of users, and it reported a critical error? This one event would be mapped as an impact to all the end users. When a new active event is processed, it is stored in SERVICE_EVENTS for each related service. Then, when a clearing event is processed, the previous service event must be deleted from the SERVICE_EVENTS table. Add the table defnition for SERVICE_EVENTS to the SQL script. CREATE TABLE SERVICE_EVENTS ( ID INTEGER PRIMARY KEY, SERVICE_FK, EVENT_FK, FOREIGN KEY(SERVICE_FK) REFERENCES SERVICE(ID), FOREIGN KEY(EVENT_FK) REFERENCES EVENTS(ID) ); It is important to recognize that deleting an entry from SERVICE_EVENTS doesn't mean that we delete the original event from the EVENTS table. Instead, we are merely indicating that the original active event is no longer active and it does not impact the related service. Prepend the entire SQL script with drop statements, making it possible to run the script for several recipes DROP TABLE IF EXISTS SERVICE_MAPPING; DROP TABLE IF EXISTS SERVICE_EVENTS; DROP TABLE IF EXISTS ACTIVE_EVENTS; DROP TABLE IF EXISTS EQUIPMENT; DROP TABLE IF EXISTS SERVICE; DROP TABLE IF EXISTS EVENTS; Append the SQL script used for database setup with inserts to preload some equipment and services. INSERT into EQUIPMENT (ID, HOST_NAME, STATUS) values (1, 'pyhost1', 1); INSERT into EQUIPMENT (ID, HOST_NAME, STATUS) values (2, 'pyhost2', 1); INSERT into EQUIPMENT (ID, HOST_NAME, STATUS) values (3, 'pyhost3', 1); INSERT into SERVICE (ID, NAME, STATUS) values (1, 'service-abc', 'Operational'); INSERT into SERVICE (ID, NAME, STATUS) values (2, 'service-xyz', 'Outage'); INSERT into SERVICE_MAPPING (SERVICE_FK, EQUIPMENT_FK) values (1,1); INSERT into SERVICE_MAPPING (SERVICE_FK, EQUIPMENT_FK) values (1,2); INSERT into SERVICE_MAPPING (SERVICE_FK, EQUIPMENT_FK) values (2,1); INSERT into SERVICE_MAPPING (SERVICE_FK, EQUIPMENT_FK) values (2,3); Finally, write the method that updates equipment status based on the current active events. def update_equipment(self, equip, event): try: max = self.dt.query_for_int( """select max(EVENTS.SEVERITY) from ACTIVE_EVENTS AE join EVENTS on (EVENTS.ID = AE.EVENT_FK) where EVENTS.HOST_NAME = ?""", (event.hostname,)) except DataAccessException: max = 1 if max != equip["STATUS"]: equip["STATUS"] = max self.dt.update("""update EQUIPMENT set STATUS = ?""", (equip["STATUS"],)) return equip Here, we need to find the maximum severity from the list of active events for a given host name. If there are no active events, then Spring Python raises a DataAccessException and we translate that to a severity of 1. We check if this is different from the existing device's status. If so, we issue a SQL update. Finally, we return the record for the device, with its status updated appropriately. How it works... This application uses a database-backed mechanism to process incoming network events, and checks them against the inventory of equipment and services to evaluate failures and restorations. Our application doesn't handle specialized devices or unusual types of services. This real-world complexity has been traded in for a relatively simple application, which can be used to write various test recipes. Events typically map to a single piece of equipment and to zero or more services. A service can be thought of as a string of equipment used to provide a type of service to the customer. New failing events are considered active until a clearing event arrives. Active events, when aggregated against a piece of equipment, define its current status. Active events, when aggregated against a service, defines the service's current status.  
Read more
  • 0
  • 0
  • 3472

article-image-maintaining-your-gitlab-instance
Packt
22 Dec 2014
14 min read
Save for later

Maintaining Your GitLab Instance

Packt
22 Dec 2014
14 min read
In this article by Jeroen van Baarsen, the author of the book GitLab Cookbook, we will see how we can manage GitLab. We look at procedures to update GitLab and also concentrate on troubleshooting problems faced. Updating an Omnibus installation Updating GitLab from a source installation Troubleshooting your GitLab installation Creating a backup Restoring a backup Importing Git repositories (For more resources related to this topic, see here.) Introduction When running your GitLab installation, you need to update it every once in a while. GitLab is released every 22nd day of the month, so around the end of the month would be a nice time to update! The releases on the 22nd day are well tested, as gitlab.com is using the release candidates in production all the time. This way, you can be sure that the release meets the standards of the GitLab team! In this chapter, we will take a look at how you can update your GitLab server and how you can create backups and restore them. If you want to know what has changed in the new release, you can take a look at the change log provided in the repository for GitLab at https://gitlab.com/gitlab-org/gitlab-ce/blob/master/CHANGELOG. Updating an Omnibus installation In this article, we will take a look at how you can update your GitLab installation when you install it via the Omnibus package. In this article, I'll make the assumption that you're using Ubuntu 12.04. You can use other Linux distributions; the steps for these can be found at about.gitlab.com. How to do it… Let's update the Omnibus installation with the following steps: Log in to your server via SSH. Stop the unicorn server: $ sudo gitlab-ctl stop unicorn Stop the background job server: $ sudo gitlab-ctl stop sidekiq Create a backup in case the upgrade fails: $ sudo gitlab-rake gitlab:backup:create Download the package from the GitLab website (https://about.gitlab.com/downloads/): $ wget https://downloads-packages.s3.amazonaws.com/ubuntu-12.04/gitlab_7.1.1-omnibus.1-1_amd64.deb Install the new package (change the x.x.x part to the correct version number from your download): sudo dpkg -i gitlab_x.x.x-omnibus.xxx.deb Reconfigure GitLab: sudo gitlab-ctl reconfigure Restart all the services: sudo gitlab-ctl restart How it works… On the 22nd day of every month, a new version of GitLab is released. This also includes the Omnibus package. As the installation of Omnibus based on GitLab does not take very long, the GitLab team has decided to install a new version of GitLab and preserve the old data of the old installation; this way, you don't go over an update process, but you will be guided through the installation process as if you're installing a new GitLab instance. So, when you're updating an Omnibus-based installation, you're not really updating but rather installing a newer version and reconfiguring it to use the old data. One thing you have to keep in mind is that making backups is very important. As any update can go wrong at some level, it's a good feeling to know that when stuff goes wrong, you always have a backup that you can use to get back up and running as quickly as possible. Updating GitLab from a source installation Updating used to be a lot of work; you had to open the update document to find out that you need to perform about 15 steps to upgrade your GitLab installation. To tackle this issue, the GitLab team has created a semiautomatic upgrader. When you run the upgrader, it will check whether there is a new minor version. If there is, it will start the upgrade process for you. It will perform database migrations and update config files for you. How to do it… Upgrade your source installation with the following steps: Log in to your server using SSH. We start with creating a backup just in case something goes wrong. Go to the folder of your GitLab instance: $ cd /home/git/gitlab Create the backup; this might take a little while depending on the amount of repositories and the size of each individual repository: $ sudo -u git -H bundle exec rake gitlab:backup:create RAILS_ENV=production Stop the server: $ sudo service gitlab stop Run the upgrader: $ if [ -f bin/upgrade.rb ]; then sudo -u git -Hruby bin/upgrade.rb; else sudo -u git -Hruby script/upgrade.rb; fi Start the application: $ sudo service gitlab start && sudo service nginx restart Check whether everything went fine. We can use the self-check GitLab ships with: $ sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production If the GitLab check indicates that we need to upgrade the GitLab shell, we can do this by performing the following steps. Go to the shell directory: $ cd /home/git/gitlab-shell Fetch the latest code: $ sudo -u git -H git fetch Run the following command to set the pointer to the latest shell release. Change 1.9.4 to the current version number. You can find this number in the output of the check we did in step 9: sudo -u git -H git checkout v1.9.4 How it works… It is highly recommended that you create a backup before you run the upgrader as every update can break something in your installation. It's a good feeling to know that when all goes wrong, you're prepared and can roll back the upgrade using the backup. Troubleshooting your GitLab installation When your GitLab instance does not work the way you expect it to work, it's nice to have a way to check what parts of your installation are not working properly. In this article, we will take a look at the self-diagnostic tools provided by GitLab. How to do it… Learn how to troubleshoot your GitLab server with the following steps: Log in to your server using SSH. The first case shows troubleshooting in the case of a GitLab source installation. Go to your gitlab folder: $ cd /home/git/gitlab To autodiagnose your installation, run the following command: $ sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production When there is a problem with your GitLab installation, it will be outputted in red text, as shown in the following screenshot: The solution for the problem is also given; just follow the explanation given by the problem you walk into. In this case, we have to run the following command: $ sudo-u git -h bundle exec rake gitlab:satellites:create RAILS_ENV=production If everything is green, your installation is in great shape! The next few steps concentrate on troubleshooting in the case of the Gitlab Omnibus installation. Run the following command: $ sudo gitlab-rake gitlab:check When you have any problem with your GitLab installation, this will be outputted; also, the possible solution will be shown. The solution that is given for this problem is the solution for the source installation. To fix this issue in the Omnibus installation, we need to alter the command a little. You have to replace the $ sudo-u git -h bundle exec rake part with $ sudo gitlab-rake. So, the command will look as follows: $ sudo gitlab-rake gitlab:satellites:create RAILS_ENV=production If everything is green, your installation is in top shape! In case you need to view the logs, you can run the following command: $ sudo gitlab-ctl tail To exit the log flow, use Ctrl + C. How it works… When you think your GitLab installation might not be in a good shape or you think you've found a bug, it's always a good idea to run the self-diagnostics for GitLab. It will tell you whether you've configured GitLab correctly and whether everything is still up to date. Here is a list of what will be checked: Is your database config correct? If your database is still running SQLite instead of PostgreSQL or MySQL, it will give you a warning. Are all the user groups configured correctly? Is the GitLab config present and up to date? Are the logs writable? Is the tmp directory writable? Is the init script present and up to date? Are all the projects namespaced? This is important if you've upgraded from an old version. Are all the satellites present? Is your Redis up to date? Is the correct Ruby version being used? Is the correct Git version being used? This is the first place you should start when walking into problems. If this does not give you the correct answers, you can open an issue on the GitLab repository (https://gitlab.com/gitlab-org/gitlab-ce). Make sure you post the output of this check as well, as you will most likely be asked to post it anyway. Creating a backup It's important that you have your source code secured so that when your laptop breaks down—or even worse, the office got destroyed—the most valuable part of your company (besides the employees, of course) is still intact. You've already taken an important step into the right direction; you set up a Git server so that your source code has multiple places to live. However, what if that server breaks down? This is where backups come into play! GitLab Omnibus makes it really easy to create backups. With just a simple command, everything in your system gets backed up: the repositories as well as the databases. It's all packed in a tar ball, so you can store it elsewhere, for example, Amazon S3 or just another server somewhere else. In this article, we not only created a backup, but also created a schema to automatically back up the creation using crontabs. This way, you can rest assured that all of your code gets backed up every night. How to do it… In the following steps, we will set up the backups for GitLab: First, log in to your server using SSH. The first few steps concentrate on the GitLab source installation. Go to your gitlab folder: cd /home/git/gitlab Run the backup command: bundle exec rake gitlab:backup:create RAILS_ENV=production The backup will now run. This might take a while depending on the number of repositories and the size of each repository. The backups will be stored in the /home/git/gitlab/tmp/backups directory. Having to create a backup by hand everyday is no fun, so let's automate the creation of backups using a cronjob file. Run the following command to open the cronjob file: $ sudo -u git crontab -e Add the following content to the end of the file: 0 2 * * * cd /home/git/gitlab && PATH=/usr/local/bin:/usr/bin:/bin bundle exec rake gitlab:backup:create RAILS_ENV=production Save the file, and the backups will be created everyday at 2 A.M. The next few steps talk about the GitLab Omnibus installation. To create the backup, run the following command: $ sudo gitlab-rake gitlab:backup:create A backup is now created in the $ /var/opt/gitlab/backups directory. Let's verify that our backup is actually there: $ ls /var/opt/gitlab/backups/ You should see at least one filename, such as 1404647816_gitlab_backup.tar. The number in the filename is a timestamp, so this might differ in your case. Now we know how to create the backup. Let's automate this via a cronjob file. Run the following command as the root user: $ crontab -e Add the following code to the end of the file to have the backup run every day at 2 A.M.: 0 2 * * * /opt/gitlab/bin/gitlab-rake gitlab:backup:create After you save the file, a backup will be created every day at 2 A.M. This is great, but there is a tiny catch; if you have the backups run for too long, it will take up all of your disk space. Let's fix this! Open this file location: /etc/gitlab/gitlab.rb. Let's have the backups only last for a week. After that, they will be destroyed. 7 days is 604,800 seconds. Add the following code to the bottom of the file: gitlab_rails['backup_keep_time'] = 604800 To have the changes take effect, we have to tell GitLab to reconfigure itself. Run the following command: $ sudo gitlab-ctl reconfigure Restoring a backup If your server breaks down, it is nice to have a backup. However, it's a pain when it's a full day's work to restore that backup; it's just a waste of time. Luckily, GitLab makes it super easy to restore the backup. Retrieve the backup from your external Amazon S3 storage or just your external hard drive, copy the file to your server, and run the backup restore command. It won't get any easier! Getting ready Make sure you have a recent backup of your GitLab instance. After you restore the backup, all the data created between the backup creation and the restoration of your backup will be lost. How to do it… Let's restore a backup using the following steps: Start with a login to your server using SSH. The next few steps concentrate on the GitLab source installation. Go to your gitlab folder: $ cd /home/git/gitlab Go to the backup folder of GitLab: $ cd /home/git/gitlab/tmp/backups Look at the filename of the most recent file and note the number that the filename starts with. Go back to your GitLab folder: $ cd /home/git/gitlab Now, run the following command and replace the 1234567 part with the number you took from the latest backup filename: $ bundle exec rake gitlab:backup:restore RAILS_ENV=production BACKUP=1234567 The next few steps concentrate on the GitLab Omnibus installation. Make sure your backup file is located at /var/opt/gitlab/backups: $ cp 1407564013_gitlab_backup.tar /var/opt/gitlab/backups/ Before we can restore the backup, we need to stop our instance. First, stop GitLab itself: $ sudo gitlab-ctl stop unicorn Next, stop the background worker: $ sudo gitlab-ctl stop sidekiq Now, we will restore our backup. You need to provide the timestamp of the backup you want to restore. The timestamp is the long number before the filename. Warning: this will overwrite all the data in your database! The following command depicts this: $ sudo gitlab-rake gitlab:backup:restore BACKUP=TIMESTAMP_OF_BACKUP Restoring the actual backup might take a little while depending on the size of your database. Restart your GitLab server again: $ sudo gitlab-ctl start Importing an existing repository It's quite simple to import your repositories from somewhere else. All you need to do is create a new project and select the repository to be imported. In this article, we will take a look at how this is done. For this article, we will import the repository hosted on GitHub at https://github.com/gitlabhq/gitlab-shell. How to do it… In the following steps, we will import a repository: Log in to your GitLab instance. Click on New project. Enter the project name as GitLab Shell. Click on Import existing repository?. Enter the URL for the repository we want to import: https://github.com/gitlabhq/gitlab-shell Now, click on Create Project. Importing the existing repository might take a while depending on the size of the repository. After the importing is done, you will be redirected to the project page. Let's check whether it's actually an imported repository. Click on the Network menu item. If everything is fine, you should see the graph in the following screenshot: How it works… There is really nothing magical about importing a repository. All GitLab does is clone the URL you give it to its own satellite. After this is done, the satellite will be linked to your project, and you're done! What if your repository is private and not publicly accessible? You can import it by adding the user credentials in the URL. Don't worry; this information is not stored anywhere! So, if we have the same repository as the one we used earlier but it has credentials, it will look like what is shown in https://username:password@github.com/gitlabhq/gitlab-shell. Summary In this article, we learned about the update processes for GitLab. We also got a gist of the ways that we can use to troubleshoot problems faced. The article explains how we can restore and back up an existing repository. Resources for Article: Further resources on this subject: Searching and Resolving Conflicts [Article] Issues and Wikis in GitLab [Article] Configuration [Article]
Read more
  • 0
  • 1
  • 3471

article-image-roles-and-permissions-moodle-administration-part1
Packt
23 Oct 2009
1 min read
Save for later

Roles and Permissions in Moodle Administration: Part1

Packt
23 Oct 2009
1 min read
Lets get started. Moodle's PreDefined Roles Moodle comes with a number of predefined roles. These standard roles are suitable for some educational setups, but most institutions require modifications to the roles' system in order to tailor Moodle to their specific needs. Each role has permissions for a number of actions that can be carried out in Moodle. For example, an administrator and a course creator are able to create new courses, whereas all other roles are denied this right. Likewise, a teacher is allowed to moderate forums, whereas students are only allowed to contribute to them. Before we can actually do anything with roles, we need to understand the concept of contexts, which is dealt with next. Contexts Contexts are the areas in Moodle where roles can be assigned to users. A role can be assigned within different contexts. A user has a role in any given context, where a context can be a course, an activity module, a user, a block, or Moodle itself. Moodle comes with the following seven contexts that you will come across a lot in this article.
Read more
  • 0
  • 0
  • 3470

article-image-term-extraction-tasks-sql-server-integration-services
Packt
23 Oct 2009
7 min read
Save for later

Term Extraction Tasks in SQL Server Integration Services

Packt
23 Oct 2009
7 min read
The following text (SomeText.txt) file saved at a suitable location on the hard drive is used. This particular text is: Rose is RedChrysanthemum is yellowViolets are violetRose can be PinkHyacinth is whiteDesk jobs are the bestLily is also whiteThe girl is wearing a rose garlandThe boy is handsomePink rose is not redrose garland is made of rosesRoserose is not roseHe rose to powerThe desk is made of rose wood The reason for using the above text is to see how well the Term Extract transformation is able to distinguish words and phrases and find how often they are found in a body of text. The transformation works for text in English and is capable of distinguishing between nouns and other parts of speech. In the following steps we will create a Visual Studio 2005 Business Intelligence project and access some text stored on the hard drive, and apply this transformation and review the results. Creating a Business Intelligence Project In the Visual Studio 2005 IDE, File | New | Project opens the New Project window as shown, where you can highlight the Integration Services Project template in the Business Intelligence page and change its default name to something different. For this tutorial TermExtract has been used as the project name. Text to be accessed shown above is saved to a file, SomeText.txt in the C: drive. In order to access this from the Integration Services we need to create a Package with a data flow task. The source for this data is the SomeText.txt file on the C: drive. Change the name of the default package file name to something different, In this case MineText.dtsx. Click Yes on the Microsoft Visual Studio message box asking whether you want to rename the package. Add a Data Flow Task Drag and drop a Data Flow Task to the Control Flow page as shown in the next figure. The Data Flow Task will access the SomeText.txt using a connection manager, an intermediary between SQL Server Integration Services and the external system. Add a Flat File Source Click on the Data Flow Task page. Drag and drop a Flat File Source from the Data Flow Sources group in the Toolbox and drop it on the Data Flow Page which is open as shown. When the Flat File Source is dropped on the Data Flow Task page you may see this error in the error window as shown. This is nothing to worry about because a connection is not yet established. Add a Connection Manager to Manage Flat File Source Now right click in the Connection Manager's pane as shown to display the pick list of connection managers and choose New Flat File Connection... as shown. This immediately displays the Flat File Connection Manager's editor window as shown. You must provide a name of your choice to the Connection Manager, and a description of your choice. Then you need to use the Browse button to locate the SomeText.txt file on your hard drive. The next figure shows the editor after these choices are made. The rest of the fields such as Locale, Code page, etc were automatically chosen by the program. Now click on the Columns list item in the left of the Editor. The one column that gets populated with the data from the SomeText.txt gets displayed. The program has correctly configured the fields for this text. Click on the OK button on the Editor. This adds a Connection Manager, MyText to the Connection manager's pane in the SSIS designer. With this, the SomeText.txt is available for the other controls that you may add. Add a Term Extraction Transformation The column that was populated in the above will now pass through the Term Extraction Transformation added by dragging and dropping this from the Toolbox on to the Data Flow Page. Click the dangling green line and extend it to touch the Term Extraction Transformation. This is an easy way to establish a connection from the source to a transformation, a destination. Double click the Term Extraction Transformation to open its Editor as shown in the next figure. In the Term Extraction tabbed page you see a single column which is displayed unchecked. Place a check mark for this column as shown in the next figure. When the 'terms' are extracted, the output column will have a 'term' and a 'score' column. The term refers to a noun, a noun phrase, or a noun and a noun phrase. The score represents how many times each term is repeated in the body of the text. Pay attention to the message that says the column can have only values of a certain types and the disabled OK button. The data type of the data going into the Term Extract Transformation can be found by right clicking on the connecting green line and looking at the page that reveals the Meta data list item as shown in the next figure. This is of the data type DT_STR. To rectify this, there are two options, either use one more transformation, the data conversion transformation or use the Advanced Editor of the Flat File Source which can be displayed by right clicking the Flat File source component and choosing the Show Advanced Editor. This option was made to change Str[DT_STR] to Unicode str [DT_WSTR]. The DT_* shows the data type that are supported. The following information about these data types are shown extracted from the Books on line. DT_STR: A null-terminated ANSI/MBCS character string DT_NTEXT: A Unicode character string with a maximum length of 2^30-1 characters DT_WSTR: a null terminated Unicode character string Now when you place a check mark for the Column 0 in the Term Extract Transformation Editor, the OK gets enabled. Click on the Exclusion tab to reveal its page. This page when configured, allows you to exclude (skip) certain terms stored in an OLEDB database. The figure shows the details of editing this page. A Microsoft Access 2003 database called 'SkipTerms' was created and a new table 'SkipTable' was created in this database. It has two columns SkipID (autonumber, Primary Key) and SkipThis (text). A new OLEDB Connection was established along the same lines as the connection manager to the Flat File Source. Of course you need to choose an OLEDB Provider in making this connection. The 'SkipThis' column has just one entry, 'desk'. This noun is found twice in SomeText.txt. The word 'desk' will be skipped in the output column when the Column 0 is processed by this transformation. Click on the Advanced tab to open its page as shown. This is where you choose type of terms, nouns, noun phrases, or both noun and noun phrases. You also select the score which shows how many times (Frequency and Frequency Threshold) the terms appear in the text. As chosen here, the transformation will be looking for noun(s) that gets repeated twice. The case sensitive option can also be chosen but left blank in this exercise. The score type TFIDF is another type of scoring more appropriate for a document collection and not a single document like in this article. You may learn more details on this from this link.  
Read more
  • 0
  • 0
  • 3470

article-image-vbnet-application-sql-anywhere-10-database-part-2
Packt
24 Oct 2009
3 min read
Save for later

VB.NET Application with SQL Anywhere 10 database: Part 2

Packt
24 Oct 2009
3 min read
[Read the first part of this article here] Now you can click on the Preview Data… hyperlink which opens up the Preview Data window as shown in Figure 19. The Select an object to preview field gets populated automatically to run the getData () method. When you click on the Preview button, the grey area is populated by a table showing the retrieved rows of data from the Customers table as shown in Figure 19. Figure 19 Click on the Close button in the above window. In the various tasks of the DataGridView many options are chosen by default. You may also check reordering of the column by placing a check mark in the Edit Column Reordering in Figure 18 which opens Edit Columns window as shown in Figure 20, another useful control to manipulate the columns so that the columns you want to see are the first few columns. Figure 20 You may want to edit the columns and change some of the items such as reordering of the columns, column name, column width, etc. All this can be done from this screen. For this tutorial only the columns width was changed. A label was added and its text was changed to, "Demo 10 Database Customers" as shown in Figure 21. Figure 21     Build the project from the main menu item, Build. Now when the program is run by clicking the Debug --> Start without debugging, or by pressing Ctrl+F5, the program runs and Form1 is displayed as shown in Figure 22. Figure 22 Figure 23 shows the properties of the dataset DsAny that is created when the data source was created. Figure 23   The schema of the above dataset is shown in Figure 24. This gets added to the project files in the Solution Explorer. Figure 24   Using the smart tasks on the CustomerBindingSource you can carry out few of the indicated tasks shown in Figure 25. Figure 25   The properties of the CustomerBindingSource are shown in Figure 26. Figure 26 The CustomerTableAdapter directly connects to the database and it has its own properties window as shown in Figure 27. You will be able to edit queries in the dataset designer, add query, etc using the hyperlinks at the bottom of the properties window. Figure 27 Alternatively you will be able to carry out similar tasks from the smart tasks on the CustomerTableAdapter component in the component tray as shown in Figure 28. In Microsoft applications, you have more than one way of carrying out a task. Figure 28 The Object Browser shown in Figure 29 for this project shows the various data related classes that are used in the application working behind scenes as not a single line of code was explicitly used for this form to display the data. Figure 29  
Read more
  • 0
  • 0
  • 3469
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-apache-cassandra-libraries-and-applications
Packt
29 Jun 2011
6 min read
Save for later

Apache Cassandra: Libraries and Applications

Packt
29 Jun 2011
6 min read
  Cassandra High Performance Cookbook Over 150 recipes to design and optimize large scale Apache Cassandra deployments Introduction Cassandra's popularity has led to several pieces of software that have developed around it. Some of these are libraries and utilities that make working with Cassandra easier. Other software applications have been built completely around Cassandra to take advantage of its scalability. This article describes some of these utilities. Building Cassandra from source The Cassandra code base is active and typically has multiple branches. It is a good practice to run official releases, but at times it may be necessary to use a feature or a bug fix that has not yet been released. Building and running Cassandra from source allows for a greater level of control of the environment. Having the source code, it is also possible to trace down and understand the context or warning or error messages you may encounter. This recipe shows how to checkout Cassandra code from Subversion (SVN) and build it. How to do it... Visit http://svn.apache.org/repos/asf/cassandra/branches with a web browser. Multiple sub folders will be listed: /cassandra-0.5/ /cassandra-0.6/ Each folder represents a branch. To check out the 0.6 branch: $ svn co http://svn.apache.org/repos/asf/cassandra/branches/ cassandra-0.6/ Trunk is where most new development happens. To check out trunk: $ svn co http://svn.apache.org/repos/asf/cassandra/trunk/ To build the release tar, move into the folder created and run: $ ant release This creates a release tar in build/apache-cassandra-0.6.5-bin.tar.gz, a release jar, and an unzipped version in build/dist. How it works... Subversion (SVN) is a revision control system commonly used to manage software projects. Subversion repositories are commonly accessed via the HTTP protocol. This allows for simple browsing. This recipe is using the command-line client to checkout code from the repository. Building the contrib stress tool for benchmarking Stress is an easy-to-use command-line tool for stress testing and benchmarking Cassandra. It can be used to generate a large quantity of requests in short periods of time, and it can also be used to generate a large amount of data to test performance with. This recipe shows how to build it from the Cassandra source. Getting ready Before running this recipe, complete the Building Cassandra from source recipe discussed above. How to do it... From the source directory, run ant. Then, change to the contrib/stress directory and run ant again. $ cd <cassandra_src> $ ant jar $ cd contrib/stress $ ant jar ... BUILD SUCCESSFUL Total time: 0 seconds How it works... The build process compiles code into the stress.jar file. Inserting and reading data with the stress tool The stress tool is a multithreaded load tester specifically for Cassandra. It is a command-line program with a variety of knobs that control its operation. This recipe shows how to run the stress tool. Before you begin... See the previous recipe, Building the contrib stress tool for benchmarking before doing this recipe. How to do it... Run the <cassandra_src>/bin/stress command to execute 10,000 insert operations. $ bin/stress -d 127.0.0.1,127.0.0.2,127.0.0.3 -n 10000 --operation INSERT Keyspace already exists. total,interval_op_rate,interval_key_rate,avg_latency,elapsed_time 10000,1000,1000,0.0201764,3 How it works... The stress tool is an easy way to do load testing against a cluster. It can insert or read data and report on the performance of those operations. This is also useful in staging environments where significant volumes of disk data are needed to test at scale. Generating data is also useful to practice administration techniques such as joining new nodes to a cluster. There's more... It is best to run the load testing tool on a different node than on the system being tested and remove anything else that causes other unnecessary contention. Running the Yahoo! Cloud Serving Benchmark The Yahoo! Cloud Serving Benchmark (YCSB) provides benchmarking for the bases of comparison between NoSQL systems. It works by generating random workloads with varying portions of insert, get, delete, and other operations. It then uses multiple threads for executing these operations. This recipe shows how to build and run the YCSB. Information on the YCSB can be found here: http://research.yahoo.com/Web_Information_Management/YCSB https://github.com/brianfrankcooper/YCSB/wiki/ https://github.com/joaquincasares/YCSB How to do it... Use the git tool to obtain the source code. $ git clone git://github.com/brianfrankcooper/YCSB.git Build the code using the ant. $ cd YCSB/ $ ant Copy the JAR files from your <cassandra_hom>/lib directory to the YCSB classpath. $ cp $HOME/apache-cassandra-0.7.0-rc3-1/lib/*.jar db/ cassandra-0.7/lib/ $ ant dbcompile-cassandra-0.7 Use the Cassandra CLI to create the required keyspace and column family. [default@unknown] create keyspace usertable with replication_ factor=3; [default@unknown] use usertable; [default@unknown] create column family data; Create a small shell script run.sh to launch the test with different parameters. CP=build/ycsb.jar for i in db/cassandra-0.7/lib/*.jar ; do CP=$CP:${i} done java -cp $CP com.yahoo.ycsb.Client -t -db com.yahoo.ycsb. db.CassandraClient7 -P workloads/workloadb -p recordcount=10 -p hosts=127.0.0.1,127.0.0.2 -p operationcount=10 -s Run the script ant pipe the output to more command to control pagination: $ sh run.sh | more YCSB Client 0.1 Command line: -t -db com.yahoo.ycsb.db.CassandraClient7 -P workloads/workloadb -p recordcount=10 -p hosts=127.0.0.1,127.0.0.2 -p operationcount=10 -s Loading workload... Starting test. data 0 sec: 0 operations; 0 sec: 10 operations; 64.52 current ops/sec; [UPDATE AverageLatency(ms)=30] [READ AverageLatency(ms)=3] [OVERALL], RunTime(ms), 152.0 [OVERALL], Throughput(ops/sec), 65.78947368421052 [UPDATE], Operations, 1 [UPDATE], AverageLatency(ms), 30.0 [UPDATE], MinLatency(ms), 30 [UPDATE], MaxLatency(ms), 30 [UPDATE], 95thPercentileLatency(ms), 30 [UPDATE], 99thPercentileLatency(ms), 30 [UPDATE], Return=0, 1 How it works... YCSB has many configuration knobs. An important configuration option is -P, which chooses the workload. The workload describes the portion of read, write, and update percentage. The -p option overrides options from the workload file. YCSB is designed to test performance as the number of nodes grows and shrinks, or scales out. There's more... Cassandra has historically been one of the strongest performers in the YCSB.
Read more
  • 0
  • 0
  • 3469

article-image-implementing-particles-melonjs
Andre Antonio
23 Jun 2014
14 min read
Save for later

Implementing Particles with melonJS

Andre Antonio
23 Jun 2014
14 min read
With the popularity of games on smartphones and browsers, 2D gaming is back on the scene, recalling the classic age of the late '80s and early '90s. At that time, most games used animation techniques with images (sprite sheets) to display special effects such as explosions, fire, or magic. In current games we can use particle systems, generating random and interesting visual effects in them. In this post I will briefly describe what a particle system is and how to implement models using the HTML5 engine melonJS. Note: Although the examples are specific to the melonJS game engine using JavaScript as a programming language, the concepts and ideas can be adapted for other languages ​​or game engines as well. Particle systems A particle system is a technique used to simulate a variety of special visual effects like sparks, dust, smoke, fire, explosions, rain, stars, falling snow, glowing trails, and many others. Basically, a particle system consists of emitters and the particles themselves. The particles are small objects or textures that have different properties, such as: Position (x, y) Velocity (vx, vy) Scale Angle Transparency (alpha) Texture (sprite ou cor Lifetime These particles perform some functions associated with their properties (movement, rotation, scaling, change in transparency, and so on) for a period of time, and are removed from the game after this interval (or they are returned to a pool of particles for reuse, ensuring better performance). According to how the particle system is implemented, it may have some characteristics affected by its lifetime, such as its size or transparency. For example, the older the particle, the sooner it will be eliminated from the game, and the smaller its size and transparency. The emitter is responsible for launching the particles, acting as a point of origin and working in a group with dozens or hundreds of particles simultaneously. Each emitter has several parameters that determine the characteristics of the particles generated by it. These parameters may include, among others: Emission rate of new particles Initial position of the particles Initial speed of the particles Gravity applied to the particles Life time of the particles When activated, the emitter manages the number of generated particles and can have different behaviors, and can emit a certain number of particles simultaneously and stop (used in an explosion), or constantly emit particles (used in smoke). It is common for an emitter to allow random value ranges (like the initial position or the lifetime of the particles), creating different and interesting effects each time it is activated, unlike an animation sequence that always exhibits the same effects. melonJS - a lightweight HTML5 game engine melonJS (http://melonjs.org/) is an open source engine that uses JavaScript and the HTML5 Canvas element to develop games that can be accessed online via a compatible browser technology. It has native integration with a Tiled Map Editor (http://www.mapeditor.org/), facilitating the creation of game levels. It even has many features such as a basic physics engine and collision management, animations, support for sprite sheets and texture atlases, tweens effects, audio support, a built-in particle system, object pooling, and mouse and touch support among others. All of these features assist in process development and the prototyping of games. The engine implements a mechanism of inheritance (based on John Resig's Simple Inheritance) allowing any object to be extended. Several functions and classes are provided to the developer for direct use or for extending new features. The following is a simple example of engine use with an object of type me.Renderable (engine base class to draw on the canvas): game.myRenderable = me.Renderable.extend({ // constructor init : function() { // set the object screen position (x, y) = (100, 200); width = 150 and height = 50 this.parent(new me.Vector2d(100, 200), 150, 50); // set the z-order this.z = 1; }, // logic - collision, movement, etc update : function(dt) { return false; }, // draw - canvas draw : function(context) { // change the canvas context color context.fillStyle = '#000'; // draw a simple rectangle in the canvas context.fillRect(this.pos.x, this.pos.y, this.width, this.height); } }); // create and add the renderable in the game world me.game.world.addChild(new game.myRenderable()); This example draws a rectangle of dimensions (150, 50) at position (100, 200) of the canvas using the color black (# 000) as filler. Single particles with melonJS Using the classes and functions of melonJS, we can assemble a simple particle system, simulating, for example, drops of water. The following example will emit some particles with an initial velocity vertical (Y axis) and will fall until they leave the screen area of ​​the game, through gravity mechanism implemented by the physics engine. The example can be accessed online (http://aaschmitz.github.io/melonjs-simple-particles) and the code is available on GitHub (https://github.com/aaschmitz/melonjs-simple-particles). Simple particle example   The particles will be implemented through a me.Renderable object to draw an image on the canvas, with attributes initialized randomly, allowing that a particle is distinct from another: game.dropletParticle = me.SpriteObject.extend({ init: function(x, y) { // class constructor this.parent(x, y, me.loader.getImage("droplet")); // the particle update even off screen this.alwaysUpdate = true; // calculate random launch angle - convert degrees in radians var launch = Number.prototype.degToRad(Number.prototype.random(10, 80)); // calculate random distance from point x original var distance = Number.prototype.random(3, 5); // calculate random altitude from point y original var altitude = Number.prototype.random(10, 12); // particle screen side (value negative is left, positive is right and zero is center) var screenSide = Number.prototype.random(-1, 1); // create new vector and set initial particle velocity this.vel = new me.Vector2d(Math.sin(launch) * distance * screenSide, -Math.cos(launch) * altitude); // set the default engine gravity me.sys.gravity = 0.3; }, update: function(dt) { // check the particle position in screen limits if ((this.pos.y > 0) && (this.pos.y < me.game.viewport.getHeight()) && (this.pos.x > 0) && (this.pos.x < me.game.viewport.getWidth())) { // set particle position this.vel.y += me.sys.gravity; this.pos.x += this.vel.x;         this.pos.y += this.vel.y;                               this.parent(dt);             return true;         } else {             // particle off screen - remove the same!             me.game.world.removeChild(this, true);              return false;         }     } });  This code snippet is used as a particle, and the class game.dropletParticle must be initialized with the position (x, y) of the particle on the screen. When the particle is not in the visible area of ​​the screen, it will be deleted. For various particles, we will use a basic emitter, which will be implemented with a normal JavaScript function: game.startEmitter = function(x, y, count) {     // add count particles in the game, all at once!     for (var i = 0; i < count; i++)         // add the particle in the game, using the mouse coordinates and z-order = 5         // use the object pool for better performance!         me.game.world.addChild(me.pool.pull("droplet", x, y), 5); }; This emitter will be called to emit count particles at once using the initial position (x, y). Note that for best performance, the pooling mechanism of the engine is used in the generation of particles. Similar to the example described previously, you'll find the implementation effects of drops and stars in an educational game, Vibrant Recyclin. It is available online (http://vibrantrecycling.ciangames.com) and developed by the author using the engine melonJS: Single particles in the game Vibrant Recycling Improved particles through the embedded particle system For the use of particles with more advanced or complex effects, the previous example proves to be poor, requiring the addition of more attributes in the particles (such as rotation, lifetime, and so on) and creating a more robust emitter with many different behaviors. Starting from version 1.0.0 of the melonJS engine, a particle system was added in it, facilitating the creation of advanced particles and emitters. The particle system consists of the following classes: me.Particle: This is thebase class of particles, responsible for movement (using physics), updating the properties and the drawing of each individual particle. Its properties are set and adjusted directly by the associate emitter. me.ParticleEmitter: This is theclass responsible for generating the particles according to the parameters configured on each emitter. It can emit particles with a stream behavior (throws particles sequentially in an infinite form or to a defined time) or burst (launches all particles at the same time). For more information, see the official documentation of the engine, available online at http://melonjs.github.io/docs/me.ParticleEmitter.html. me.ParticleContainer: This is theclass associated with each emitter, which maintains a relationship with all particles generated by it, updating the logic of them and being responsible for the removal of particles that are outside the viewport or have a life time reset. me.ParticleEmitterSettings: This is the object containing the default settings to be used in emitters, allowing you to create many reusable emitters models. Check the parameters allowed by consulting the official documentation of the engine available online at http://melonjs.github.io/docs/me.ParticleEmitterSettings.html. To use the particle system with melonJS, do the following: Instantiate an emitter. Adjust the properties of the emitter or assign a me.ParticleEmitterSettings previously created for the same. Add the emitter and its container in the game. Enable the emitter through the functions burstParticles() or streamParticles() however many times necessary. At the end of the process, remove the emitter and its container from the game. The following is a basic example of an emitter that, if enabled, will simulate an explosion launching the particles upwards. Note that the example uses a normal JavaScript function and each time the function is called, the emitter is created, activated, and destroyed, which is not a good option if the function is executed several times: game.makeExplosion = function(x, y) {     // create a basic emitter at position (x, y) using sprite "explosion"     var emitter = new me.ParticleEmitter(x, y, me.loader.getImage("explosion"));     // adjust the emitter properties     // launch 50 particles              emitter.totalParticles = 50;     // particles lifetime between 1s and 3s     emitter.minLife = 1000;     emitter.maxLife = 3000;     // particles have initial velocity between 7 and 13     emitter.speed = 10;     emitter.speedVariation = 3;     // initial launch angle between 70 and 110 degrees     emitter.angle = Number.prototype.degToRad(90);     emitter.angleVariation = Number.prototype.degToRad(20);     // gravity 0.3 and z-order 10     emitter.gravity = 0.3;     emitter.z = 10;     // add the emitter to the game world     me.game.world.addChild(emitter);     me.game.world.addChild(emitter.container);     // launch all particles one time and stop     emitter.burstParticles();     // remove emitter from the game world     me.game.world.removeChild(emitter);     me.game.world.removeChild(emitter.container); }; The example with simple particles described in the previous section will be implemented using the built-in particle system in the engine. This can be accessed online (http://aaschmitz.github.io/melonjs-improved-particles) and the code is available on GitHub (https://github.com/aaschmitz/melonjs-improved-particles).  game.explosionManager = Object.extend({              init: function(x, y) {         // create a new emitter         this.emitter = new me.ParticleEmitter(x, y);         this.emitter.z = 10;         // start the emitter with pre-defined params         this.start(x, y);         // add the emitter to game         me.game.world.addChild(this.emitter);         me.game.world.addChild(this.emitter.container);     },     start: function(x, y) {         // set the emitter params         this.emitter.image = me.loader.getImage("droplet");         this.emitter.totalParticles = 20;         this.emitter.minLife = 2000;         this.emitter.maxLife = 5000;         this.emitter.speed = 10;         this.emitter.speedVariation = 3;         this.emitter.angle = Number.prototype.degToRad(90);         this.emitter.angleVariation = Number.prototype.degToRad(20);         this.emitter.minStartScale = 0.6;         this.emitter.maxStartScale = 1.0;         this.emitter.gravity = 0.3;         // move the emitter         this.emitter.pos.set(x, y);     },     launch: function(x, y) {                    // move the emitter         this.emitter.pos.set(x, y);         // launch the particles!         this.emitter.burstParticles();     },     remove: function() {         // remove the emitter from game                 me.game.world.removeChild(this.emitter.container);         me.game.world.removeChild(this.emitter);     } }); Comparing the examples using simple particles and the one using the built-in particle system of the engine, we note that the second option is more robust, customizable, and fluid. It provides more realism and refinement in the effects created by the particles. Improved particle example using the built-in particle system Visual particles editor The melonJS engine has a visual particles editor, available online (http://melonjs.github.io/examples/particles/) for creating emitters faster or to make fine adjustments in emitters already created. melonJS particles editor The particles editor has a selection menu on the top of screen, where you choose between several emitters preset such as fire, smoke, and rain. The right pane of the screen is responsible for configuring (and tuning) emitters. The left pane displays the configuration parameters of the emitter currently running, serving to be added via code the parameters of the emitter to be used in the game. You can operate the mouse on the center screen indicators (colored circles) affecting directly some properties of the emitters in a visual way. Conclusion The use of a particle system allows the creation of more enjoyable and interesting visual effects, through customization and randomization of several parameters configured in the emitters, thus creating a greater diversity of particles generated. The melonJS engine proves to be a robust and viable alternative to creating games in HTML5. Being an open source project and having a very active team and community, melonJS receives several enhancements and features with each new version, making it easier for game developers to use. About the author  Andre Antonio Schmitz is a game developer focusing on HTML5 at Cian Games (http://www.ciangames.com). Living in Caxias do Sul, Brasil, he graduated with a Bachelor's degree in Computer Science and an MBA specialization in IT Management. You can find him on Twitter (https://twitter.com/aaaschmitz), Google+ (https://plus.google.com/+AndreAntonioSchmitz/), or GitHub (https://github.com/aaschmitz).
Read more
  • 0
  • 0
  • 3468

article-image-first-steps-scalix-admin-console-and-scalix-web-access
Packt
21 Oct 2009
4 min read
Save for later

First Steps with Scalix Admin Console and Scalix Web Access

Packt
21 Oct 2009
4 min read
SAC at a Glance Point your Browser to the URL of your Scalix server, following this syntax: http:///sac. A pop-up window with the Administration Console Login is opened. If you are using Firefox or another browser with pop-up suppression, perhaps the configuration will need some corrections. Allow the Scalix server to open popups. In Firefox, you can easily configure this by clicking in the yellow bar on top of the displayed page. Other browsers may require editing the preferences. Otherwise, Scalix will provide a web page for you with a link, which opens the Admin Console in the same browser window. Logging In On Scalix 11, the Scalix Administration Login looks like this: Enter the Administrator's name in the field Login ID, exactly as configured during installation. Activate the reminder that you are connected via http and not through https by clicking on option field Not using a secure https connection. Once we have configured https for Scalix, the login dialog will not provide this option anymore. However, enabling https is not that easy, and therefore not standard in Scalix, except for the installations on Red Hat Enterprise. Click on the button Login to start the Administration console. A First Look Around The Scalix Administration Console is a Web application provided by a Tomcat application server. The only requirement for it is a modern browser supporting JavaScript. Firefox and Internet Explorer do fine, Konqueror may work soon. The Admin Console window is split in three parts: A menu with icons called Toolbar A list view on the lower left named Contents Pane and The main window on the right, called Display Pane The icons in the menu bar let you choose the administration task you want to accomplish, the content pane lists the possible entries that can be edited, and the options and parameters of a selected entry are presented in the display pane. By clicking on one of the icons on the Toolbar, you can access the different sections of the Scalix Administration Console. The first three sections are about users, groups, and resources, and will be used in daily administration for adding, deleting or modifying these objects. The section Plugins offers a management GUI for your own or third-party Scalix plug-ins. The Server Info icon leads to a concise list of running services, where the administrator can set the log level of these services and browse through the services' log files. The Settings Icon allows you to set preferences for the server and new users. A concise online help is available, and the icons Refresh and Logout complete the menu bar's icons. Navigating in the Admin Console A nice gadget in SAC is the little icon on the top left of the main window. Surrounded by four arrows, this icon displays the icon of the current section and enables the administrator to navigate in a quick and easy manner through the administration console. Clicking the up or down arrows will select and activate the next entry upwards or downwards in the list view to the left, and the left/right arrows navigate you back and forth in a browser-like fashion. Users, Groups, Resources... Now click on the Users icon in order to switch to the user management dialog. Click on the entry of the only user present at this time, sxadmin. For every user, there are six tabs where the user information is stored. The tab General holds the most important information: Username, Display Name, and Email address. This information is all that is necessary to add an user and use the new account. The other tabs contain contact information, group memberships, and administrative delegations. The mailbox quota, that is the amount of storage that the user's account may sum up to, is configured in the Mail dialog. On the Advanced tab, the administrator can add a role to the user, decide whether this user is a Standard or a Premium User, and give him a different authentication ID. Changing Passwords There are other features in the Admin Console that you will be using frequently once you are master of some Scalix users. One of them is probably the button Change Password on the lower right corner leading directly to the password dialog. This button is present in every user's configuration dialog.
Read more
  • 0
  • 0
  • 3468

article-image-security-settings-salesforce
Packt
11 Sep 2014
10 min read
Save for later

Security Settings in Salesforce

Packt
11 Sep 2014
10 min read
In the article by Rakesh Gupta and Sagar Pareek, authors of Salesforce.com Customization Handbook, we will discuss Organization-Wide Default (OWD) and various ways to share records. We will also discuss the various security settings in Salesforce. The following topics will be covered in this article: (For more resources related to this topic, see here.) Concepts of OWD The sharing rule Field-Level Security and its effect on data visibility Setting up password polices Concepts of OWD Organization-Wide Default is also known as OWD. This is the base-level sharing and setting of objects in your organization. By using this, you can secure your data so that other users can't access data that they don't have access to. The following diagram shows the basic database security in Salesforce. In this, OWD plays a key role. It's a base-level object setting in the organization, and you can't go below this. So here, we will discuss OWD in Salesforce. Let's start with an example. Sagar Pareek is the system administrator in Appiuss. His manager Sara Barellies told him that the user who has created or owns the account records as well as the users that are higher in the role hierarchy can access the records. Here, you have to think first about OWD because it is the basic thing to restrict object-level access in Salesforce. To achieve this, Sagar Pareek has to set Organization-Wide Default for the account object to private. Setting up OWD To change or update OWD for your organization, follow these steps: Navigate to Setup | Administer | Security Controls | Sharing Settings. From the Manage sharing settings for drop-down menu, select the object for which you want to change OWD. Click on Edit. From the Default Access drop-down menu, select an access as per your business needs. For the preceding scenario, select Private to grant access to users who are at a high position in the role hierarchy, by selecting Grant access using hierarchy. For standard objects, it is automatically selected, and for custom objects, you have the option to select it. Click on Save. The following table describes the various types of OWD access and their respective description: OWD access Description Private Only the owner of the records and the higher users in the role hierarchy are able to access and report on the records. Public read only All users can view the records, but only the owners and the users higher in the role hierarchy can edit them. Public read/write All users can view, edit, and report on all records. Public read/write/ transfer All users can view, edit, transfer, and report on all records. This is only available for case and lead objects. Controlled by parent This says that access on the child object's records is controlled by the parent. Public full access This is available for campaigns. In this, all users can view, edit, transfer, and report on all records.   You can assign this access to campaigns, accounts, cases, contacts, contracts, leads, opportunities, users, and custom objects. This feature is only available for Professional, Enterprise, Unlimited, Performance, Developer, and Database Editions. Basic OWD settings for objects Whenever you buy your Salesforce Instance, it comes with the predefined OWD settings for standard objects. You can change them anytime by following the path Setup | Administer | Security Controls | Sharing Settings. The following table describes the default access to objects: Object Default access Account Public read/write Activity Private Asset Public read/write Campaign Public full access Case Public read/write transfer Contact Controlled by parent (that is, account) Contract Public read/write Custom Object Public read/write Lead Public read/write transfer Opportunity Public read only Users Public read only and private for external users Let's continue with another example. Sagar Pareek is the system administrator in Appiuss. His manager Sara Barellies told him that only the users who created the record for the demo object can access the records, and no one else can have the power to view/edit/delete it. To do this, you have to change OWD for a demo object to private, and don't select Grant Access Using Hierarchy. When you select the Grant Access Using Hierarchy field, it provides access to people who are above in the role hierarchy. Sharing Rule To open the record-level access for a group of users, roles, or roles and subordinates beyond OWD, you can use Sharing Rule. Sharing Rule is used for open access; you can't use Sharing Rule to restrict access. Let's start with an example where Sagar Pareek is the system administrator in Appiuss. His manager Sara Barellies wants every user in the organization to be able to view the account records but only a group of users (all the users do not belong to the same role or have the same profile) can edit it. To solve the preceding business requirement, you have to follow these steps: First, change the OWD account to Public Read Only by following the path Setup | Administer | Security Controls | Sharing Settings, so all users from the organization can view the account records. Now, create a public group Account access and add users as per the business requirement. To create a public group, follow the path Name | Setup | Administration Setup | Manage Users | Public Groups. Finally, you have to create a sharing rule. To create sharing rules, follow the path Setup | Administer | Security Controls | Sharing Settings, and navigate to the list related to Account Sharing Rules: Click on New, and it will redirect you to a new window where you have to enter Label, Rule Name, and Description (always write a description so that other administrators or developers get to know why this rule was created). Then, for Rule Type, select Based on criteria. Select the criteria by which records are to be shared and create a criterion so that all records fall under it (such as Account Name not equal to null). Select Public Groups in the Share with option and your group name. Select the level of access for the users. Here, select Read/Write from the drop-down menu of Default Account, Contract and Asset Access. Finally, it will look like the following screenshot: Types of Sharing Rules What we did to solve the preceding business requirement is called Sharing Rule. There is a limitation on Sharing Rules; you can write only 50 Sharing Rules (criteria-based) and 300 Sharing Rules (both owner- and criteria-based) per object. The following are the types of Sharing Rules in Salesforce: Manual Sharing: Only when OWD is set to Private or Public Read for any object will a sharing button be enabled in the record detail page. Record owners or users, who are at a higher position in role and hierarchy, can share records with other users. For the last business use case, we changed the account OWD to Public Read Only. If you navigate to the Account records detail page, you can see the Sharing button: Click on the Sharing button and it will redirect you to a new window. Now, click on Add and you are ready to share records with the following: Public groups Users Roles Roles and subordinates Select the access type for each object and click on Save. It will look like what is shown in the following screenshot: The Lead and Case Sharing buttons will be enabled when OWD is Private, Public Read Only, and Public Read/Write. Apex Sharing: When all other Sharing Rules can't fulfill your requirements, then you can use the Apex Sharing method to share records. It gives you the flexibility to handle complex sharing. Apex-managed sharing is a type of programmatic sharing that allows you to define a custom sharing reason to associate with your programmatic share. Standard Salesforce objects support programmatic sharing while custom objects support Apex-managed sharing. Field-Level Security and its effect on data visibility Data on fields is very important for any organization. They want to show some data to the field-specific users. In Salesforce, you can use Field-Level Security to make fields hidden or read-only for a specific profile. There are three ways in Salesforce to set Field-Level Security: From an object-field From a profile Field accessibility From an object-field Let's start with an example where Sagar Pareek is the system administrator in Appiuss. His manager Sara Barellies wants to create a field (phone) on an account object and make this field read-only for all users and also allowing system administrators to edit the field. To solve this business requirement, follow these steps: Navigate to Setup | Customize | Account | Fields and then click on the Phone (it's a hyperlink) field. It will redirect you to the detail page of the Phone field; you will see a page like the following screenshot: Click on the Set Field-Level Security button, and it will redirect you to a new page where you can set the Field-Level Security. Select Visible and Read-Only for all the profiles other than that of the system administrator. For the system administrator, select only Visible. Click on Save. If you select Read-Only, the visible checkbox will automatically get selected. From a profile Similarly, in Field-Level settings, you can also achieve the same results from a profile. Let's follow the preceding business use case to be achieved through the profile. To do this, follow these steps: Navigate to Setup | Administer | Manage Users | Profile, go to the System Administrator profile, and click on it. Now, you are on the profile detail page. Navigate to the Field-Level Security section. It will look like the following screenshot: Click on the View link beside the Account option. It will open Account Field-Level Security for the profile page. Click on the Edit button and edit Field-Level Security as we did in the previous section. Field accessibility We can achieve the same outcome by using field accessibility. To do this, follow these steps: Navigate to Setup | Administer | Security Controls | Field Accessibility. Click on the object name; in our case, it's Account. It will redirect you to a new page where you can select View by Fields or View by Profiles: In our case, select View by Fields and then select the field Phone. Click on the editable link as shown in the following screenshot: It will open the Access Settings for Account Field page, where you can edit the Field-Level Security. Once done, click on Save. Setting up password policies For security purposes, Salesforce provides an option to set password policies for the organization. Let's start with an example. Sagar Pareek, the system administrator of an organization, has decided to create a policy regarding the password for the organization, where the password of each user must be of 10 characters and must be a combination of alphanumeric and special characters. To do this, he will have to follow these steps: Navigate to Setup | Security Controls | Password Policies. It will open the Password Policies setup page: In the Minimum password length field, select 10 characters. In the Password complexity requirement field, select Must mix Alpha, numeric and special characters. Here, you can also decide when the password should expire under the User password expire in option. Enforce the password history under the option enforce password history, and set a password question requirement as well as the number of invalid attempts allowed and the lock-out period. Click on Save. Summary In this article, we have gone through various security setting features available on Salesforce. Starting from OWD, followed by Sharing Rules and Field-Level Security, we also covered password policy concepts. Resources for Article: Further resources on this subject: Introducing Salesforce Chatter [Article] Salesforce CRM Functions [Article] Adding a Geolocation Trigger to the Salesforce Account Object [Article]
Read more
  • 0
  • 0
  • 3467
article-image-introduction-wordpress-applications-frontend
Packt
12 Nov 2013
7 min read
Save for later

Introduction to a WordPress application's frontend

Packt
12 Nov 2013
7 min read
(For more resources related to this topic, see here.) Basic file structure of a WordPress theme As WordPress developers, you should have a fairly good idea about the default file structure of WordPress themes. Let's have a brief introduction of the default files before identifying their usage in web applications. Think about a typical web application layout where we have a common header, footer, and content area. In WordPress, the content area is mainly populated by pages or posts. The design and the content for pages are provided through the page.php template, while the content for posts is provided through one of the following templates: index.php archive.php category.php single.php Basically, most of these post-related file types are developed to cater to the typical functionality in blogging systems, and hence can be omitted in the context of web applications. Since custom posts are widely used in application development, we need more focus on templates such as single-{post_type} and archive-{post_type} than category.php, archive.php, and tag.php. Even though default themes contain a number of files for providing default features, only the style.css and index.php files are enough to implement a WordPress theme. Complex web application themes are possible with the standalone index.php file. In normal circumstances, WordPress sites have a blog built on posts, and all the remaining content of the site is provided through pages. When referring to pages, the first thing that comes to our mind is the static content. But WordPress is a fully functional CMS, and hence the page content can be highly dynamic. Therefore, we can provide complex application screens by using various techniques on pages. Let's continue our exploration by understanding the theme file execution hierarchy. Understanding template execution hierarchy WordPress has quite an extensive template execution hierarchy compared to general web application frameworks. However, most of these templates will be of minor importance in the context of web applications. Here, we are going to illustrate the important template files in the context of web applications. The complete template execution hierarchy can be found at: http://hub.packtpub.com/wp-content/uploads/2013/11/Template_Hierarchy.png An example of the template execution hierarchy is as shown in the following diagram: Once the Initial Request is made, WordPress looks for one of the main starting templates as illustrated in the preceding screenshot. It's obvious that most of the starting templates such as front page, comments popup, and index pages are specifically designed for content management systems. In the context of web applications, we need to put more focus into both singular and archive pages, as most of the functionality depends on top of those templates. Let's identify the functionality of the main template files in the context of web applications: Archive pages: These are used to provide summarized listings of data as a grid. Single posts: These are used to provide detailed information about existing data in the system. Singular pages: These are used for any type of dynamic content associated with the application. Generally, we can use pages for form submissions, dynamic data display, and custom layouts. Let's dig deeper into the template execution hierarchy on the Singular Page path as illustrated in the following diagram: Singular Page is divided into two paths that contain posts or pages. Static Page is defined as Custom or Default page templates. In general, we use Default page templates for loading website pages. WordPress looks for a page with the slug or ID before executing the default page.php file. In most scenarios, web application layouts will take the other route of Custom page templates where we create a unique template file inside the theme for each of the layouts and define it as a page template using code comments. We can create a new custom page template by creating a new PHP file inside the theme folder and using the Template Name definition in code comments illustrated as follows: <?php/** Template Name: My Custom Template*/?> To the right of the preceding diagram, we have Single Post Page, which is divided into three paths called Blog Post, Custom Post, and Attachment Post. Both Attachment Posts and Blog Posts are designed for blogs and hence will not be used frequently in web applications. However, the Custom Post template will have a major impact on application layouts. As with Static Page, Custom Post looks for specific post type templates before looking for a default single.php file. The execution hierarchy of an Archive Page is similar in nature to posts, as it looks for post-specific archive pages before reverting to the default archive.php file. Now we have had a brief introduction to the template loading process used by WordPress. In the next section, we are going to look at the template loading process of a typical web development framework to identify the differences. Template execution process of web application frameworks Most stable web application frameworks use a flat and straightforward template execution process compared to the extensive process used by WordPress. These frameworks don't come with built-in templates, and hence each and every template will be generated from scratch. Consider the following diagram of a typical template execution process: In this process, Initial Request always comes to the index.php file, which is similar to the process used by WordPress or any other framework. It then looks for custom routes defined within the framework. It's possible to use custom routes within a WordPress context, even though it's not used generally for websites or blogs. Finally, Initial Request looks for the direct template file located in the templates section of the framework. As you can see, the process of a normal framework has very limited depth and specialized templates. Keep in mind that index.php referred to in the preceding section is the file used as the main starting point of the application, not the template file. In WordPress, we have a specific template file named index.php located inside the themes folder as well. Managing templates in a typical application framework is a relatively easy task when compared to the extensive template hierarchy used by WordPress. In web applications, it's ideal to keep the template hierarchy as flat as possible with specific templates targeted towards each and every screen. In general, WordPress developers tend to add custom functionalities and features by using specific templates within the hierarchy. Having multiple templates for a single screen and identifying the order of execution can be a difficult task in large-scale applications, and hence should be avoided in every possible instance. Web application layout creation techniques As we move into developing web applications, the logic and screens will become complex, resulting in the need of custom templates beyond the conventional ones. There is a wide range of techniques for putting such functionality into the WordPress code. Each of these techniques have their own pros and cons. Choosing the appropriate technique is vital in avoiding potential bottlenecks in large-scale applications. Here is a list of techniques for creating dynamic content within WordPress applications: Static pages with shortcodes Page templates Custom templates with custom routing Summary In this article we learned about basic file structure of the WordPress theme, the template execution hierarchy, and template execution process. We also learned the different techniques of Web application layout creation. Resources for Article: Further resources on this subject: Customizing WordPress Settings for SEO [Article] Getting Started with WordPress 3 [Article] Dynamic Menus in WordPress [Article]
Read more
  • 0
  • 0
  • 3463

article-image-advanced-data-access-patterns
Packt
11 Aug 2015
25 min read
Save for later

Advanced Data Access Patterns

Packt
11 Aug 2015
25 min read
In this article by, Suhas Chatekar, author of the book Learning NHibernate 4, we would dig deeper into that statement and try to understand what those downsides are and what can be done about them. In our attempt to address the downsides of repository, we would present two data access patterns, namely specification pattern and query object pattern. Specification pattern is a pattern adopted into data access layer from a general purpose pattern used for effectively filtering in-memory data. Before we begin, let me reiterate – repository pattern is not bad or wrong choice in every situation. If you are building a small and simple application involving a handful of entities then repository pattern can serve you well. But if you are building complex domain logic with intricate database interaction then repository may not do justice to your code. The patterns presented can be used in both simple and complex applications, and if you feel that repository is doing the job perfectly then there is no need to move away from it. (For more resources related to this topic, see here.) Problems with repository pattern A lot has been written all over the Internet about what is wrong with repository pattern. A simple Google search would give you lot of interesting articles to read and ponder about. We would spend some time trying to understand problems introduced by repository pattern. Generalization FindAll takes name of the employee as input along with some other parameters required for performing the search. When we started putting together a repository, we said that Repository<T> is a common repository class that can be used for any entity. But now FindAll takes a parameter that is only available on Employee, thus locking the implementation of FindAll to the Employee entity only. In order to keep the repository still reusable by other entities, we would need to part ways from the common Repository<T> class and implement a more specific EmployeeRepository class with Employee specific querying methods. This fixes the immediate problem but introduces another one. The new EmployeeRepository breaks the contract offered by IRepository<T> as the FindAll method cannot be pushed on the IRepository<T> interface. We would need to add a new interface IEmployeeRepository. Do you notice where this is going? You would end up implementing lot of repository classes with complex inheritance relationships between them. While this may seem to work, I have experienced that there are better ways of solving this problem. Unclear and confusing contract What happens if there is a need to query employees by a different criteria for a different business requirement? Say, we now need to fetch a single Employee instance by its employee number. Even if we ignore the above issue and be ready to add a repository class per entity, we would need to add a method that is specific to fetching the Employee instance matching the employee number. This adds another dimension to the code maintenance problem. Imagine how many such methods we would end up adding for a complex domain every time someone needs to query an entity using a new criteria. With several methods on repository contract that query same entity using different criteria makes the contract less clear and confusing for new developers. Such a pattern also makes it difficult to reuse code even if two methods are only slightly different from each other. Leaky abstraction In order to make methods on repositories reusable in different situations, lot of developers tend to add a single method on repository that does not take any input and return an IQueryable<T> by calling ISession.Query<T> inside it, as shown next: public IQueryable<T> FindAll() {    return session.Query<T>(); } IQueryable<T> returned by this method can then be used to construct any query that you want outside of repository. This is a classic case of leaky abstraction. Repository is supposed to abstract away any concerns around querying the database, but now what we are doing here is returning an IQueryable<T> to the consuming code and asking it to build the queries, thus leaking the abstraction that is supposed to be hidden into repository. IQueryable<T> returned by the preceding method holds an instance of ISession that would be used to ultimately interact with database. Since repository has no control over how and when this IQueryable would invoke database interaction, you might get in trouble. If you are using "session per request" kind of pattern then you are safeguarded against it but if you are not using that pattern for any reason then you need to watch out for errors due to closed or disposed session objects. God object anti-pattern A god object is an object that does too many things. Sometimes, there is a single class in an application that does everything. Such an implementation is almost always bad as it majorly breaks the famous single responsibility principle (SRP) and reduces testability and maintainability of code. A lot can be written about SRP and god object anti-pattern but since it is not the primary topic, I would leave the topic with underscoring the importance of staying away from god object anti-pattern. Avid readers can Google on the topic if they are interested. Repositories by nature tend to become single point of database interaction. Any new database interaction goes through repository. Over time, repositories grow organically with large number of methods doing too many things. You may spot the anti-pattern and decide to break the repository into multiple small repositories but the original single repository would be tightly integrated with your code in so many places that splitting it would be a difficult job. For a contained and trivial domain model, repository pattern can be a good choice. So do not abandon repositories entirely. It is around complex and changing domain that repositories start exhibiting the problems just discussed. You might still argue that repository is an unneeded abstraction and we can very well use NHibernate directly for a trivial domain model. But I would caution against any design that uses NHibernate directly from domain or domain services layer. No matter what design I use for data access, I would always adhere to "explicitly declare capabilities required" principle. The abstraction that offers required capability can be a repository interface or some other abstractions that we would learn. Specification pattern Specification pattern is a reusable and object-oriented way of applying business rules on domain entities. The primary use of specification pattern is to select subset of entities from a larger collection of entities based on some rules. An important characteristic of specification pattern is combining multiple rules by chaining them together. Specification pattern was in existence before ORMs and other data access patterns had set their feet in the development community. The original form of specification pattern dealt with in-memory collections of entities. The pattern was then adopted to work with ORMs such as NHibernate as people started seeing the benefits that specification pattern could bring about. We would first discuss specification pattern in its original form. That would give us a good understanding of the pattern. We would then modify the implementation to make it fit with NHibernate. Specification pattern in its original form Let's look into an example of specification pattern in its original form. A specification defines a rule that must be satisfied by domain objects. This can be generalized using an interface definition, as follows: public interface ISpecification<T> { bool IsSatisfiedBy(T entity); } ISpecification<T> defines a single method IsSatisifedBy. This method takes the entity instance of type T as input and returns a Boolean value depending on whether the entity passed satisfies the rule or not. If we were to write a rule for employees living in London then we can implement a specification as follows: public class EmployeesLivingIn : ISpecification<Employee> { public bool IsSatisfiedBy(Employee entity) {    return entity.ResidentialAddress.City == "London"; } } The EmployeesLivingIn class implements ISpecification<Employee> telling us that this is a specification for the Employee entity. This specification compares the city from the employee's ResidentialAddress property with literal string "London" and returns true if it matches. You may be wondering why I have named this class as EmployeesLivingIn. Well, I had some refactoring in mind and I wanted to make my final code read nicely. Let's see what I mean. We have hardcoded literal string "London" in the preceding specification. This effectively stops this class from being reusable. What if we need a specification for all employees living in Paris? Ideal thing to do would be to accept "London" as a parameter during instantiation of this class and then use that parameter value in the implementation of the IsSatisfiedBy method. Following code listing shows the modified code: public class EmployeesLivingIn : ISpecification<Employee> { private readonly string city;   public EmployeesLivingIn(string city) {    this.city = city; }   public bool IsSatisfiedBy(Employee entity) {    return entity.ResidentialAddress.City == city; } } This looks good without any hardcoded string literals. Now if I wanted my original specification for employees living in London then following is how I could build it: var specification = new EmployeesLivingIn("London"); Did you notice how the preceding code reads in plain English because of the way class is named? Now, let's see how to use this specification class. Usual scenario where specifications are used is when you have got a list of entities that you are working with and you want to run a rule and find out which of the entities in the list satisfy that rule. Following code listing shows a very simple use of the specification we just implemented: List<Employee> employees = //Loaded from somewhere List<Employee> employeesLivingInLondon = new List<Employee>(); var specification = new EmployeesLivingIn("London");   foreach(var employee in employees) { if(specification.IsSatisfiedBy(employee)) {    employeesLivingInLondon.Add(employee); } } We have a list of employees loaded from somewhere and we want to filter this list and get another list comprising of employees living in London. Till this point, the only benefit we have had from specification pattern is that we have managed to encapsulate the rule into a specification class which can be reused anywhere now. For complex rules, this can be very useful. But for simple rules, specification pattern may look like lot of plumbing code unless we overlook the composability of specifications. Most power of specification pattern comes from ability to chain multiple rules together to form a complex rule. Let's write another specification for employees who have opted for any benefit: public class EmployeesHavingOptedForBenefits : ISpecification<Employee> { public bool IsSatisfiedBy(Employee entity) {    return entity.Benefits.Count > 0; } } In this rule, there is no need to supply any literal value from outside so the implementation is quite simple. We just check if the Benefits collection on the passed employee instance has count greater than zero. You can use this specification in exactly the same way as earlier specification was used. Now if there is a need to apply both of these specifications to an employee collection, then very little modification to our code is needed. Let's start with adding an And method to the ISpecification<T> interface, as shown next: public interface ISpecification<T> { bool IsSatisfiedBy(T entity); ISpecification<T> And(ISpecification<T> specification); } The And method accepts an instance of ISpecification<T> and returns another instance of the same type. As you would have guessed, the specification that is returned from the And method would effectively perform a logical AND operation between the specification on which the And method is invoked and specification that is passed into the And method. The actual implementation of the And method comes down to calling the IsSatisfiedBy method on both the specification objects and logically ANDing their results. Since this logic does not change from specification to specification, we can introduce a base class that implements this logic. All specification implementations can then derive from this new base class. Following is the code for the base class: public abstract class Specification<T> : ISpecification<T> { public abstract bool IsSatisfiedBy(T entity);   public ISpecification<T> And(ISpecification<T> specification) {    return new AndSpecification<T>(this, specification); } } We have marked Specification<T> as abstract as this class does not represent any meaningful business specification and hence we do not want anyone to inadvertently use this class directly. Accordingly, the IsSatisfiedBy method is marked abstract as well. In the implementation of the And method, we are instantiating a new class AndSepcification. This class takes two specification objects as inputs. We pass the current instance and one that is passed to the And method. The definition of AndSpecification is very simple. public class AndSpecification<T> : Specification<T> { private readonly Specification<T> specification1; private readonly ISpecification<T> specification2;   public AndSpecification(Specification<T> specification1, ISpecification<T> specification2) {    this.specification1 = specification1;    this.specification2 = specification2; }   public override bool IsSatisfiedBy(T entity) {    return specification1.IsSatisfiedBy(entity) &&    specification2.IsSatisfiedBy(entity); } } AndSpecification<T> inherits from abstract class Specification<T> which is obvious. IsSatisfiedBy is simply performing a logical AND operation on the outputs of the ISatisfiedBy method on each of the specification objects passed into AndSpecification<T>. After we change our previous two business specification implementations to inherit from abstract class Specification<T> instead of interface ISpecification<T>, following is how we can chain two specifications using the And method that we just introduced: List<Employee> employees = null; //= Load from somewhere List<Employee> employeesLivingInLondon = new List<Employee>(); var specification = new EmployeesLivingIn("London")                                     .And(new EmployeesHavingOptedForBenefits());   foreach (var employee in employees) { if (specification.IsSatisfiedBy(employee)) {    employeesLivingInLondon.Add(employee); } } There is literally nothing changed in how the specification is used in business logic. The only thing that is changed is construction and chaining together of two specifications as depicted in bold previously. We can go on and implement other chaining methods but point to take home here is composability that the specification pattern offers. Now let's look into how specification pattern sits beside NHibernate and helps in fixing some of pain points of repository pattern. Specification pattern for NHibernate Fundamental difference between original specification pattern and the pattern applied to NHibernate is that we had an in-memory list of objects to work with in the former case. In case of NHibernate we do not have the list of objects in the memory. We have got the list in the database and we want to be able to specify rules that can be used to generate appropriate SQL to fetch the records from database that satisfy the rule. Owing to this difference, we cannot use the original specification pattern as is when we are working with NHibernate. Let me show you what this means when it comes to writing code that makes use of specification pattern. A query, in its most basic form, to retrieve all employees living in London would look something as follows: var employees = session.Query<Employee>()                .Where(e => e.ResidentialAddress.City == "London"); The lambda expression passed to the Where method is our rule. We want all the Employee instances from database that satisfy this rule. We want to be able to push this rule behind some kind of abstraction such as ISpecification<T> so that this rule can be reused. We would need a method on ISpecification<T> that does not take any input (there are no entities in-memory to pass) and returns a lambda expression that can be passed into the Where method. Following is how that method could look: public interface ISpecification<T> where T : EntityBase<T> { Expression<Func<T, bool>> IsSatisfied(); } Note the differences from the previous version. We have changed the method name from IsSatisfiedBy to IsSatisfied as there is no entity being passed into this method that would warrant use of word By in the end. This method returns an Expression<Fund<T, bool>>. If you have dealt with situations where you pass lambda expressions around then you know what this type means. If you are new to expression trees, let me give you a brief explanation. Func<T, bool> is a usual function pointer. This pointer specifically points to a function that takes an instance of type T as input and returns a Boolean output. Expression<Func<T, bool>> takes this function pointer and converts it into a lambda expression. An implementation of this new interface would make things more clear. Next code listing shows the specification for employees living in London written against the new contract: public class EmployeesLivingIn : ISpecification<Employee> { private readonly string city;   public EmployeesLivingIn(string city) {    this.city = city; }   public override Expression<Func<Employee, bool>> IsSatisfied() {    return e => e.ResidentialAddress.City == city; } } There is not much changed here compared to the previous implementation. Definition of IsSatisfied now returns a lambda expression instead of a bool. This lambda is exactly same as the one we used in the ISession example. If I had to rewrite that example using the preceding specification then following is how that would look: var specification = new EmployeeLivingIn("London"); var employees = session.Query<Employee>()                .Where(specification.IsSatisfied()); We now have a specification wrapped in a reusable object that we can send straight to NHibernate's ISession interface. Now let's think about how we can use this from within domain services where we used repositories before. We do not want to reference ISession or any other NHibernate type from domain services as that would break onion architecture. We have two options. We can declare a new capability that can take a specification and execute it against the ISession interface. We can then make domain service classes take a dependency on this new capability. Or we can use the existing IRepository capability and add a method on it which takes the specification and executes it. We started this article with a statement that repositories have a downside, specifically when it comes to querying entities using different criteria. But now we are considering an option to enrich the repositories with specifications. Is that contradictory? Remember that one of the problems with repository was that every time there is a new criterion to query an entity, we needed a new method on repository. Specification pattern fixes that problem. Specification pattern has taken the criterion out of the repository and moved it into its own class so we only ever need a single method on repository that takes in ISpecification<T> and execute it. So using repository is not as bad as it sounds. Following is how the new method on repository interface would look: public interface IRepository<T> where T : EntityBase<T> { void Save(T entity); void Update(int id, Employee employee); T GetById(int id); IEnumerable<T> Apply(ISpecification<T> specification); } The Apply method in bold is the new method that works with specification now. Note that we have removed all other methods that ran various different queries and replaced them with this new method. Methods to save and update the entities are still there. Even the method GetById is there as the mechanism used to get entity by ID is not same as the one used by specifications. So we retain that method. One thing I have experimented with in some projects is to split read operations from write operations. The IRepository interface represents something that is capable of both reading from the database and writing to database. Sometimes, we only need a capability to read from database, in which case, IRepository looks like an unnecessarily heavy object with capabilities we do not need. In such a situation, declaring a new capability to execute specification makes more sense. I would leave the actual code for this as a self-exercise for our readers. Specification chaining In the original implementation of specification pattern, chaining was simply a matter of carrying out logical AND between the outputs of the IsSatisfiedBy method on the specification objects involved in chaining. In case of NHibernate adopted version of specification pattern, the end result boils down to the same but actual implementation is slightly more complex than just ANDing the results. Similar to original specification pattern, we would need an abstract base class Specification<T> and a specialized AndSepcificatin<T> class. I would just skip these details. Let's go straight into the implementation of the IsSatisifed method on AndSpecification where actual logical ANDing happens. public override Expression<Func<T, bool>> IsSatisfied() { var p = Expression.Parameter(typeof(T), "arg1"); return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(          Expression.Invoke(specification1.IsSatisfied(), p),          Expression.Invoke(specification2.IsSatisfied(), p)), p); } Logical ANDing of two lambda expression is not a straightforward operation. We need to make use of static methods available on helper class System.Linq.Expressions.Expression. Let's try to go from inside out. That way it is easier to understand what is happening here. Following is the reproduction of innermost call to the Expression class: Expression.Invoke(specification1.IsSatisfied(), parameterName) In the preceding code, we are calling the Invoke method on the Expression class by passing the output of the IsSatisfied method on the first specification. Second parameter passed to this method is a temporary parameter of type T that we created to satisfy the method signature of Invoke. The Invoke method returns an InvocationExpression which represents the invocation of the lambda expression that was used to construct it. Note that actual lambda expression is not invoked yet. We do the same with second specification in question. Outputs of both these operations are then passed into another method on the Expression class as follows: Expression.AndAlso( Expression.Invoke(specification1.IsSatisfied(), parameterName), Expression.Invoke(specification2.IsSatisfied(), parameterName) ) Expression.AndAlso takes the output from both specification objects in the form of InvocationExpression type and builds a special type called BinaryExpression which represents a logical AND between the two expressions that were passed to it. Next we convert this BinaryExpression into an Expression<Func<T, bool>> by passing it to the Expression.Lambda<Func<T, bool>> method. This explanation is not very easy to follow and if you have never used, built, or modified lambda expressions programmatically like this before, then you would find it very hard to follow. In that case, I would recommend not bothering yourself too much with this. Following code snippet shows how logical ORing of two specifications can be implemented. Note that the code snippet only shows the implementation of the IsSatisfied method. public override Expression<Func<T, bool>> IsSatisfied() { var parameterName = Expression.Parameter(typeof(T), "arg1"); return Expression.Lambda<Func<T, bool>>(Expression.OrElse( Expression.Invoke(specification1.IsSatisfied(), parameterName), Expression.Invoke(specification2.IsSatisfied(), parameterName)), parameterName); } Rest of the infrastructure around chaining is exactly same as the one presented during discussion of original specification pattern. I have avoided giving full class definitions here to save space but you can download the code to look at complete implementation. That brings us to end of specification pattern. Though specification pattern is a great leap forward from where repository left us, it does have some limitations of its own. Next, we would look into what these limitations are. Limitations Specification pattern is great and unlike repository pattern, I am not going to tell you that it has some downsides and you should try to avoid it. You should not. You should absolutely use it wherever it fits. I would only like to highlight two limitations of specification pattern. Specification pattern only works with lambda expressions. You cannot use LINQ syntax. There may be times when you would prefer LINQ syntax over lambda expressions. One such situation is when you want to go for theta joins which are not possible with lambda expressions. Another situation is when lambda expressions do not generate optimal SQL. I will show you a quick example to understand this better. Suppose we want to write a specification for employees who have opted for season ticket loan benefit. Following code listing shows how that specification could be written: public class EmployeeHavingTakenSeasonTicketLoanSepcification :Specification<Employee> { public override Expression<Func<Employee, bool>> IsSatisfied() {    return e => e.Benefits.Any(b => b is SeasonTicketLoan); } } It is a very simple specification. Note the use of Any to iterate over the Benefits collection to check if any of the Benefit in that collection is of type SeasonTicketLoan. Following SQL is generated when the preceding specification is run: SELECT employee0_.Id           AS Id0_,        employee0_.Firstname     AS Firstname0_,        employee0_.Lastname     AS Lastname0_,        employee0_.EmailAddress AS EmailAdd5_0_,        employee0_.DateOfBirth   AS DateOfBi6_0_,        employee0_.DateOfJoining AS DateOfJo7_0_,        employee0_.IsAdmin       AS IsAdmin0_,        employee0_.Password     AS Password0_ FROM   Employee employee0_ WHERE EXISTS (SELECT benefits1_.Id FROM   Benefit benefits1_ LEFT OUTER JOIN Leave benefits1_1_ ON benefits1_.Id = benefits1_1_.Id LEFT OUTER JOIN SkillsEnhancementAllowance benefits1_2_ ON benefits1_.Id = benefits1_2_.Id LEFT OUTER JOIN SeasonTicketLoan benefits1_3_ ON benefits1_.Id = benefits1_3_.Id WHERE employee0_.Id = benefits1_.Employee_Id AND CASE WHEN benefits1_1_.Id IS NOT NULL THEN 1      WHEN benefits1_2_.Id IS NOT NULL THEN 2      WHEN benefits1_3_.Id IS NOT NULL THEN 3       WHEN benefits1_.Id IS NOT NULL THEN 0      END = 3) Isn't that SQL too complex? It is not only complex on your eyes but this is not how I would have written the needed SQL in absence of NHibernate. I would have just inner-joined the Employee, Benefit, and SeasonTicketLoan tables to get the records I need. On large databases, the preceding query may be too slow. There are some other such situations where queries written using lambda expressions tend to generate complex or not so optimal SQL. If we use LINQ syntax instead of lambda expressions, then we can get NHibernate to generate just the SQL. Unfortunately, there is no way of fixing this with specification pattern. Summary Repository pattern has been around for long time but suffers through some issues. General nature of its implementation comes in the way of extending repository pattern to use it with complex domain models involving large number of entities. Repository contract can be limiting and confusing when there is a need to write complex and very specific queries. Trying to fix these issues with repositories may result in leaky abstraction which can bite us later. Moreover, repositories maintained with less care have a tendency to grow into god objects and maintaining them beyond that point becomes a challenge. Specification pattern and query object pattern solve these issues on the read side of the things. Different applications have different data access requirements. Some applications are write-heavy while others are read-heavy. But there are a minute number of applications that fit into former category. A large number of applications developed these days are read-heavy. I have worked on applications that involved more than 90 percent database operations that queried data and only less than 10 percent operations that actually inserted/updated data into database. Having this knowledge about the application you are developing can be very useful in determining how you are going to design your data access layer. That brings use to the end of our NHibernate journey. Not quite, but yes, in a way. Resources for Article: Further resources on this subject: NHibernate 3: Creating a Sample Application [article] NHibernate 3.0: Using LINQ Specifications in the data access layer [article] NHibernate 2: Mapping relationships and Fluent Mapping [article]
Read more
  • 0
  • 0
  • 3462

article-image-jquery-14-dom-manipulation-methods-style-properties-and-class-attributes
Packt
19 Feb 2010
3 min read
Save for later

jQuery 1.4 DOM Manipulation Methods for Style Properties and Class Attributes

Packt
19 Feb 2010
3 min read
General attributes These methods get and set DOM attributes of elements. .attr() (getter) Get the value of an attribute for the first element in the set of matched elements. .attr(attributeName) Parameters attributeName: The name of the attribute to get Return value A string containing the attribute value. Description It's important to note that the .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, we need to rely on a looping construct such as jQuery's .each() method. Using jQuery's .attr() method to get the value of an element's attribute has two main benefits: Convenience: It can be called directly on a jQuery object and chained to other jQuery methods. Cross-browser consistency: Some attributes have inconsistent naming from browser to browser. Furthermore, the values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies. .attr() (setter) Set one or more attributes for the set of matched elements. .attr(attributeName, value).attr(map).attr(attributeName, function) Parameters (first version) attributeName: The name of the attribute to set value: A value to set for the attribute Parameters (second version) map: A map of attribute-value pairs to set Parameters (third version) attributeName: The name of the attribute to set function: A function returning the value to set Return value The jQuery object, for chaining purposes. Description The .attr() method is a convenient and powerful way to set the value of attributes, especially when setting multiple attributes or using values returned by a function. Let's consider the following image: <img id="greatphoto" src="brush-seller.jpg" alt="brush seller" /> Setting a simple attribute We can change the alt attribute by simply passing the name of the attribute and its new value to the .attr() method. $('#greatphoto').attr('alt', 'Beijing Brush Seller'); We can add an attribute the same way. $('#greatphoto').attr('title', 'Photo by Kelly Clark'); Setting several attributes at once To change the alt attribute and add the title attribute at the same time, we can pass both sets of names and values into the method at once using a map (JavaScript object literal). Each key-value pair in the map adds or modifies an attribute: $('#greatphoto').attr({alt: 'Beijing Brush Seller',title: 'photo by Kelly Clark'}); When setting multiple attributes, the quotation marks around attribute names are optional. Computed attribute values By using a function to set attributes, we can compute the value based on other properties of the element. For example, we could concatenate a new value with an existing value as follows: $('#greatphoto').attr('title', function() { return this.alt + ' – photo by Kelly Clark'}); This use of a function to compute attribute values can be particularly useful when we modify the attributes of multiple elements at once. .removeAttr() Remove an attribute from each element in the set of matched elements. .removeAttr(attributeName).removeAttr(function) Parameters (first version) attributeName: An attribute to remove Parameters (second version) function: A function returning the attribute to remove Return value The jQuery object, for chaining purposes. Description The .removeAttr() method uses the JavaScript removeAttribute() function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers. As of jQuery 1.4, the .removeAttr() function allows us to indicate the attribute to be removed by passing in a function.
Read more
  • 0
  • 0
  • 3462
article-image-ordered-and-generic-tests-visual-studio-2010
Packt
30 Nov 2010
5 min read
Save for later

Ordered and Generic Tests in Visual Studio 2010

Packt
30 Nov 2010
5 min read
  Software Testing using Visual Studio 2010 Ordered tests The following screenshot shows the list of all the tests. You can see that the tests are independent and there is no link between the tests. We have different types of tests like Unit Test, Web Performance Test, and Load Test under the test project. Let's try to create an ordered test and place some of the dependent tests in an order so that the test execution happens in an order without breaking. Creating an ordered test There are different ways of creating ordered tests similar to the other tests: Select the test project from Solution Explorer, right-click and select Add Ordered Test, and then select ordered test from the list of different types of tests. Save the ordered test by choosing the File | Save option. Select the menu option Test then select New Test..., which opens a dialog with different test types. Select the test type and choose the test project from the Add to Test Project List drop-down and click on OK. Now the ordered test is created under the test project and the ordered test window is shown to select the existing tests from the test project and set the order. The preceding window shows different options for ordering the tests. The first line is the status bar, which shows the number of tests selected for the ordered test. The Select test list to view dropdown has the option to choose the display of tests in the available Test Lists. This dropdown has the default All Loaded Tests, which displays all available tests under the project. The other options in the dropdown are Lists of Tests and Tests Not in a List. The List of Tests will display the test lists created using the Test List Editor. It is easier to include the number of tests grouped together and order them. The next option, Tests Not in a List, displays the available tests, which are not part of any Test Lists. The Available tests list displays all the tests from the test project based on the option chosen in the dropdown. Selected tests contains the tests that are selected from the available tests list to be placed in order. The two right and left arrows are used for selecting and unselecting the tests from the Available tests list to the Selected Tests list. We can also select multiple tests by pressing the Ctrl key and selecting the tests. The up-down arrows on the right of the selected tests list are used for moving up or down the tests and setting the order for the testing in the Selected tests list. The last option, the Continue after failure checkbox at the bottom of the window, is to override the default behavior of the ordered tests, aborting the execution after the failure of any test. If the option Continue after failure is unchecked, and if any test in the order fails, then all remaining tests will get aborted. In case the tests are not dependent, we can check this option and override the default behavior to allow the application to continue running the remaining tests in order. Properties of an ordered test Ordered tests have properties similar to the other test types, in addition to some specific properties. To view the properties, select the ordered test in the Test View or Test List Editor window, right-click and select the Properties option. The Properties dialog box displays the available properties for the ordered test. The preceding screenshot shows that most of the properties are the same as the properties of the other test types. We can associate this test with the TFS work items, iterations, and area. Executing an ordered test An ordered test can be run like any other test. Open the Test View window or the Test List Editor and select the ordered test from the list, then right-click and choose the Run Selection option from Test View or Run Checked Tests from the Test List Editor. Once the option is selected, we can see the tests running one after the other in the same order in which they are placed in the ordered test. After the execution of the ordered tests, the Test Results window will show the status of the ordered test. If any of the tests in the list fails, then the ordered test status will be Failed. The summary of statuses of all the tests in the ordered test is shown in the following screenshot in the toolbar. The sample ordered test application had four tests in the ordered tests, but two of them failed and one had an error. Clicking the Test run failed hyperlink in the status bar shows a detailed view of the test run summary: The Test Results window also provides detailed information about the tests run so far. To get these details, choose the test from the Test Results window and then right-click and choose the option, View Test Results Details, which opens the details window and displays the common results information such as Test Name, Result, Duration of the test run, Start Time, End Time, and so on. The details window also displays the status of each and every test run within the ordered test. In addition it displays the duration for each test run, name, owner, and type of test in the list. Even though the second test in the list fails, the other tests continue to execute as if the Continue after failure option was checked.
Read more
  • 0
  • 0
  • 3462

article-image-this-week-on-packt-hub-18-may-2018
Aarthi Kumaraswamy
18 May 2018
3 min read
Save for later

This week on Packt Hub – 18 May 2018

Aarthi Kumaraswamy
18 May 2018
3 min read
We've just completely revamped our weekly newsletter. We'd love to hear from us on hub@packtpub.com. If you like what you see, make sure to subscribe and tell others too. Here’s what you may have missed in the last 7 days – Tech news, insights and tutorials… Featured interview “The wider use of generator functions in Python 3 has made functional Python programming much more common.” — Steven F. Lott We recently interviewed Steven F. Lott, a programmer since the 70s, a true Python professional and best-selling author of a number of Python books. In this interview, Steven talks a bit about modern Python and how the language adapts well to the Functional paradigm, offering developers a range of solutions to build modern, cloud-based applications. Tech news Conferences covered this week PyCon US 2018 Highlights: Quantum computing, blockchains, and serverless rule! What Google, RedHat, Oracle, and others announced at KubeCon + CloudNativeCon 2018 Data news in depth Shiny 1.1.0 releasing soon pandas 0.23 released Development & programming news in depth What can you expect from the upcoming Java 11 JDK? Android P new features: artificial intelligence, digital wellbeing, and simplicity Firefox 60 arrives with exciting updates for web developers: Quantum CSS engine, new Web APIs and more Unity announces a new automotive division and two-day Unity AutoTech Summit SteamVR introduces new controllers for game developers, the SteamVR Input system Amazon open sources Amazon Sumerian, its popular AR/VR app toolkit Introducing Fuse Open, Fuse App Engine and apps-as-a-service Barracuda announces Cloud-Delivered Web Application Firewall service Cloud & networking news in depth Google Compute Engine Plugin makes it easy to use Jenkins on Google Cloud Platform Introducing Intel’s OpenVINO computer vision toolkit for edge computing Rackspace now supports Kubernetes-as-a-Service Verizon chooses Amazon Web Services(AWS) as its preferred cloud provider Other News Google employees quit over company’s continued AI ties with the Pentagon Twitter’s disdain for third-party clients gets real Tutorials Data tutorials Building a Microsoft Power BI Data Model How to Build TensorFlow Models for Mobile and Embedded devices What does the structure of a data mining architecture look like? Getting started with Google Data Studio: An intuitive tool for visualizing BigQuery Data Development & programming tutorials Development tutorials Building a chat app with Kotlin using Node.js Is your web design responsive? How to use arrays, lists, and dictionaries in Unity for 3D game development How to create a generic reusable section for a single page based website How to use Bootstrap grid system for responsive website design? Programming tutorials How to work with classes in Typescript That ’70s language: AWK programming Regular expressions in AWK programming: What, Why, and How Other tutorials How to secure an Azure Virtual Network Tips and tricks for troubleshooting and flying drones safely This week’s opinions, analysis, and insights Data Insights What can Google Duplex do for businesses? 30 common data science terms explained Development & Programming Insights Top frameworks for building your Progressive Web Apps (PWA) What is a multi-layered software architecture? Other Insights 5 pen testing rules of engagement: What to consider while performing Penetration testing Cognitive IoT: How Artificial Intelligence is remolding Industrial and Consumer IoT What are lightweight Architecture Decision Records? BeyondCorp is transforming enterprise security Polycloud: a better alternative to cloud agnosticism  
Read more
  • 0
  • 0
  • 3461
Modal Close icon
Modal Close icon