text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
generator-react-webpack V2.0 Yeoman generator for ReactJS - lets you quickly set up a project including karma test runner and Webpack module system. 关于 Generator-React-Webpack will help you build new React projects using modern technologies. Out of the box it comes with support for: - Webpack - ES2015 via Babel-Loader - Different supported style languages (sass, scss, less, stylus) - Style transformations via PostCSS - Automatic code linting via esLint - Ability to unit test components via Karma and Mocha/Chai 修改到版本 2.0 This generator is written in ES2015. This means it is not compatible with node.js versions before 4.0. It also does NOT include support for Flux-Frameworks anymore. Instead, we will use it as a base for other generators to build upon. This will make the base generator easier to use and update. If you are interested, feel free to write your own generator and use generator-react-webpack as a base (via composition). If you have built a generator using generator-react-webpack, tell us and we will add a link to our README. 扩展于generator-react-webpack的生成器 - Generator-React-Webpack-Alt (Adds ability to create actions, stores and sources for alt.js) 安装 # Make sure both is installed globally npm install -g yo npm install -g generator-react-webpack 设置项目 # Create a new directory, and `cd` into it: mkdir my-new-project && cd my-new-project # Run the generator yo react-webpack Please make sure to edit your newly generated package.json file to set description, author information and the like. 生成新组件 # After setup of course :) # cd my-new-project yo react-webpack:component my/namespaced/components/name The above command will create a new component, as well as its stylesheet and a basic testcase. 生成新的无状态的功能组件 yo react-webpack:component my/namespaced/components/name --stateless Stateless functional components where introduced in React v0.14. They have a much shorter syntax than regular ones and no state or lifecycle methods at all. Please read the React 0.14 release notes to get more information about those components. Note: You will still be able to set properties for stateless components! 添加 PostCSS 插件 If you have enabled PostCSS at generation time, install your PostCSS plugins via npm and require it in postcss function in cfg/base.js. Example for autoprefixer: cd my-new-project npm install autoprefixer Require in cfg/base.js ... postcss: function () { return [ require('autoprefixer')({ browsers: ['last 2 versions', 'ie >= 8'] }) ]; } ... 使用 项目中可用以下命令: # Start for development npm start # or npm run serve # Start the dev-server with the dist version npm run serve:dist # Just build the dist version and copy static files npm run dist # Run unit tests npm test # Lint all files in src (also automatically done AFTER tests are run) npm run lint # Clean up the dist directory npm run clean # Just copy the static assets npm run copy 命名组件 We have opted to follow @floydophone convention of uppercase for component file naming e.g. Component.js. I am open to suggestions if there is a general objection to this decision. 模块 Each component is a module and can be required using the Webpack module system. Webpack uses Loaders which means you can also require CSS and a host of other file types. Read the Webpack documentation to find out more. 属性 Thanks to Edd Hannay for his Webpack optimisations, my local merge and testing meant his additions lost his signature (my fault, sorry). So, big thanks Edd. 贡献 Contributions are welcomed. When submitting a bugfix, write a test that exposes the bug and fails before applying your fix. Submit the test alongside the fix. 运行测试 npm test or node node_modules/.bin/mocha
https://wohugb.gitbooks.io/react-webpack-cookbook/content/generator-react-webpack.html
CC-MAIN-2021-04
refinedweb
610
54.93
Something missing or incorrect? This article's source is on Github. Please feel free to open an issue or send a PR. Table of Contents - Introduction - Reasons to use Vue and Laravel together - Common gotchas when using Vue and Laravel together - Blade and Vue interpolation syntax - Passing PHP variables as Vue component props - Laravel router and vue-router - Lack of Webpack aliases when using Laravel Mix - Thanks and good bye Introduction Recently the excellent Vue Community guide was released. A guide on all things Vue - written for the Vue community, by the Vue community. This article's stuture will mirror exactly the layout of the Laravel section of the Vue Community guide, heading for heading. The intent is to provide a living resource (i.e. it will be updated over time if/when necessary) that goes into far greater detail (including code samples/demos) than the guide (which is intended to be more concise and easier to digest). Reasons to use Vue and Laravel together Scaffolded by default A default install of Laravel has everything you need to begin enhancing your server-rendered (Blade) templates with Vue components. No setup necessary. After having created a Laravel project, you'll be provided with: bootstrap.js: - loads some libraries such as lodash, axios and Popper - configures axios for CSRF app.js: - makes Vue globally available - registers the ExampleComponent.vue - provides example code on how to automatically register Vue components - initialises Vue ExampleComponent.vue: You are of course free to customise these files to your needs such as by removing unneeded/unwanted libraries. Laravel Mix Laravel Mix--a fluid API on top of Webpack, also included in the box--takes much of the pain out of asset compiling for you, so you can focus on authoring your Vue components. You simply need to run npm run watch and then you can get straight to work on writing your Vue components! It's not quite @vue/cli-levels of awesome but it's actually a really nice library and I do recommend it. It's also not at all tied to Laravel in any way- you can use it in any project. Widespread community adoption Several prominent members of the Laravel community are proponents of Vue (and its ecosystem). This includes but is not limited to: - Taylor Otwell - Founder (and Benevolent Dictator for Life) of Laravel itself - Known user of Laravel and Vue - Adam Wathan - Author of TailwindCSS - Creator of the Advanced Vue Component Design course - Known user of Laravel and Vue - Jeffrey Way - Author of Laravel Testing Decoded - Reoccuring speaker at Laracon - Creator of several Laravel/Vue courses - Known user of Laravel and Vue This advocacy and support of Vue, as far as I can tell, extends to the Laravel community as a whole, meaning that a majority of Laravel developers will likely be more comfortable and familiar with Vue than say React or Angular. Naturally, then, it follows that there will be: - more resources to help you learn (guides, tutorials, articles) - more people who have experience with Vue+Laravel (help, support, guidance) - in general a healthy ecosystem (plugins, boilerplates, etc.) Common gotchas when using Vue and Laravel together Blade and Vue interpolation syntax As you may be aware both Blade templates and Vue templates use moustache syntax (i.e. {{ message }}) for variable interpolation, which presents a problem. Fortunately the solution is simple - just prepend an @ to the moustache statement. This will instruct the Blade template rendering engine to ignore this statement, leaving it to be later processed by Vue. <p>You have @{{ messageCount }} new message(s).</p> If you need to escape several moustache statements, you may instead use the @verbatim directive. @verbatim <div class="container"> <p>Welcome {{ user.name }} ({{ user.id }})!</p> <p>Your last visit was: {{ user.lastVisit }}.</p> </div> @endverbatim Passing PHP variables as Vue component props If you ever need to pass a Blade variable as a prop into a Vue component from within a Blade template then you may be tempted to reach for json_encode however you should instead use the @json directive: <user-profile : Laravel router and vue-router You can absolutely use Laravel router and vue-router together without too much effort. Perhaps you want vue-router to handle all routing; or for it to handle only some and for Laravel to handle the others; or to serve multiple SPAs using one Laravel app. All of this and more is possible. Setting it all up NOTE: This section presumes a relatively basic understanding of Vue, vue-router, Laravel and the command line. The boilerplate provided by Laravel does not include vue-router but it won't be much trouble to set up. Install vue-router npm install vue-router --save Create a router instance and some routes Create resources/js/router.js: import Vue from "vue"; import VueRouter from "vue-router"; import PageHome from "./pages/Home"; import PageAbout from "./pages/About"; Vue.use(VueRouter); const router = new VueRouter({ mode: "history", routes: [ { path: "/", component: PageHome }, { path: "/about", component: PageAbout } ] }); export default router; Create a simple App component Create resources/js/components/App.vue: <template> <div> <nav> <ul> <li> <router-linkHome</router-link> </li> <li> <router-linkAbout</router-link> </li> </ul> </nav> <main> <router-view></router-view> </main> </div> </template> Create a few page components Create resources/js/pages/Home.vue: <template> <div>Home</div> </template> Create resources/js/pages/About.vue: <template> <div>About</div> </template> Configure the root Vue instance Modify resources/js/app.js: import router from "./router"; import App from "./components/App"; const app = new Vue({ el: '#app', router, // <-- register router with Vue render: (h) => h(App) // <-- render App component }); Configure the Laravel router This is the important part - we need to instruct Laravel to route all requests to the index action on the SPAController. Replace routes/web.php: <?php Route::get('/{vue}', 'SPAController@index')->where('vue', '.*'); NOTE: Any routes registered before this catch-all will still function. This is how we are able to handle some routes with Laravel and others with vue-router. Create the controller and action Create app/Http/Controllers/SPAController.php: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SPAController extends Controller { public function index() { return view("spa"); } } Create the view Create resources/views/spa.blade.php: <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="csrf-token" content="{{ csrf_token() }}" /> <title>Laravel + Vue = ❤️</title> <link href="{{ asset('css/app.css') }}" rel="stylesheet" /> </head> <body> <div id="app"></div> <script src="{{ asset('js/app.js') }}"></script> </body> </html> That's it! You are now serving a Vue SPA with Laravel and vue-router is in charge of all routing (except for any routes which were defined before the catch-all, which will be handled by Laravel!). Lack of Webpack aliases when using Laravel Mix If you've used vue-cli then you'll probably be familiar with (and used to using) aliases such as @ and ~. Unfortunately this is not setup by default. Fortunately for us - there's a plugin. Thanks and good bye Thanks for reading and enjoy developing with Laravel and Vue. Also, be sure to check out the new Vue Community. Something missing or incorrect? This article's source is on Github. Please feel free to open an issue or send a PR. Discussion (3) Please note that the PR that adds this to the Vue Community has not yet been merged. The PR is now merged. Great job!
https://dev.to/sustained/laravel-vue-4530
CC-MAIN-2021-49
refinedweb
1,250
53.71
Here we are, back at the blog again as promised. Admittedly, this is a week or so later then I had planned, but… best laid plans and of mice and men and all that. I’ll blame three straight weeks of travelling to visit with partners for the missed target. But all that aside, I am back to share something I’ve been thinking about blogging on for over a year. Namely Azure’s Notification Hub. Notification Hub has bounced around a bit. First it was under the Web Apps banner, then finally landed under the Service Bus brand. Regardless of which area it falls under, I think it’s a highly underappreciated service. Perhaps this will help change that perception in some small way. Overview In short, Notification hub is a way to centralize your notifications across multiple platforms. Its provides you with a single API interface from which you can send notifications to a myriad of platforms (iOS, Android, Kindle, Windows, etc…). In doing this, the service handles negotiations with the platform specific APIs and also helps deal with the various throttling limits that are in place for each. As if this weren’t enough, Event Hub (EH) also provides several higher level functions. Device Registry – a single location that you can use to store details and metadata about individual devices. The service monitor for and purge expired device registrations. Saving you from being kicked off the notification service of various providers. Templates – the capability to define templates that can be used to map a single message to different platforms and notification message formats. Tags – meta-data attributes that can be used to help you target the recipient(s) of a given message. Allowing you to target a single device, a group of devices, or all devices as you see fit. Each of these topics could be grounds for its own post or possibly even a series of posts. But today I’m interested in one specific topic, using NH to send notifications to a Windows 10 UWP (Universal Windows Platform) application written in HTML5/JS. To get this all to work, we have to perform the following steps: - Define the application in the Windows Store to and configure the Windows Notification Service (WNS) - Configure the Notification Hub to talk with the application’s WNS endpoint. - Have the app discover its “channel uri” which is used by the Windows Notification Service (WNS) to send notifications to the app. - Using that URI, ask the Notification Hub to a unique device ID - Using the device ID, register the device with the Notification Hub So let’s get to it… The Windows Store, WNS, and Notification Hub To do notifications, we need to start by setting up WNS, and this requires us to declare our application at Windows Dev Center: After logging in, click on “Dashboard” then select “Create a new app”. You’ll need to provide a name for your app (that must be unique) so it can be reserved for your use. With the app created we then click on “Services->Push notifications”. The app should already be configured for push notifications by default, but we need to get the credentials so we can configure the Notification Hub. In the first section on the Windows Push Notification Services, locate the “Live Service site” link in the second paragraph and click it. This routes you over to the app settings for the new app. We want to capture and record two values here, the Package SID and Client secret as shown below… Now we’ll switch over to the Azure Management Portal (classic) and create a new Notification Hub. Select the “+” at the bottom and do App Services -> Service Bus -> Notification Hub -> Quick Create. Provide a hub name, where its located, and a unique namespace for it. After a few minutes (even faster if you’re re-using an existing namespace), the hub will be created and ready for configuration. We’ll click on its “configure” tab and enter in the Package SID and Client Secret from above. Save this change, and switch back to the dashboard for the Notification Hub, and get its connection information for the DefaultFullSharedAccessSignature. This use of the “full” permissions, can be a security issue. But I’ll take more about that in the next section. With these steps done, we’ve declared a store application, created a Windows Notification Service endpoint for it, and associated the WNS with our Notification Hub. Its start to start building the app. The Solution Last time I worked with Notification Hub, was in September of 2014 with a Windows 8.1 app written in Angular. Since that time I’ve been actively trying to change my development habits and learn more JavaScript. So when another partner approach me about their HTML5/JavaScript application, I wanted to make another go at getting Notification Hub to work, this time with JavaScript. The challenge I soon found out was that we (Microsoft), still don’t have many materials available for building UWPs with JavaScript. I want to fix that. To that end I’m creating a GitHub repository where I’ll be putting my explorations in creating UWPs and hopefully others will either fork this effort and perhaps even contribute back to it. I’ll start with what I hope is a fairly solid Notification Hub example. I started by creating a Visual Studio 2015 solution that included a JavaScript Blank Universal Windows App, and a C# based ASP.NET Web API. Yeah, I know I said I’m trying to learn more about JavaScript, so I could have built the API in Node, but one battle at a time. I’m putting both in the same solution for convenience since I can then debug both side by side in the same VS instance. The reason I created two projects was simple, security. I could have let the application directly interact with the Notification Hub api. However, this would have required me to put the shared access key for the hub into the app itself. But by placing it into a server side API, it helps protect the key from being pulled out of the app and put into malicious use. The REST API With the solution in place, I started by building an API side first. I’ll create a single API controller that will have two methods. There will be a POST method that accepts a channel URI and returns a Notification Hub Device ID, and a PUT method that takes the Device ID and other values and registers it for notifications. You could put both these into a single operation. But there may be times where you just want to update the registration (say adding/updating a tag). So I prefer this two step process. We start by creating a model that will be used by the controller. This class will be used when the controller is activated to help initialize a Notification Hub client. The class looks like this.. public class Notifications { public static Notifications Instance = new Notifications(); public NotificationHubClient Hub { get; set; } private Notifications() { //get properties that have NH connection info string nhConnString = Properties.Settings.Default.NotificationHubConnectionString; string nhName = Properties.Settings.Default.NotificationHubName; // create a NH client Hub = NotificationHubClient.CreateClientFromConnectionString(nhConnString, nhName); } } You’ll note that this code depends on two settings. Right-click on the project and add those now. The ConnectionString value we captured when we set up the notification hub. And the hub name we specified when we set up the hub. For this code to compile, we also have to make sure we use nuget to add the Microsoft Azure Notification Hub package to our project and a couple of using clauses so that everything resolves properly. We’ll then add the controller that will contain our Notification Hub registration API. we start by adding a private NotificationHubClient variable and then populate this variable using the model we created earlier. public class RegisterController : ApiController { private NotificationHubClient hub; public RegisterController() { hub = Notifications.Instance.Hub; } } For the post method, I start by define the request object. I create an object that is my request payload, having a single parameter that is the “channel URI”. public class regGetRegistrationId { public string channeluri { get; set; } } With this, we can define the POST api method. This method will accept the channel URI (aka handle), and try to find an existing device ID for this URI in the Notification Hub device registry. If we find a match, we’ll return its device ID, and it not, we’ll create a new one. When checking existing devices, we do this in a loop to help make sure we don’t have multiple registrations using the same channel URI (which could result in the app getting the same notification multiple times). [HttpPost] [Route("api/register/")] public async Task<HttpResponseMessage> Post([FromBody]regGetRegistrationId request) { string newRegistrationId = null; string channelUri = request.channeluri; //todo: validate the URI is for notify.windows.com domain // make sure there are no existing registrations for the channel URI provided if (channelUri != null) { var registrations = await hub.GetRegistrationsByChannelAsync(channelUri, 100); foreach (RegistrationDescription registration in registrations) { if (newRegistrationId == null) { newRegistrationId = registration.RegistrationId; } else { await hub.DeleteRegistrationAsync(registration); } } } if (newRegistrationId == null) newRegistrationId = await hub.CreateRegistrationIdAsync(); return Request.CreateResponse(HttpStatusCode.OK, newRegistrationId); } Moving on to the PUT method for actually registering the device the app is running on, I again start by declaring my request payload/contract. This one has the device ID from the previous call, the platform we want to register with, the handle (in WNS, this is the Channel URI), and a set of tags that can be used for targeting notifications. public class DeviceRegistration { public string deviceid { get; set; } // the device ID public string platform { get; set; } // what platform, WNS, APNS, etc... public string handle { get; set; } // callback handle for the associated notification service public string[] tags { get; set; } // tags to be used in targetting notifications } Finally, we have the API method itself. It takes the payload, reformats the details into what’s needed for the Notification Hub SDK, and performs the registration. If the device is already registered, this would update/overlay the registration with new values. [HttpPut] [Route("api/register/")] public async Task<HttpResponseMessage> Put([FromBody]DeviceRegistration deviceUpdate) { RegistrationDescription registration = null; switch (deviceUpdate.platform.ToLower()) { case "mpns": registration = new MpnsRegistrationDescription(deviceUpdate.handle); break; case "wns": registration = new WindowsRegistrationDescription(deviceUpdate.handle); break; case "apns": registration = new AppleRegistrationDescription(deviceUpdate.handle); break; case "gcm": registration = new GcmRegistrationDescription(deviceUpdate.handle); break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } registration.RegistrationId = deviceUpdate.deviceid; registration.Tags = new HashSet<string>(deviceUpdate.tags); // optionally you could supplement/override the list of client supplied tags here // tags will help you target specific devices or groups of devices depending on your needs try { await hub.CreateOrUpdateRegistrationAsync(registration); } catch (MessagingException e) { //ReturnGoneIfHubResponseIsGone(e); } return Request.CreateResponse(HttpStatusCode.OK); } In this example, we’re taking whatever tags were handed to our API method. In reality, the API may handle this type of update. Perhaps designating specific tags based off of information about the user of the app, or settings the user has defined in the app itself. At this point, you could use a tool like Fiddler to test the API directly. You can monitor the notification hub dashboard in the Azure management portal to make sure operations are succeeding. There’s a bit of delay from when actions show up on the dashboard after being performed (seems like 5-10 minutes for the graph across the top, but an hour or so for the device registration count across the bottom). So don’t expect immediate results if you’re doing this type of testing. I’d suggest just firing off a couple REST requests to ensure your code doesn’t throw any obvious examples and then get back to coding up the rest of the app. The Client-Side JavaScript Code With the API in place, we can start working on the JavaScript side of things. The bulk of the code can be found in a stand-alone object I created called notification.js. This object has a single method named registration. Its a bit long, so we’ll look at it step by step. First up, we need to look to see if the app was run previously and saved its channel URI. // check and see if we have a saved ChannelURI var applicationData = Windows.Storage.ApplicationData.current; var localSettings = applicationData.localSettings; var savedChannelURI = localSettings.values["WNSChannelURI"]; //savedChannelURI = "re-register"; // uncomment this line to force re-registration every time the app runs Note the last line, if uncomment it can over-write whatever the saved value was. A channel URI can change and usually won’t last more than 30 days. So the recommendation is that you get it, and save it, and only re-register with the Notification hub if it changes. If you un-comment this line of code, you can run the app over and over again while testing/debugging your code. Just make sure you remove it after you’re done. Next, we’re going to get a new channel URI by using the Windows UWP API. // get current channel URI for notifications var pushNotifications = Windows.Networking.PushNotifications; var channelOperation = pushNotifications.PushNotificationChannelManager.createPushNotificationChannelForApplicationAsync(); // get current channel URI and check against saved URI channelOperation.then(function (newChannel) { return newChannel.uri; }).then(function (currentChannelURI) { // do stuff here! }).done(); This code sets up a Push Notification client and returns a promise for when the operation is complete, This returns the URI which is then passed to the “then” promise for additional operation. Its inside that promise that the real work is done. We start by checking to see if the channel URI we just received is any different then the one we have saved. if (!savedChannelURI || savedChannelURI.toLowerCase() != currentChannelURI.toLowerCase()) { And if not, we’ll start making our calls to our rest API, starting with the call to get a device ID // get a Notification Hub registration ID via the API WinJS.xhr({ type: "post", url: "", headers: { "Content-type": "application/x-www-form-urlencoded" }, responseType: "text", data: "channeluri=" + currentChannelURI.toLowerCase() }).then(function (getIdSuccess) { If this completes successful, inside of its “then” function, we set up the parameters for the call to the second API, passing it the device/registration ID we received back. // strip the double quotes off the string, we don't want those var deviceId = getIdSuccess.responseText.replace(/['"]/g, ''); console.log("Device ID is: " + deviceId); // create object for notification hub device registration // tag values used are arbitrary and could be supplemented by any // assigned on the server side var registrationpayload = { "deviceid" : deviceId, "platform" : "wns", "handle" : currentChannelURI, "tags" : ["tag1", "tag2"] }; Note that I’m stripping of the quotes that came at the beginning and end of my deviceId. I then use it and other values to construct the remainder of the PUT request payload. Which I can now call… // update the registration WinJS.xhr({ type: "put", url: "", headers: { "Content-type": "application/json" }, data: JSON.stringify(registrationpayload) }).then( function (registerSuccess) { console.log("Device successfully registered"); // save/update channel URI for next app launch localSettings.values["WNSChannelURI"] = currentChannelURI; }, function (error) { console.log(JSON.parse(error.responseText)); } ).done(); Its inside the “then” for this second call that I save the new URI for the next time the app launches. It should also be noted that I’m not really doing any error handling in these samples and that in a production quality app, you really should have a few retries in this (since it will fail if there’s no network connection). With this object and its method declared, we can now wire it up to the application. I put it in its own JavaScript file so it could be easily reused by another project, so we’ll want to add it to the default.html page of our new app. <!-- UWP___JavaScript references --> <link href="/css/default.css" rel="stylesheet" /> <!-- TAG: #notificationhubjs --> <script src="/js/notifications.js"></script> <!-- Notification Hub Integration --> <script src="/js/default.js"></script> Note hose this was inserted before the default.js file. This helps ensure that the object is available to default.js which is the entry point for my application. Inside the default.js we’ll add the code to access our new method. // TODO: This application has been newly launched. Initialize your application here. // TAG: #notificationhubjs uwpNotifications.registerChannelURI(); // register the app for notifications By placing this in the block of the default.js after the “newly launched” I’ll ensure this code is called when the app is launched, but not each time the app is resumed. Which is my intent. Now all that remains is to associate my app with the app I created in the store. Store Association and Testing Fortunately, since we’ve already registered our application with the store, visual studio makes this step really easy. Right-click on the UWP application in the solution explorer, and select Store -> Associate App with the Store. You’ll get walked through a wizard that will log you into the store and let you select an existing app, or create a new one. Select the app you created above, and associate it with your app. Note: If you are using a public repository such as GitHub, don’t check in your code after making the association. By associating the project with the store, you are altering the application manifest and adding in a file that contains store specific details. I recommend doing this final stage/testing in a separate branch to allow you to more easily merge back changes without bringing over those details. With this change done, we’re can run the app and test our notifications. Start by first launching the Web API in debug mode. I found it was easiest to set that project to my start-up project. Next, run the UWP application in debug mode. You’ll find you can set breakpoints in both apps and they’ll get hit. Which makes doing basic debugging of the code a lot easier. Once you know the app has launched and appears to have registered with the Notification Hub properly, we can go back to the Windows Management portal and use the notification hub to test our application. Be sure to set the platform to “Windows” and the notification type to “Toast”. If we’ve done everything correctly, you should receive a toast notification. What’s even better, is that if you stop debugging, you can still send the notification. This is one of the things that makes notifications awesome. Your app doesn’t even need to be running for you to still send notifications to it. And with Windows 10, you can even allow the user to take actions on those notifications. But that’s likely a subject left for another day. Conclusion So hopefully this has helped stitch a few topics together in a way that’s helpful. As I mentioned earlier, I’ve put all this code up on GitHub for you to borrow and reuse if you see fit. Over time I hope to grow that project, so if you want to skip to the parts covered in this blog, just clone the repository, and look for the tag #notificationhubjs. Until next time! {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/a-javascript-based-windows-10-uwp-notification-hub
CC-MAIN-2017-04
refinedweb
3,222
55.34
The report described in this chapter is designed to help you learn more about Report Builder features for the Web. To build this report, you will use the Report Wizard to create a data model. Then, you will use the Web Wizard to create an HTML report. You will make fairly extensive manual refinements in the Layout Model view and the Live Previewer. In particular, you will use the Web Settings properties. You will use the Chart Wizard to create a chart, and then return to the Web Wizard to add chart hyperlinks. To view your Web report, you will need a Web browser, such as Netscape 3.x or higher, or Internet Explorer 3.x or higher, that supports HTML style sheets and Javascript. In this example, you will create: The following figure illustrates the various Web features that you will add to your Web report. Table 4-1, "Features demonstrated in this Web sample report", describes the steps you will take to enhance your report with these Web features. To build this report, you will need the following files, which are located in your ORACLE_HOME\TOOLS\DOC60\US\RBBR60 directory: rbweb_hdr.htm rbweb_ps.htm 1.gif 3.gif chalk.jpg imdb.bmp drama.gif page-e.gif). The web Use the Report Wizard and click OK. If not, choose File->New->Report. Click Use the Report Wizard use the Report Wizard to create a data model with a single query and a report with a default layout. Tip: Doing so checks all of the column check boxes. Tip: You now should see SALES_REGION='West' in the Condition field. web_41 help you modify the appearance of data by using format masks and changing the maximum rows of data returned by your query. F_SumTOTAL_SALESPerPRODUCT_CATEGORY. Tip: You can view the name of any object by clicking on it once, then choosing Tools->Property Palette to view the Name property. web_412.rdf. Your output should look something like the following figure in the Live Previewer: When designing a large report (i.e., one that retrieves many records), it is helpful to reduce the number of records retrieved during the design and test phases of the project. Tip: Note that you can change this property according to the number of rows you want to view. However, the more rows you fetch, the longer it will take for your browser to load your HTML output. When you are done designing your report and you want to see all of the rows of data, you should reset this property to blank. web_42.rdf. The steps in this section will help you to add an HTML file to your report. This will add a title and graphic to your HTML output. It will also add a background to every page of your HTML output. The HTML report header page contains the information in the <HEAD> tag of your HTML output. \rbweb_hdr.htm. Tip: You can click on the browse (...) button to locate this file. This file should be located in your ORACLE_HOME\TOOLS\DOC60\US\RBBR60 directory. clicking on each object, then clicking (or the other two icons above and below it) and choosing a color from the palette. web_43.rdf. web_43.htm. web_43.htmin your Web browser. Confirm that the title "21st Century Video" and a graphic appear at the beginning of your report. Tip: At this point, your layout may overlay part of the header. This will be fixed in a later step. Note also that you can add other HTML files to your report by using the other properties under Report Escapes. Your HTML output should look something like the following figure: The steps in this section will help you to add bookmarks to your report and generate HTML output: web_44.htm. web_44.rdf. web_44.htmin your Web browser. Click on some of the bookmarks to check that they work properly. Your HTML output should look something like the following figure: While viewing the HTML output in your browser, you will notice a gray line separating each "page" of your output. The steps in this section will help you to remove that page separator. web_45.rdf. web_45.htm. web_45.htmin your Web browser to confirm the page separator no longer displays between pages. You can compare web_45.htmto web_44.htm. In your HTML output, you may want to add hyperlinks so that you can click on text or images to access other hyperlink destinations, such as external URLs or other destinations within your report. The steps in this section will help you to add targets to your Web report, and then add hyperlinks that link to the targets, as well as to external hyperlink destinations. Tip: In addition to dragging with the mouse, you can also move selected objects using the arrow keys. Sales Results. Tip: You can use the color-changing tools in the tool palette to modify the look of this text object. Text_RptTop. rpt_top. web_461.rdf. This text object is the target of a hyperlink you will create in a later step. text_totop. #rpt_top. web_462.rdf. imdb.bmp), or click Browse to find the file. IMDB_BMP. For more information, go to the Internet Movie Database. Tip: You can also choose colors for the background of the textbox, or remove the line from the border of the textbox.. IMDB_text. Your current layout should look similar to the following figure: web_463.rdf. web_463.htm. web_463.htmin your Web browser to confirm that the new hyperlinks work properly. Your HTML output should look similar to the following figure: You can further enhance objects that contain hyperlinks by adding pop-ups and rollovers that contain textual descriptions. The steps in this section will help you to create pop-up and rollover text that displays when you drag the mouse over an object in your HTML report. IMDB_BMP. Internet Movie Database. web_471.rdf. web_471.htm. web_471.htmin your Web browser. onMouseover="window.status='Clicking here will display the Internet Movie Database home page.';return true" onMouseOut="window.status=' ';return true" web_472.rdf. web_472.htm. web_472.htmin your Web browser. The steps in this section will help you to specify that certain objects, such as page numbers, will not display in your HTML, HTMLCSS, or PDF output. However, these items will still display in other report file formats. function text_totop1FormatTrigger return boolean is begin if UPPER(:DESFORMAT) = 'HTML' or UPPER(:DESFORMAT) = 'HTMLCSS' or UPPER(:DESFORMAT) = 'PDF' then return (TRUE); else return (FALSE); end if; end; web_48.rdf. web_48.htm. web_48.htmin your Web browser. Compare your HTML output to your report output in the Report Builder Live Previewer. The boilerplate text object labeled "Back to Top" should display in your browser, but not in the Live Previewer. The steps in this section will help you to create a summary section for your report, and include a pie chart in the summary section. Tip: If the Data Model tool palette is not displayed, choose View->Property Palette. SALES_REGION='West'AND TOTAL_PROFIT>2000 web_491.rdf. Executive Summary of Video Sales. Tip: While the boilerplate text object is still selected, you can change the font and fill colors. Quarter Profits. R_execprof. 1.5 inches wide and 0.25 inches tall). F_qrtr. Tip: If you receive PL/SQL errors, you can try choosing Program->Compile->All to compile your format triggers. web_492.rdf. web_492.htm. web_492.htmin your Web browser to confirm that the first page displays your new header page. Tip: When you launch the Chart Wizard, Oracle Graphics Builder runs in the background. On Windows, you should see this application in your taskbar. RDFand . HTMfiles. rbweb_chart. web_493.rdf. web_493.htm. web_493.htmin your Web browser to confirm that a chart displays on the first page of your output. You can also add hyperlinks to your chart that will drill down to corresponding data. In this exercise, you will create hyperlinks from the pie chart to the summary report you created in Section 4.9.2, "Creating the default layout for the summary section". #rbweb_chart&<Total_Profit1>. F_PROFFLD. rbweb_chart&<Total_Profit1>. web_494.rdf. web_494.htm. web_494.htmin your Web browser click an area on the pie chart to access the corresponding data in the report. The steps in this section will help you to add Javascript to your Web report. Doing so will create additional special effects for your report, such as animation and customized navigational controls. In order for the Javascript in this exercise to work properly, you should have completed Section 4.9, "Creating a summary section with a chart" and Section 4.3, "Including an HTML report header". In this exercise, you will add Javascript to a text object that, when open in a Web browser, will change an image object from blue to red when you pass your mouse over the image. To complete this exercise, you will need the 1.gif. 1.giffile (located in your ORACLE_HOME\TOOLS\DOC60\US\RBBR60directory) to the destination directory (the location where the generated HTML files will reside). directly below the layout. <a href="#webrep_bottom" onmouseover= "document.images['example'].src=image02.src" onmouseout= "document.images['example'].src=image01.src"> <img src="1.gif" name="example" border=0></a> B_JS. rbweb_hdr.htmfile). In the next step you will add the Javascript to the body of your HTML output. function B_JSFormatTrigger return boolean is begin if UPPER(:DESFORMAT) = 'HTML' or UPPER(:DESFORMAT) = 'HTMLCSS' or UPPER(:DESFORMAT) = 'PDF' then return (TRUE); else return (FALSE); end if; end; Click on the arrow to view the Executive Summary. Place this object next to the boilerplate text object containing the Javascript (B_JS). web_4101.rdf. web_4101.htm. web_4101.htmin your Web browser and confirm that the boilerplate text object you created displays. You should also see a blue arrow that turns red when you drag your mouse over it. Tip: You can click on this arrow to access your Executive Summary if you've completed Section 4.9, "Creating a summary section with a chart". You can also repeat step 3 in Section 4.8, "Using PL/SQL to conditionally hide/show objects for Web output" to conditionally show/hide the objects you created in this section, so that they only display in your HTML output. You can use HTML page streaming in your Web report to display navigational controls so that users can easily move from one page to another.: Report Builder provides default page streaming controls. For this exercise, however, you will use customized the navigational controls. For your convenience, the graphics and javascript needed to create the customized controls have been provided. They are: rbweb_ps.htm, which contains the javascript page-e.gif) ORACLE_HOME\TOOLS\DOC60\US\RBBR60directory) to the destination directory (the location where the generated HTML files will reside). rwbld60 pagestream=yes. web_4102.rdf). web_4102.htmin your Web browser and confirm that the navigational controls display. The steps in this section are optional; they will help you run your report dynamically from the Reports Server. To complete this exercise, you must have Oracle Developer Server software, and must have installed and configured the Reports Server for dynamic reporting. Refer to the Publishing Reports manual for more information, or contact your system administrator for assistance. ORACLE_HOME\TOOLS\DOC60\US\RBBR60directory on your machine to the directory where the cached files are sent. Refer to the Reports Server configuration file to determine the cache directory. rbweb_hdr.htm rbweb_page.htm 1.gif 3.gif drama.gif userid=user_name/password@mydb+ server=repserver+desformat=htmlcss+ destype=cache+pagestream=yes where: your_webserver is the URL address of the Web server cgi-bin is the virtual location of the CGI or OWS executable user_name/password@mydb is the connection string to the database repserver is the name of the Reports Server Congratulations! You have finished the Web sample report. You now know how to: For more information about web-based reports, see the online help:
http://docs.oracle.com/html/A73172_01/output/bawor_we.htm
CC-MAIN-2014-41
refinedweb
1,977
56.35
How to: Construct and Process Batch Queries by Using REST Overview This topic shows you how to submit batched queries to the Microsoft® SharePoint® Foundation representational state transfer (REST) interface from a Microsoft Silverlight® application, and how to process the response from the service. This topic uses the Team Discussion list as an example. The Team Discussion list is created by default on SharePoint 2010 team sites. If you created your SharePoint site from a different site definition, this list may not be available. Summary of Steps This topic describes the following steps: - Step 1: Create Multiple REST Queries. In this step, you use your service reference to construct multiple REST queries that will be sent to the server in a single batch. - Step 2: Create the Delegate Method and Process the Results. In this step you create the delegate method that will process the batch results. Step 1: Create Multiple REST Queries This procedure creates several queries against the Team Discussion list, and submits them to the REST interface as a batched request. To create and submit a batched request - Add a using statement that points to the REST service reference. Use the following format. In the following example, Client.SilverlightSample is the Silverlight project namespace and Sample.ServiceReference is the service namespace. - Use the default constructor to instantiate the data context entity for the service, as shown in the following example. The name of your data context class will take the form <sitename>DataContext, where <sitename> is the name of your SharePoint site. - Create your query objects. The following example creates three queries against the Team Discussion list. // Get anything with the word 'Business' in the Body var query1 = context.TeamDiscussion .Where(p => p.Body.Contains("Business")); // Get anything that was created within the previous 14 days var query2 = context.TeamDiscussion .Where(p => p.Created.Value > DateTime.Now.AddDays(-14)); // Get anything with an attachment var query3 = context.TeamDiscussion .Where(p => p.Attachments != null && p.Attachments.Count > 0); - Call the BeginExecuteBatch method on the data context to submit your queries as a batched request. Supply the following objects as arguments to the BeginExecuteBatch method. - A callback delegate that points to the method you want to invoke when the query returns. In this case, we will create a callback method named DisplayDiscussions in step 2. - A state object, which in this case is the data context instance. - Each of your query objects. The method accepts a parameter array of query objects; therefore, you can submit as many queries as required. Step 2: Create the Delegate Method and Processing the Results This procedure creates a callback method to process the results of the batch query. In this example, we create a method named DisplayDiscussions to match the delegate used in the last task of step 1. To process the batched results - Create a new private method named DisplayDiscussions that accepts a single parameter of type IAsyncResult. - In the DisplayDiscussions method, add a call to the Dispatcher.BeginInvoke() method. This is used to process the results on the UI thread. - Add code to retrieve the response from the data service and process each response operation. For each response operation, check the following before you process the results. - Check that the operation is error free. - Check that the operation is of the expected type. private void DisplayParts(IAsyncResult result) { Dispatcher.BeginInvoke(() => { //Get the Batch Response DataServiceResponse Response = context.EndExecuteBatch(result); //Loop through each operation foreach (QueryOperationResponse Operation in Response) { if (Operation.Error != null) { throw Operation.Error; } //Check the Operation is of the expected type if (Operation is QueryOperationResponse<TeamDiscussionItem>) { //TODO: Process your results } } }); }
https://msdn.microsoft.com/en-us/library/ff798397.aspx
CC-MAIN-2017-51
refinedweb
601
57.67
go to bug id or search bugs for Description: ------------ is_readable() and file_exists(), when called from a PHP 4.3.2 (Linux), 4.4.0 (Mac OS) and 5.2.1 (Mac OS) script that is executed with posix_euid() != posix_uid() does not recognize files that are owned and readable only by the effective uid. Instead is_readable() and file_exists() return "false" even though functions like fileperms, fopen and readfile work as expected. Reproduce code: --------------- #!/usr/bin/php <?php echo "My effective UID is ".posix_geteuid()." but my UID is really ".posix_getuid()."\n"; chdir($curdir = dirname(__FILE__)) or die("Unable to enter the private directory"); echo "The current directory is owned by ".fileowner($curdir)." and has permissions ".sprintf('%o', fileperms($curdir))."\n"; touch("test.dat"); chmod("test.dat", 0600); // readable only by the effective user echo "is_readable should give TRUE, and gives ".(is_readable("test.dat") ? "TRUE" : "FALSE")."\n"; echo "file_exists should give TRUE, and gives ".(file_exists("test.dat") ? "TRUE" : "FALSE")."\n"; echo "The file has permissions ".sprintf('%o', fileperms("test.dat")).", is owned by ".fileowner("test.dat")." and is in the ".filegroup("test.dat")." group.\n"; unlink("test.dat"); // no error because the file really does exist! ?> Expected result: ---------------- My effective UID is 501 but my UID is really [uid] The current directory is owned by 501 and has permissions 40700 is_readable should give TRUE, and gives TRUE file_exists should give TRUE, and gives TRUE The file has permissions 100600, is owned by 501 and is in the 501 group. Actual result: -------------- When run as its owner, gives the expected result, with [uid]=501. When run from a different account using the executable obtained from #include <unistd.h> int main(int argc, char **argv) { execl("/path/to/reproduce_code.php", "/path/to/reproduce_code.php", NULL); } which is then chmod 04711 or 06711, gives My effective UID is 501 but my UID is really 503 The current directory is owned by 501 and has permissions 40700 is_readable should give TRUE, and gives FALSE file_exists should give TRUE, and gives FALSE The file has permissions 100600, is owned by 501 and is in the 501 group. These tests are done on Mac OS X 10.4.8 with both PHP 4.4.4 and 5.2.1, but I first noticed this behaviour with PHP 4.3.2 under Red Hat Linux for which I do not have root privileges. Add a Patch Add a Pull Request PHP uses access() function. man access: The check is done with the process's real UID and GID, rather than with the effective IDs as is done when actually attempting an operation. This is to allow set-UID programs to easily determine the invoking user's authority. Thanks. I understand that PHP uses access() and that access() behaves as per its man page. I also understand that this is one way of fixing e.g. Bug#30931. But I don't understand why that implies that is_readable() and file_exists() are *supposed to* behave according to the access() man page. Aren't is_readable() and file_exists() supposed to behave as described in the PHP manual? Nowhere therein does it specify that the check is done using the real UID/GID instead of the effective one. And I'm afraid I don't understand why checking the real UID/GID is the desired behaviour. Thanks, Jeremy > Nowhere therein does it specify that the check is done > using the real UID/GID instead of the effective one. Reclassified a docu problem. Feel free to help the documentation team in documenting this behavior. check is done using the real UID/GID instead of the effective one."
https://bugs.php.net/bug.php?id=40535
CC-MAIN-2018-17
refinedweb
601
66.03
These are chat archives for rust-lang/rust I am getting a compiler error, but I have a different issue than I thought yesterday. Sorry, I was a bit burned out from chasing bugs and ended up chasing the wrong problem. The real issue is more similar to this: trait Foo<T> { fn method(self) -> T; } enum Things<T> { A(T), B(T), } impl<T> Foo<T> for Things<T> { fn method(self) -> T { unimplemented!() } } impl<T> Things<T> { fn change(&mut self, t: T) { match *self { Things::A(_) => *self = Things::B(self.method(t)), Things::B(_) => *self = Things::A(self.method(t)), } } } I think the problem is that my Foo implementation consumes self, so I can't call self.method() inside of the change method. At all. That is frustrating me, because I don't think I can change the Foo trait, for other reasons. I don't suppose there's any way around this? Clonefor Things, then you can do self.clone().method(). But why does Foo::method()have to take self? method, in this example, is the step method which produces the next state. I liked that it consumed self, ensuring that old states didn't hang around. If it isn't obvious, I'm still very much struggling to get into the Rust mindset. That's part of the reason I'm building this project. It's sort of a learning exercise. Clonefor the trait might solve this problem, it defeats the purpose of the states consuming themselves, so I might as well just bite the bullet and change Foo::method()to method(&self):( self, if you want to guarantee the old state isn't used. I take it change()is meant to define all possible state transitions? method()right? If you're interested in spending the time, here are the relevant bits. Link [1] is the file containing the definition of the state trait and several reference implementations that adapt fn pointers and closures to be used as states. This file compiles fine. Link [2] is the file containing the definition of the machine trait, which is intended to be an interface for objects that take states and run them, optionally producing some output (tokens, etc). This file does not compile, for the reasons discussed above. My end goal is to build an iterator adapter that takes a machine implementation and produces an iterator of tokens so you could do something like iter.tokenize(machine), but I'm trying to keep it as modular and generic as possible. That way, the pieces can be used for other purposes. [1] [2] run()method in that second link is an absolute mess, I realize. I fought with it for like a day before I realized what the actual underlying problem was. s.step(c) run()repeatedly to get a piece of output (token?) each time. &self. I don't like it, but it would probably be necessary anyway to enable the use of these tools to create a PDA, and my intention was to be agnostic to the type of machine (hence the heavy use of generics) enum FSMand not just struct FSM { state: Option<State> }? Bothor Outputanyway... fn state_a(&mut Scanner) -> (Option<State>, Option<Token>) { let symbol = Scanner.Peek(); match symbol { something_relevant => return (state::StateFnItem(state_b), None), _ => // etc... } } fn state_b(&mut Scanner) -> (Option<State>, Option<Token>) { /* something similar */ } impl Machine for FSMyou always return the output right away, thus you don't need to store it in the FSM... struct FSM { state: Option<S> , output: Option<O>} .step(c)on it, which consumes the state... can't do that since it's borrowed. let state = self.state.take(); match state { Some(state) => { let (new_state, output) = state.step(); self.state = new_state; if let Some(output) = output { return Some(output); } }, None => return None } .take(). Still not 100% familiar with std lib Nonein its place. error[E0392]: parameter `U` is never used --> /run/media/rustycode/Storage_ext4/Dev/db-topics/libs/database/src/generic.rs:70:24 | 70 | pub struct Database<T, U> | ^ unused type parameter | = help: consider removing `U` or using a marker such as `std::marker::PhantomData` error: aborting due to previous error #[derive(Debug)] pub struct Database<T, U> where T: Record<U> { data: Vec<T<U>>, abs_sd: Vec<(f32, f32)>, } Vec<T>and adding another field: _output: PhantomData<U> impl<C, S, O> Machine for FSM<C, S, O> where S: state::State<C=C, R=FSM<C, S, O>> { type C = C; type O = O; fn run(&mut self, c: &mut Self::C) -> Option<Self::O> { loop { match mem::replace(self, FSM::Nothing) { FSM::State(s) => { mem::replace(self, s.step(c)); } FSM::Output(o) => return Some(o), FSM::Both(s, o) => { mem::replace(self, FSM::State(s)); return Some(o); } FSM::Nothing => return None, } } } }
https://gitter.im/rust-lang/rust/archives/2017/06/09
CC-MAIN-2019-26
refinedweb
803
64.2
Hello all, I'd like to ask whether it would be possible to render/draw text dynamically on prefabs. Specifically, what I would like to do is have planets falling from the top of the screen (that would be generated from a sprite prefab) and on top of each one's surface to display a different word, which is taken from a JSON file. Additionally I'd like the text to follow the downwards motion of the planet it's drawn on. Is this something that would be possible with the free version of Unity? And what would be the workflow for building something like that? I would hope this could be done via GuiTextures or something, but I haven't found a way to build it yet or any relevant tutorials. The only alternative I can think of is creating a sprite for each one of the words separately and loading them all to the scene, but I'm afraid this will soon create a mesh. Any suggestions would really help! Thank you Not sure of all of your parameters here. For text in world space you can use Text$$anonymous$$eshes (3D Text). You can also track world space object using GUIText() or GUI.Label(). I'm not sure about the nature of your falling planets, but you might consider making the planets GUITextures ins$$anonymous$$d of Sprites and then using a GUIText for the label. Answer by Eric5h5 · Jan 19, 2014 at 10:01 PM The simplest way would be to have a TextMesh that's a child of the sprite. Use renderer.sortingLayerID and renderer.sortingOrder (in code) to get the text to draw over the sprite as necessary. Thank you both for the suggestions, I have just started building this, so I'm gonna try testing both workflows GUITextures+GUIText and Text$$anonymous$$esh to see which one I can implement, and report back. Not sure if it will make things clearer, but I'm posting an image of what I'm trying to do. I have already made the sprite prefab (yellow icon), which is dynamically created on screen, but I'm not sure what kind of element the word should be (e.g. a GUItext?) to be able to dynamically render on-top of the icon (as I'd like to draw a different word on each falling yellow icon). I guess the word should be part of the same prefab? Eric5h5, could you maybe give me an example of making the Text$$anonymous$$esh a child of the sprite or code using Renderer.sortingLayerID and renderer.sortingOrder? Answer by youblistermypaint · Sep 27, 2015 at 05:17 PM To expand on Eric5h5's answer. You would want to set up a GameObject with a TextMesh component as a child of your Sprite. And then attach the following script to it: using UnityEngine; public class SpriteText : MonoBehaviour { void Start() { var parent = transform.parent; var parentRenderer = parent.GetComponent<Renderer>(); var renderer = GetComponent<Renderer>(); renderer.sortingLayerID = parentRenderer.sortingLayerID; renderer.sortingOrder = parentRenderer.sortingOrder; var spriteTransform = parent.transform; var text = GetComponent<TextMesh>(); var pos = spriteTransform.position; text.text = string.Format("{0}, {1}", pos.x, pos.y); } } Hi, I did this, and it "kinda" works. I've done what you suggested (thank you) However, the text is behind the sprite ins$$anonymous$$d of in front of it. I have a sprite as a background assigned to a Sorting Layer named _background, and the sprite (button) in which I added the text mesh to, is on a Sorting Layer named_foreground. The text is rendering over the background, but it is behind the foreground. I see no options unfortunately for the GameObject to assign it a particular sorting layer. The GameObject is a child of the button. Any ides how I could fix this? Thank you so much! It's been awhile since I did anything with this script but I imagine you would need to mess with your Z position of your sprite and / or the text to get it to layer the way you want. Answer by roccosaya · Aug 10, 2016 at 07:54 PM thanks for the quick reply. Oddly, setting the offset Z to -1, fixed the problem. The -1 is what I find strange. I have no idea why -1 works, just tried a negative number, after trying a few positive ones. Answer by DrMike91 · Oct 07, 2016 at 04:58 PM I'm doing a 2D game and needed text to follow a moving Sprite. I just added a GameObject child to the Sprite and added a Text Mesh as a component and changed the Offset Z value to -1 as suggested and all is well. I did not need to do anything with scripting for the mesh. When the sprite move, the text moves. I had searched many threads on this subject - most had very complicated answers; this was so simple and just. Destroy Object On Collision? 3 Answers 2D Sprite moving outside screen edges (side bumpers) 0 Answers 2D Sprite animation JS to C# 2 Answers Rigidbody2D getting destroyed in the inspector 2 Answers Game Runs Horribly Slow On iPad? 3 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/620747/render-text-on-sprite-prefab-2d-ios.html?sort=oldest
CC-MAIN-2021-17
refinedweb
864
72.36
Didier Borel2,837 Points squared function i don't understand why this is not working def squared(arguement): try: int(arguement)**2 # If it can do that it will go here except ValueError: arguement*len(arguement) # If it cant it will go here. 4 Answers Krishna Pratap Chouhan15,178 Points Its all great, but you are suppose to return a value. # EXAMPLES # squared(5) would return 25 # squared("2") would return 4 # squared("tim") would return "timtimtim" def squared(arguement): ret_value = 0 try: ret_value = int(arguement)**2 # If it can do that it will go here except ValueError: ret_value = arguement*len(arguement) return ret_value Didier Borel2,837 Points Hi krishna, thxs a lot for your answer it was helpful, and gave me the small step i was missing. When I wrote your code in the challenge, i got a correct answer. when i write the code workspaces I get no answer. I just get backed the name of the file, (here I named it python squared.py), so 2 questions: - why is that? simply because I never gave an arguement? - so I wrote this in workspaces, and got back this answer def squared(arguement): arguement=4 ret_value = 0 try: ret_value = int(arguement)**2 # If it can do that it will go here except ValueError: ret_value = arguement*len(arguement) return ret_value answer treehouse:~/workspace$ python squared.py File "squared.py", line 9 return ret_value ^ IndentationError: unindent does not match any outer indentation level can you explain this to me? Didier Borel2,837 Points Thanks for this very complete and helpful answer, Krishna! I will have a look at the indentation issue. another question: in fact it is question number one above : when i write your code workspaces I get no answer. I just get backed the name of the file, (here I named it python squared.py), why is that? simply because I never gave an arguement? Krishna Pratap Chouhan15,178 Points When you run a python file, python <file-name>.py you will not get anything unless there is some output being sent from the file. When running using compiler(unlike in IDLE) you will not get anything on scree by simply stating the variable. e.g. In IDLE: >>>>> a Hello World!!! You see above is a output In File using compiler a = "Hello World!!!" a While running this code in Terminal/Command_prompt $ python <filename>.py $ There is no output. But if you change the code to... In File using compiler a = "Hello World!!!" print(a) While running this code in Terminal/Command_prompt $ python <filename>.py Hello World!!! $ There is output. Also, just defining the function wont do anything, you'll have to call it as well. For e.g. def printHello(): print("Hello") . $ python <filename>.py $ There is no output . But def printHello(): print("Hello") printHello() . $ python <filename>.py $ There is output Defining a function is just like declaring a variable. You actually have to call that functionality. So you have to call the function you declared. If it accepts an argument and you call without an argument it'll give an error, unless you have provided a default value to those arguments. Didier Borel2,837 Points great- thanks so much Krishna. so now how do I run something in idle? where do i load that? Krishna Pratap Chouhan15,178 Points In Terminal/Command_prompt, type python $ python and you'll see... . Python 3.6.5 (v, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Krishna Pratap Chouhan15,178 Points Krishna Pratap Chouhan15,178 Points So this is how compiler generates the error and points where it got the error. First line: You ran the code with python as compiler. Second line: Error occurred while compiler was going through line 9 Third line tells: Error occurred at which point exactly in the line.(here the upper arrow shows at very first token) Fourth line tells: What the problem was with the code. Here it says, it indentation. My guess, you might have missed the indentation(or less number of spaces) before the returnstatement. Solution, is simple but nothing straight forward. Since indentation specifies the block in python you have to take care of indentation. To solve this problem, go through the code, null/remove all the indentation and again specify the indentation. In my experience this generally happen when indentation space varies. Tab/indentation length is 2-spaces, 3-spaces or 4-spaces sometimes. There is nothing particular, just maintain a uniform indentation. I use 4-space indentation but many people uses 3-space also.
https://teamtreehouse.com/community/squared-function-2
CC-MAIN-2019-26
refinedweb
770
67.15
Spring Boot Scenario with NetBeans IDE By Geertjan-Oracle on Feb 03, 2016 Today Spring Boot guru Josh Long (@starbuxman) sent me a helpful scenario for getting started with Spring Boot. I've finetuned and translated some aspects to make everything work smoothly in NetBeans IDE. So, let's get started. Go to, click "Switch to the full version", and choose the 'H2', 'web', 'JPA', and 'REST Repositories' checkboxes. Alternatively, you can use the auto completing drop down on the right. You'll get a JAR-based Maven project. Instead, make sure where it says "Packaging" to select "War", as shown below. Click "Generate Project" at the bottom of the page, which by default will give you a ZIP file named "demo.zip" on disk. No need to unzip that ZIP file or to go through any kind of complex import process to get the project it contains into NetBeans IDE. Instead, go here: As can be seen above, go to File | Import Project | From ZIP and then browse to the "demo.zip" file. Click "Import" and NetBeans will unzip your file, open the Maven project, and display it in NetBeans IDE. If some/all of the dependencies have not been downloaded by Maven, you'll see various project problems and errors, which you can solve by right-clicking the project and choosing Build. That will download the Maven dependencies and at the end the project should look nice and neat, as follows: All the coding we will do from this point onwards will be done in the "DemoApplication.java" file that you see in the "com.example" package above. The import statements we'll need are as follows: import java.util.Collection; import java.util.stream.Stream; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.annotation.Id; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.stereotype.Component; Add each class below beneath the previously existing class in the file. In other words, all the code we'll be working on will be within the same Java source file. Start by adding a simple JPA entity: @Entity class Reservation { @Id @GeneratedValue private Long id; private String reservationName; public Long getId() { return id; } public String getReservationName() { return reservationName; } public Reservation(String reservationName) { this.reservationName = reservationName; } public Reservation() { } @Override public String toString() { return "Reservation{" + "id=" + id + ", reservationName=" + reservationName + '}'; } } Next, we need some way to handle persistence logic, therefore add the following below the previous code in the file, to create a Spring Data JPA repository: @RepositoryRestResource interface ReservationRepository extends JpaRepository { @RestResource(path = "by-name") Collection findByReservationName(@Param("rn") String rn); } Finally, again below the previous code in the same file, you'll need to insert some simple sample data, so create a component that gets called on application startup: @Component class DummyCLR implements CommandLineRunner { @Autowired private ReservationRepository repository; @Override public void run(String... args) throws Exception { Stream.of("Josh", "Geertjan", "Pieter").forEach(x -> repository.save(new Reservation(x))); repository.findAll().forEach(System.out::println); } } Now let's run the application, using this tip to do so, which will run the embedded Tomcat provided by Spring Boot and deploy the application to it, correctly running the code from the "public static void main" entry point of the application. We'll be circumventing the NetBeans approach to deploying applications completely and making use of the corresponding features provided by Spring Boot instead. To do this, right-click the project, click Properties, and rewrite the "Execute Goals" field of the "Run project" action from "package" to "org.springframework.boot:spring-boot-maven-plugin:1.3.2.RELEASE:run", as shown below: Now, whenever you press F6, you'll be deploying the application to the embedded Tomcat, which you'll also be starting up. In the Output window (Ctrl-4), you can stop the process, i.e., shutdown the embedded Tomcat and undeploy the application. Run the application via F6 or by choosing "Run" on the project or in the toolbar, which will end up showing you the reservations in the Output window: Also, when you open your browser to "" you'll see the REST API stood up for you based on your data set, which will initially show an error. "OK," says Josh, at this point. "This is all well and good but let's get serious! This uses an embedded in-memory DB! And there are no operational features. This isn't ready for production! How do you see things like the health of the app? metrics?" Right-click the "Dependencies" node in the project, choose "Add Dependency", and add "spring-boot-starter-actuator": After you click "Add" above, the dependency will be added to the POM. Actually, no version should be required since its dependency is managed by Maven in the parent POM. Now, if you restart, i.e., end the process and restart it, you should now be able to hit URLs like the following: localhost:8080/, /reservations, /reservations/1, /reservations/2, etc.: You should also be able to visit /metrics and /health. "Not bad," says Josh. "Info on the state of the app." The above instructions are all the basics needed for getting started with Spring Boot. More in follow up blog entries soon. Any reason to need to switch to war, especially since you are running with embedded Tomcat? Posted by Mark on February 04, 2016 at 07:31 AM PST # Hej Geertjan, the association of the goal could be automated using a plugin. * Add a ProjectOpenHook - * When a maven project is opened (with some spring-boot specifics as marker like super-pom or what ever) then alter the goal BR Posted by guest on February 04, 2016 at 11:54 AM PST # Hope this isn't too obvious but how would you add a debug action/goal Posted by Paul Verket on March 08, 2016 at 05:34 PM PST # Sorry if this is obvious but how would you set up debugging? Posted by Paul Verket on March 09, 2016 at 12:57 PM PST # I followed your instructions to the letter, but no ServletInitializer.java file was created. Has something changed in Maven? Posted by guest on May 02, 2016 at 01:28 AM PDT # ServletInitializer is not created by Spring Boot. Spring Boots assumes you want to run as a Jar. TO convert to run as a war, you must create that yourself. For instructions - Posted by Mark on May 04, 2016 at 06:11 AM PDT # I had to change: * import javax.persistence.Id; to import org.springframework.data.annotation.Id; * @RepositoryRestResource interface ReservationRepository extends JpaRepository{ to @RepositoryRestResource interface ReservationRepository extends JpaRepository<Reservation, Long> { Posted by poshjosh on May 30, 2016 at 07:51 AM PDT # Hi Geertjan, Getting NB to run/shutdown Tomcat can actually be simplified to this as the Run command: spring-boot:run Spring on, Mark :) Posted by Mark Heckler on May 31, 2016 at 02:43 PM PDT # Hi Geertjan, I have seen your webinar on topic Up and Running with Spring Boot in NetBeans IDE, available here: related to this article, and I think it is great. Is there a way to add Spring Boot application shutdown via actuator /shutdown or other way before the Run action, to provide easier redeployment of code changes via Run action? I mean without actually having to shutdown manually before Run. Thanks, Dejan Posted by Dejan on August 09, 2016 at 01:15 AM PDT # Hi, For those using spring profiles, if you want to pass your spring profile automatically when running the app, just add the following in the the "Set Properties" box when editing the action: Env.SPRING_PROFILES_ACTIVE=myprofile Regards Posted by Charl on September 29, 2016 at 04:10 AM PDT #
https://blogs.oracle.com/geertjan/entry/spring_boot_scenario_with_netbeans
CC-MAIN-2017-04
refinedweb
1,332
55.44
Opened 3 years ago Closed 6 months ago #4893 closed enhancement (fixed) Build 0ad using system libmozjs-52 / SpiderMonkey52 Description I maintain the Debian package of 0ad. 0ad fails to build on arm64 because mozjs83 fails to build. The error is: /<<PKGBUILDDIR>>/libraries/source/spidermonkey/mozjs-38.0.0/js/src/jit/shared/CodeGenerator-shared-inl.h:232:10: error: 'class js::jit::MacroAssembler' has no member named 'verifyHeapAccessDisassembly' masm.verifyHeapAccessDisassembly(begin, end, ^~~~~~~~~~~~~~~~~~~~~~~~~~~ See for the complete build log. One solution would be to use the mozjs package provided by Debian and already available for arm64. Debian unstable provides libmozjs-52-dev. I tried to patch 0ad (work-in-progress patch attached) to use this mozjs version but the build fails with: ../../../source/scriptinterface/NativeWrapperDecls.h:79:51: error: ‘jsval’ has not been declared static bool callMethod(JSContext* cx, uint argc, jsval* vp); ^ ../../../source/scriptinterface/NativeWrapperDecls.h:79:51: note: in definition of macro ‘OVERLOADS’ [...] ../../../source/scriptinterface/NativeWrapperDefns.h:133:50: error: cannot convert ‘int*’ to ‘JS::Value*’ for argument ‘2’ to ‘JS::CallArgs JS::CallArgsFromVp(unsigned int, JS::Value*)’ JS::CallArgs args = JS::CallArgsFromVp(argc, vp); \ it looks like the 0ad code needs some changes to migrate from mozjs-38 to mozjs-52. Is there any interest to support a more recent (and supported, with security bugs fixed, etc.) version of mozjs for 0ad? Attachments (1) Change History (47) by , 3 years ago comment:1 by , 3 years ago Nobody interested in using a supported libmozjs library? comment:2 by , 3 years ago First we have to update to SpiderMonkey 45, work was started here but there are still a number of things todo (). You can find some previous SM upgrade tickets on trac, that is a considerable amount of work, much more than a small patch fixing some compile warnings. For instance the SM38 upgrade was done in 35 commits: r18689 comment:3 by , 3 years ago comment:4 by , 3 years ago Can't we skip to 52 directly ? comment:5 by , 3 years ago We have to find out what has changed meanwhile. Pyrogenesis code that is incompatible to sm45 will be incompatble to sm52 too, so skipping will be more work as far as I understand. On the other hand compile warnings should always be addressed, so we should review the uploaded patch either way. comment:6 by , 3 years ago I'd be willing to donate some money for this work, ALT's e2k port has mozjs52 but getting mozjs38 there is problematic right now. comment:7 by , 3 years ago There is a patch with some days of started work for sm60: Phab:D1510. (I still don't know if it will be easier to jump to the latest stable or to progress one release at a time. The patch looked like it might be manageable to jump.) comment:8 by , 3 years ago Heh, I won't see 60 on e2k for quite some time I guess... comment:9 by , 3 years ago Our sm60 patch could be next month or next decade too. About the version, Itms mentioned in an internal thread that the next 'LTS' is SM60, but I couldn't verify this for now. According to the latest release is SM52 and no sucessor officially scheduled yet. comment:10 by , 2 years ago comment:11 by , 2 years ago 2 elexis: as previously noted, I'm willing to donate some money, especially if someone can do the transition from mozjs38 with an explicit stop at mozjs52 (that will gain a whole new target platform). Let it be 50 euros to be more specific, and please email me with proper contact if that's acceptable. comment:12 by , 2 years ago Notice that our SM includes few patches: The updated version might also require some, implementation will tell. comment:13 by , 2 years ago Notice that our SM includes few patches It's fine as long as these are fixes not upstream-incompatible kludges for a particular project :-) SM52 is getting skipped unconditionally, right?.. (I know the "you need it you do it" rule, no moaning) comment:14 by , 2 years ago SM52 is getting skipped unconditionally, right? By default 0ad is compiled with the spidermonkey version in 0ad/libraries/source/spidermonkey/, one can supposedly compile with a shared library using --with-system-mozjs38 wiki:BuildInstructions in case you mean that. stop at mozjs52 Until there is a new version of spidermonkey that is tagged as "release" that is? Perhaps it wouldn't be too bad for pyrogenesis/0ad to to update beyond the most recent "release" as wraitii did, if the "release" doesn't really differ in stability or maintenance from the most recent version. Debian for instance has mozjs60 in their repository, but mozjs52 is still the most recent "release". The release packe for mozjs52 is completely empty and I can't even find the download via the method they describe after browsing through hundreds of mozjs52 patches. So I suppose "sm52" is the "prerelease" from I'll review what wraitii and Itms did so far, an update of SM is overdue either way. comment:15 by , 2 years ago Replace deprecated jsval with JS::Value. Remove unused SGUIBaseSettings and GUI comment. Fix indentation of a macro, refs D794. Differential Revision: Review by: leper. Itms came up with the same patch for the SpiderMonkey 45 update independently. comment:16 by , 2 years ago comment:17 by , 2 years ago comment:18 by , 23 months ago comment:19 by , 23 months ago The next Debian version (buster) should be released in July 2019. It will provide libmozjs-60-0 and libmozjs-52-0. It would be fine to target support of libmozjs-60-0 (instead of version 52) if possible. comment:20 by , 22 months ago comment:21 by , 21 months ago comment:22 by , 21 months ago comment:23 by , 21 months ago comment:24 by , 21 months ago explicit stop at mozjs52 Meanwhile Firefox / SpiderMonkey is at revision 68, so it sounds hurtful not to go further. I was wondering whether one could introduce a macro that changes the code to work with 52 at option, but that will probably not scale, because we probably want to start using more recnet spidermonkey version features, in specific rooting a std::vector or std::map in a JSContext as demonstrated in this sm60 example: comment:25 by , 21 months ago For one, I'm still eager to donate e.g. $50 for support of Firefox 52's mozjs *if* that comes feasible (I understand that it can be days or weeks of work more and the suggestion might be just inappropriate). My personal reason is that it's the topmost version of the engine I've got on e2k (Elbrus 2000) architecture, and getting 0ad here would be so nice :-) comment:26 by , 21 months ago comment:27 by , 21 months ago comment:28 by , 20 months ago Wasn't too sure where to drop this, but it appears SM70 might have serious performance optimisations for our use cases: comment:29 by , 18 months ago TODO: It seems there is a SpiderMonkey segfault, see #5636, reproducible with: Object.defineProperty(this, "f", { get: function() { [].keys return (function() { f(); }); } }); f(); comment:30 by , 17 months ago comment:31 by , 9 months ago The migration to SM52 is ready to be tested. You can find the code at Here is the forum post describing the upgrade in detail: To address concerns above about upgrading to newer versions: we are going to try and use more recent versions, also available in the package managers. We do not plan to stick with SM52, unless forced by lack of manpower or unexpected issues. preliminary patch to build 0ad using system libmozjs-52
https://trac.wildfiregames.com/ticket/4893
CC-MAIN-2021-21
refinedweb
1,297
58.62
This site uses strictly necessary cookies. More Information I made a Car using the following Hierarchy: I have the following Empty GameObjects(GO): Car, Tyers, Glass, Body, Lights, Head Lights and Rear Lights. The rest are Basic 3D GameObjects. There are three Problems: 1) If I have Only the Car GO with the RigidBody then the Car wont move using the RigidBody.AddForce(). 2) If I Make Every Empty GO a RigidBody then the Car Breaks and the Empty GOs fall through the Terrain. 3) If I Make Every GO a RigidBody then also the Car Breaks and the Empty GOs fall through the Terrain. In 2) and 3) the GOs still DON'T respond to RigidBody.AddForce(). ---------- Code Used: using UnityEngine; using System.Collections; public class MoveObjectPlayerInputKB : MonoBehaviour { private Rigidbody car; public float speed = 0.5F; public float turnSpeed = 0.5F; // Use this for initialization void Start () { car = GetComponent<Rigidbody> (); } // Update is called once per frame void Update () { float turn = Input.GetAxis("Horizontal"); float forward = Input.GetAxis("Vertical"); car.AddForce (new Vector3(0F, 0F, forward) * Time.deltaTime * speed); transform.Rotate (new Vector3 (0F, turn, 0F) * Time.deltaTime * turnSpeed); // car.AddTorque (new Vector3 (0F, turn, 0F) Time.deltaTime turnSpeed); } } Thanks in advanced and I also Apologize for asking such a Question as I am New to Unity. It's ONLY been 2 weeks.! The Result I'm getting. @$$anonymous$$ikeNewall Can you Help... Thanks. @crazy$$anonymous$. [Help] Player stops moving when hitting wall diagonally 0 Answers What's the best way to get clean, smooth collision physics? 0 Answers Different physics behaviour with identical setup? 0 Answers How to make physics collisions act like in old games (NES, SNES especially) 1 Answer [SOLVED] Ball rolling around a planet bounces off? 2 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/1120210/car-made-from-different-gameobjects-and-empty-game.html
CC-MAIN-2021-39
refinedweb
295
68.97
I'm playing around with asyncio #!/usr/bin/env python3 import asyncio import string async def print_num(): for x in range(0, 10): print('Number: {}'.format(x)) await asyncio.sleep(1) print('print_num is finished!') async def print_alp(): my_list = string.ascii_uppercase for x in my_list: print('Letter: {}'.format(x)) await asyncio.sleep(1) print('print_alp is finished!') async def msg(my_msg): print(my_msg) await asyncio.sleep(1) async def main(): await msg('Hello World!') await print_alp() await msg('Hello Again!') await print_num() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() Hello print_alp is finished! Hello Again! Number: 0 Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 6 Number: 7 Number: 8 Number: 9 print_num is finished! You are calling the functions sequentially, so the code also executes sequentially. Remember that await this means "do this and wait for it to return" (but in the meantime, if this chooses to suspend execution, other tasks which have already started elsewhere may run). If you want to run the tasks asynchronously, you need to: async def main(): await msg('Hello World!') task1 = asyncio.ensure_future(print_alp()) task2 = asyncio.ensure_future(print_num()) await asyncio.gather(task1, task2) await msg('Hello Again!') See also the documentation of the asyncio.gather function. Alternatively, you could also use asyncio.wait.
https://codedump.io/share/2XF2YHVoudCC/1/python--asyncio-doesn39t-execute-the-tasks-asynchronously
CC-MAIN-2017-30
refinedweb
217
54.59
Use a register command to generate RSS and Atom feeds as well as a corresponding Sitemaps. Integrates easily with ShareThis Project description pip install django-feedmap Django Feedmap is a syndication feeds and sitemaps generator for django. Register the querysets only once with feedmap so it knows how to populate the feeds. Put this bit in your urls.py: from feedmap import feedmap feedmap.register('entries', BlogEntry.objects.filter(is_public=True), feed_attrs = { 'title':'Recent Blog Entries', 'link':'/blog/', }, ) urlpatterns += feedmap.urls Then it will generate syndication feeds in atom and rss2 formats as well as corresponding sitemaps: /sitemap.xml # Global Index /sitemap-feeds.xml # Index of syndication feeds /sitemap-entries.xml # Actual sitemap of recent blog entries /feeds/entries # RSS2 feed /feeds/entries/atom # Atom feed Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/django-feedmap/
CC-MAIN-2021-10
refinedweb
155
50.53
Tk_GetOption man page Tk_GetOption — retrieve an option from the option database Synopsis #include <tk.h> Tk_Uid Tk_GetOption(tkwin, name, class) Arguments - Tk_Window tkwin (in) Token for window. - const char *name (in) Name of desired option. - const char *class (in) Class of desired option. Null means there is no class for this option; do lookup based on name only. Description This procedure is invoked to retrieve an option from the database associated with tkwin's main window. If there is an option for tkwin that matches the given name or class, then it is returned in the form of a Tk_Uid. If multiple options match name and class, then the highest-priority one is returned. If no option matches, then NULL is returned. Tk_GetOption caches options related to tkwin so that successive calls for the same tkwin will execute much more quickly than successive calls for different windows. Keywords class, name, option, retrieve Info Tk Library Procedures
https://www.mankier.com/3/Tk_GetOption
CC-MAIN-2017-17
refinedweb
156
57.47
> > > Ar]. > > I don't think you are following my drift. There exists a memory system > within APR. It is called a pool. If anyone here attempts to replace the > HIDDEN INTERNALS of that memory system with some new sms thingy and then > suggests that we should change all calls to apr_pool with apr_sms_pool, > I am going to throttle them with a baseball bat (and then -1 the patch). Ouch. :) > > We have an abstraction. We will have the same abstraction with sms. > Therefore, either sms is under pool or it is a replacement for the hidden > internals of pool with some extensions that are new. It seems to make more > sense as a replacement, which means we code it as such and not as some > "other" memory system. That means we use the same names and selectively > compile one of the two choices into apr until we are sure that the old one > can be replaced with the new one. > > Under no circumstances whatsoever will we change all of our code to call > sms things just because they were implemented as a superset of the current > pool internals. That defeats the whole purpose of abstract data types. OK. This seems like a good idea. > > > Second, with a different namespace we _can_ retain the current pools > > api (at least long enough) next to the sms api. In the httpd, apr > > and apr-util codebase the sms api would be preferred. > > Cruft shall not be carried forward unless it is necessary for backwards > compatibility. > > > > Just use the same names as apr_pool.c and selectively compile one or > > > the other. > > > > The fun is that you don't have to compile one in, you could decide at > > runtime if you please. So, possible roadmap for moving forward... - keep working on the sms code as apr_sms for the time being. We keep doing this until we have an sms module that could replace the current pool code. - build into configure a switch for new/old pool code, keeping the default as the current code - move the pools.c file into the memory/unix directory and add logic to Makefile.in to build pools.c or the sms stuff o at the same time change the top level API's for the sms code to look like apr_pool_t semantics o remove the lib directory - contiue development and add to the API such that we have the full range of flexability of the sms concept but called apr_pool_t - when we're ready change the default option in APR to the new code Carrying on what's been started in the sms code under a seperate namespace should mean we don't cause too much grief until we're ready to make the move. I'm only suggesting moving the pools.c file as that way all memory files are in a single location which seems to make more sense. IN fact it might make more sense to have the top level apr_sms.c file in the memory directory and the seperate sms modules in the platform specific directories. We can debate this but I don't care one way or the other. > > There is nothing fun about bloated runtimes. Indeed. If people are happy with this then this is how we'll proceed and in a while when we're ready to move to stage 2 we'll no doubt have another discussion about the exact details of how we do things :) We do like talking don't we?? Of course some of us prefer words to baseball bats Roy :)) david
http://mail-archives.apache.org/mod_mbox/apr-dev/200106.mbox/%3C001601c0f07f$b1a88ca0$7f00a8c0@VAIO%3E
CC-MAIN-2014-15
refinedweb
593
79.3
User Groups with Custom Permissions in Django You must have encountered with something like , trip booking services with different plans and packages or gym plan with different subscription level. The thing here is that, there are a list of product which you get those on subscribing to different packages that are provided by the company to whom subscription package you are taking . Generally the generic idea they follow is like the level wise distribution of different products . Let’s take the Tour subscription package over internet, then there are differ offers/plan/package like:- 1. Starter plan:- In this package you will get the facility of non-AC bus travel and 1 day stay in a non-AC room only.Let’s say the trip is to to Haridwar( a religious place in Uttarakhand) . 2. Golden Plan:- It will be somewhat costly than the Starter Plan. In this plan you will be given all a 2-day stay in a non-AC room, travelling in a AC bus and the trip will be to Haridwar, Rishikesh and Mussoorie . 3. Diamond Plan:- This is the most costly plan, in which you will be provided a 3 day plan with AC bus, and AC room stay along with trip to Haridwar, Rishikesh and Mussoorie and also a trip to a Water Park . Well, i just tried to give you a very simple example. Now our main objective is to design, and write code of it’s back-end in a very efficient way (following the DRY Principle) . There are multiple methods of implementing this in Django but the most suitable and efficient method is making a Grouping the Users and defining the permissions of these groups .The user of that particular group will automatically inherit the permission of that group in which it is. But first let’s define the User model. Create a Django application ‘users’ then in models.py file under ‘users’ app directory write this code. from django.contrib.auth.models import AbstractUser from django.utils import timezone from django.db import models class User(AbstractUser): “””Define the extra fields related to User here””” first_name = models.CharField(_(‘First Name of User’), blank = True, max_length = 20) last_name = models.CharField(_(‘Last Name of User’), blank = True, max_length = 20) # — — — Some more User fields according to your need — — — — # This is the most important part to look upon to # define the custom permissions related to User. class Meta: permissions = ((“can_go_in_non_ac_bus”, “To provide non-AC Bus facility”), (“can_go_in_ac_bus”, “To provide AC-Bus facility”), (“can_stay_ac-room”, “To provide staying at AC room”), (“can_stay_ac-room”, “To provide staying at Non-AC room”), (“can_go_dehradoon”, “Trip to Dehradoon”), (“can_go_mussoorie”, “Trip to Mussoorie”), (“can_go_haridwaar”, “Trip to Haridwaar”), (“can_go_rishikesh”, “Trip to Rishikesh”)) # — — other custom permissions according to your needs — — — — - After migrating our models that we wrote above, we have two option to for making a group . 1. Django Admin Pannel :- In Admin Panel you will see “Group” in bold letter, Click on that and make 3 different group named ‘level0’, ‘level1’, ‘level2’ . and define the custom permissions according to your needs. 2. By Programmatically creating a group with permissions :- Open python shell by ‘python manage.py shell’. from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType #import User model from users.models import User new_group, created = Group.objects.get_or_create(name =’new_group’) # Code to add permission to group ??? ct = ContentType.objects.get_for_model(User) # Now what — Say I want to add ‘Can go Haridwar’ permission to level0? permission = Permission.objects.create(codename =’can_go_haridwar’, name =’Can go to Haridwar’, content_type = ct) new_group.permissions.add(permission). We will set different set of permissions in the same way to all the three groups .Until now we have made groups and linked it with custom permissions that we made Now we have to check that a particular user is accessing the appropriate functionality like, we have to put a limit that level0 does not access the functionalities of level1 users or level2 user and so on. To do this we will check the permission on every view function that we made . To be very careful here that, for the function based view we will simple use the custom decorator. For example:- @group_required(‘level0’) def my_view_fucntion(request): … For more knowledge here is the code The things get a bit complex when we talk about class-based views, we can not simple just add a decorator function, but we have to make a permission-mixing class. For example:- class GroupRequiredMixin(object): “””Class Definition””” ….….. ……. class DemoView(GroupRequiredMixin, View): group_required = [u’admin’, u’manager’] # View code… For more you can take help from here To show strongly recommend and practice links : 1. 2. 3. 4. Feel free to write comments for any modification /suggestion) Happy Hacking :)
https://medium.com/@theparadoxer02/user-groups-with-custom-permissions-in-django-9eaea67b220e
CC-MAIN-2018-13
refinedweb
793
52.39
Introduction This started with a simple question in the C# forum: As a self taught amateur in c#, I have never found a reason to implement a struct instead of a class. Since I am self taught (No formal education) I would like to know what advantage would be gained by using a struct in lieu of a class? More importantly why when and where would it benefit my programs? And I started to reply...then a while later realized this was a lot more involved than a simple "use it then, don't use it then" type answer. So, when one of the replies suggested a permanent record of this, I thought it was a good idea. So, here it is: the difference between struct and class in one place. struct class A struct are the same as a class, except one is a Value type and the other is a Reference type. The end. Well, no - it's a simple statement, and it's both true and complete... but it doesn't explain anything, and it doesn't really mean anything either. So what is the difference? What does it mean? And when should I use a struct, and when a class? That's a lot bigger question that you probably thought - it involves a lot of background before you can make a decision to use one or the other. So, let's have a look at the background... public class MyClass { public int I; public int J; } public struct MyStruct { public int I; public int J; } public void UseClassAndStruct() { MyClass mc = new MyClass(); mc.I = 1; mc.J = 2; MyStruct ms = new MyStruct(); ms.I = 1; ms.J = 2; } public void UseClassAndStruct() { MyClass mc = new MyClass(); mc.I = 1; mc.J = 2; MyStruct ms; ms.I = 1; ms.J = 2; } Because you don't have to use the new keyword with structs. If you do, then the struct constructor is called, if you don't it isn't - simple as that. Unlike a class, the name of the struct is the struct itself, it is not a "pointer" to a instance. And that's important, because that is the whole point: a struct is the object, and class is a reference to the object. MyClass mc; That allocates memory on the stack to hold a reference to a MyClass instance in future, it does not create an instance of MyClass, and you will have seen that before - when you try to use any property or method of a class and you get a "Object reference not set to an instance of an object" exception and your program crashes, it's because you created a variable, but didn't create or assign an actual instance to the variable. It's a bit like referring to your car in terms of the parking space you normally use: if your wife takes the car and parks it somewhere else, then the parking space is empty, and your journey dies when you try to drive away... The space is the variable, the car is the instance. You have to explicitly create an instance of the class by using the new keyword: mc = new MyClass(); What this does is create a new instance of MyClass on the heap, and assign the reference to it to the variable mc. This is important, because the stack and the heap are different "types" of memory: the heap is a big "lump" of memory which is sorted out by the Garbage collector and all classes, methods and threads share it. The stack on the other hand is specific to a thread, and everything on the stack is discarded when you exit the method - which means that the mc variable is lost, but the data it references is not - if you have copied the reference to a variable outside the method, then you can still access it from the rest of your program. int i; double j; Point p; All create value types. int i = 3; int j = i; i = 4; Console.WriteLine("{0}:{1}", i, j); What does that produce? Obviously, it produces a string "4:3" - anything else would make coding very, very difficult! But...what if we do that with reference types? MyClass i = new MyClass(); i.I = 3; MyClass j = i; i.I = 4; Console.WriteLine("{0},{1}", i.I, j.I); This time, it prints "4:4" because i and j are references to the same instance in memory, instead of being separate, self contained value types. The same thing happens if we use our structs: MyStruct i = new MyStruct(); i.I = 3; MyStruct j = i; i.I = 4; Console.WriteLine("{0},{1}", i.I, j.I); This time, we get "4:3" again. When you assign a reference type variable to another reference type variable, it copies the reference, not the object. When you assign a value type variable to another value type, it copies the content of the object, not a reference to the object. If you call it with a value type such as a struct, a copy of the value is passed, and any changes you make will not be reflected back: public void ClassMod(MyClass mc) { mc.I += 100; Console.WriteLine(mc.I); } public void StructMod(MyStruct ms) { ms.I += 100; Console.WriteLine(ms.I); } MyClass mc = new MyClass(); mc.I = 3; ClassMod(mc); MyStruct ms = new MyStruct(); ms.I = 3; StructMod(ms); Console.WriteLine("{0},{1}", mc.I, ms.I); 103 103 103,3 Within the method, everything works the same. But outside...the changes we made to the struct inside the method affect the copy, not the original. Speed, under certain conditions. Structs can be a lot slower to use if you aren't careful: if you have a large struct, just calling a method and passing it as a parameter means it must be copied which takes time. But...if they are small (16 bytes or less) and you use a lot of them then they can be a lot faster than a reference type, because the Heap is not involved. Every time you create a reference type instance, the heap must be looked at, a suitable size bit of memory found and allocated and a reference to that returned. This takes time - quite a lot of it! A value type in contrast takes almost no work to allocate: copy the stack pointer, add the size of the struct to it for next time is pretty much all you have to do (and you have to do that for reference types as well so you have somewhere to store the reference to the heap memory!) What happens when you have a value type and you want to store it with other types in a mixed List (for example)? List<object> mixedList = new List<object>(); mixedList.Add("Hello there"); mixedList.Add(Form1); mixedList.Add(12); Um...12 is an int which is a value type, and so isn't derived from object...is it? Yes, it is: all value types derive from a special class called System.ValueType, which derives from object and what happens is that the value is "boxed" - a reference is created on the heap to hold the value type and it is copied there, and the reference to the boxed value is added to the list. When you cast it back to the original struct it is "unboxed" and you have a value type again. This is not a fast process and is one of the reasons you don't use structs for everything! So, to copy from MSDN[^]: "CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects. AVOID defining a struct unless the type has all of the following characteristics: The immutable bit is not enforced - it is just a recommendation, otherwise integers, doubles, and so forth wouldn't work! But...it's a very good idea to make structs immutable: it causes a lot less confusion. The Point struct does it by making the X and Y Setters private, so that it is obvious that all Points are different instances and that you don't move the original when you change a copy. All of the above has talked about structs being created on the stack, but that isn't quite accurate, because you can easily use structs on the heap as well: by embedding them inside classes. Again, you've used this a lot in the past: every Control has a Location property, which is a Point, and thus a struct. The data for the Point is included within the body of the class instance, and is allocated space on the heap along with the rest of the class data. And this is interesting...because every array in .NET is a reference type, even if the data it is an array of is a value type. So an array of integers is a reference type, and is allocated on the heap, not the stack: int[] myArrayOfInt = new int[100]; Does this make a difference? Yes, yes it can... How big is the stack? Seriously, how big is it? Clearly, it's smaller than the heap, but how much data can you get on it? Well... The default stack size for a .NET Windows application is 1 MB - but, it's only 256KB for 32-bit ASP.NET apps and 512KB for 64-bit ASP.NET apps, which is a significant difference if you are writing a web site... It can be changed: but it's not trivial - you have to modify the PE header of the executable for Windows apps, or you can change the settings in IIS for web apps if you are the admin. The Thread class has a constructor overload that takes a stack size, so that's pretty simple, if you use the full Thread model rather than the simpler BackgroundWorker. 1MB is not a lot, when you think about it: in terms of 32 bit integers, that's only 256K values, so if your struct has 16 integers - which is not a lot - you could only get 16K of them on the stack - and there is a lot of other stuff on there already: references, return addresses, that kind of thing, so it doesn't take that much to exhaust it. And for a 32Bit web site...you only get 4K of your structure on there in total. The heap is lot bigger, so you can store a lot more on there, and having all arrays be reference types means that you can declare some HUGE arrays without running out of memory. Did you know .NET has a maximum size of an object? It does, you know - 2GB is the total limit. Nor single object can ever exceed 2GB. Loads and loads of space... But...If you have a array of class instances, each individual class instance is created on the heap separately, so the array adds only the overhead needed to store the references: 32 bit on a 32 bit OS, or 64 bits on a 64 bit OS (which means that the maximum size of an array is different as well: 500 * 1024 * 1024 entries of 32 bit, or half that for 64Bit apps). But...for value types (including structs), the array size is the number of elements multiplied by the size of the element - so as your struct grows in size, the fewer of them you can get into an array before you run out of memory. So think very, very carefully before you start creating big structs: the MS suggested limit for structs of 16 bytes is actually a pretty good idea. :laugh: For most applications, only ever consider using a struct if it meets Microsoft recommendations: Small, Immutable and you aren't going to have to Box it. Generally speaking use a class for nearly everything. But, for special cases, consider a struct even if it doesn't meet those criteria if you need to save processing time in a tight loop - the lack of dereferencing that is involved in using a struct rather than a class can be a significant time saver. But beware! Passing structs to methods, or any other form of copying can cause a serious processing overhead. :laugh: The original poster of an excellent question: David C# Hobbyist.[^] - without whom, this would never have been born. And of course, his question: Struct vs Class[^] MSDN: without which we would all have nothing to confuse us with accurate but frequently unhelpful information, and inaccurate examples. :sigh: Original Version 2014 Feb 23 Spelling and grammar errors in "My Thanks to" section :O This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) public class Worker { public void Execute(Action act) { act(); } } [TestMethod] public void ActOnStructViaLambda() { var input = new MyStruct{I=3}; new Worker().Execute(() => input.I+=100); Assert.AreEqual(103, input.I); } var input = new MyStruct{I=3}; input.I+=100; Assert.AreEqual(103, input.I); .method public hidebysig instance void ActOnStructViaLambda() cil managed { // Code size 74 (0x4a) .maxstack 4 .locals init ([0] valuetype TCFDLL.MyStruct '<>g__initLocal0', [1] class TCFDLL.Class1/'<>c__DisplayClass2' 'CS$<>8__locals3') IL_0000: newobj instance void TCFDLL.Class1/'<>c__DisplayClass2'::.ctor() IL_0005: stloc.1 .line 22,22 : 13,14 '' IL_0006: nop .line 23,23 : 13,48 '' IL_0007: ldloc.1 IL_0008: ldloca.s '<>g__initLocal0' IL_000a: initobj TCFDLL.MyStruct IL_0010: ldloca.s '<>g__initLocal0' IL_0012: ldc.i4.3 IL_0013: stfld int32 TCFDLL.MyStruct::I IL_0018: ldloc.0 IL_0019: stfld valuetype TCFDLL.MyStruct TCFDLL.Class1/'<>c__DisplayClass2'::input .line 24,24 : 13,56 '' IL_001e: newobj instance void TCFDLL.Class1/Worker::.ctor() IL_0023: ldloc.1 IL_0024: ldftn instance void TCFDLL.Class1/'<>c__DisplayClass2'::'<ActOnStructViaLambda>b__1'() IL_002a: newobj instance void [mscorlib]System.Action::.ctor(object, native int) IL_002f: call instance void TCFDLL.Class1/Worker::Execute(class [mscorlib]System.Action) IL_0034: nop .line 25,25 : 13,43 '' IL_0035: ldc.i4.s 103 IL_0037: ldloc.1 IL_0038: ldflda valuetype TCFDLL.MyStruct TCFDLL.Class1/'<>c__DisplayClass2'::input IL_003d: ldfld int32 TCFDLL.MyStruct::I IL_0042: call void [Microsoft.VisualStudio.QualityTools.UnitTestFramework]Microsoft.VisualStudio.TestTools.UnitTesting.Assert::AreEqual<int32>(!!0, !!0) IL_0047: nop .line 26,26 : 13,14 '' IL_0048: nop IL_0049: ret } // end of method Class1::ActOnStructViaLambda OriginalGriff wrote:And also that I'm not offended by some the comments I get. Dictionary<Point, Color> pointColor; Paulo Zemek wrote:type that implements GetHashCode and Equals General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/728836/Using-struct-and-class-whats-that-all-about-2?msg=4785367
CC-MAIN-2020-16
refinedweb
2,442
72.26
81526/how-to-add-display-name-in-the-openshift-project Hi Guys, I have created an openshift project. I want to add a display name to this project. How can I do that? Hi@akhtar, You can add a display name or description in your Openshift project. You need to add this requirement in your oc new-project command. You can see the below-given example. $ oc new-project hello-openshift --description="This is an example project to demonstrate OpenShift v3" --display-name="Hello OpenShift" As per Bluemix Status Page today DevOps Delivery Pipeline ...READ MORE Using 'git status' command in the repository .., Some environment is dependent on a service ...READ MORE Hi@akhtar, A Kubernetes namespace provides a mechanism to ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/81526/how-to-add-display-name-in-the-openshift-project
CC-MAIN-2021-17
refinedweb
130
61.12
Prelude I’ve recently started a new job at an American start-up company. My position in the company is the one of Technical Lead – the person responsible for the selection of technologies around which the projects are being built. Since we’ll be doing mostly web development we’ve had a long kick-off discussion with the company’s CTO about the direction which we should initially take. He had PHP in mind, but I convinced him that Ruby or Python would make much better platforms for our futures apps. So he tasked me to research the two leading frameworks in the Ruby and Python land – namely Ruby on Rails 3 and Django 1.3. I had a week to prepare some prototypes with both and create on overview for my boss. I had some experience with Rails 2 a few years back and I have fairly decent knowledge of Ruby. My Python is not as fluent (admittedly), but still – I’ve played a lot with Python recently. Django, however, was completely new to me. In this article I’ll try to compare the frameworks in a totally friendly way; if you’ve expected an epic flame war post you may very well stop reading here. I’m obviously no Rails/Django guru, so if I’ve written something that is wrong – please feel free to correct me. Please, keep in mind that a short comparison article cannot even begin to scratch the immense power and complexity of such frameworks. The overview, that you’ll find here is a bit on the superficial side, but it should give you enough pointers to get you started. Hopefully this article will be useful to people that are in the same boat as was – picking between Rails and Django. Setup & Getting started Rails Linux & OSX The recommended (by me) way to install Ruby and Ruby on Rails 3.x is via RVM. RVM allows you to have several version of Ruby installed at the same time and to easily switch between them. It also allows you to create gem sets, which are quite handy in testing. After you’ve installed RVM it’s easy to install any Ruby interpreter and Rails. This example shows how to get RVM, MRI 1.9.2 and Rails current (3.0.9): Since RVM builds Ruby environments from source you might need to install a few dependencies first. After you’ve install RVM it will output those packages as instructions. If you’re using Z Shell (like me) you should replace .bash_profile with .zshenv or .zshrc. Windows While there are many ways to get Ruby on Rails installed on a Windows host, the simplest is certainly to use the RailsInstaller. It has only one little drawback – currently it comes with Ruby 1.8.7 bundled, but the recent beta already features Ruby 1.9.2. Your first Rails app As you can see the structure of a Rails project consists of quite a few folders and files. This is a bit intimidating at first, but becomes quite valuable once you’ve used to the predefined structure. You’ll find a good overview of the structure here. Open your browser and type as the url. If everything is OK you’ll see a Rails welcome page. At this point you should probably either start playing with scaffolding or read the rest of this article and start playing with scaffolding afterwards :–) For instance you can try: Open your browser and type as the url. “Magic” like this made Rails famous originally. By default Rails apps use SQLite as a database backend, so might have to install it as well. The rails script is useful for various tasks – code generation, plug-in installation, running a rails console, running a development web server, etc. Django Linux I prefer to install django from the distribution’s package manager. On a Red Hat distro like Fedora I would do: And on a Debian system: A popular alternative (that would work for OSX and Windows users as well) to this distro-specific approach is to use a python package manager like easy_install or pip. Windows The Bitnami Django stack is the simplest way to get Django and everything that it requires in a single step. Your first app Compared to Rails, Django created a much simpler project structure. There are only four files in here and only two are actual Django configuration files – settings.py and urls.py. manage.py is just a script useful for managing some aspects of the project (similar to the rails script) – it can sync the model with the database, run a development web server, run a django console, etc. To test the new project open in your browser. Features at a glance Rails Convention over configuration The centerpiece of Rails’s philosophy is called convention over configuration(CoC). This basically means that a Rails project has a predefined layout and sensible defaults. All components (models, views, controllers, layouts, css, javascript, etc) have standard places where you should drop them and the application picks them up without any additional effort on your part. People seem to underestimate the importance of CoC in practice initially – it makes it a lot easier to reason about a project and a lot easier to configure the project. On the other hand if some of the defaults don’t work for you – you’d have to jump through some hoops. Recent versions of Rails, however, have made it a lot easier to tweak the defaults. All in all I feel that CoC is a big win for developers and I guess many people share my opinion since CoC can now be found in many other frameworks as well. MVC to the bone Rails is a classical Model-View-Controller full stack web framework – it handle all aspects of a typical web application. What separates it from most of the MVC frameworks around is the heavy emphasis on REST. The domain objects are treated as resources and could be handled in a uniform manner using just the standard HTTP verbs like GET, PUT, DELETE, POST. REST is extremely good fit for data driven applications. As usual the model houses the application’s business logic, the controller invokes functionality from the model layer and feeds the resulting data to the view layer, which display the data in a meaningful way to the user. The model layer is the home of your domain objects and the business logic surrounding them. Domain objects (a.k.a. entities) are mapped to database tables (at least in RDBMS). Unlike most object relational mappers Rails’s ActiveRecord (the default ORM; could be substituted with something else if you wish) doesn’t require you to explicitly declare the structure of the objects, but rather extracts it automatically from your DB table definitions. A simple class, modeling an application user might look like this: Note that the validation methods are entirely optional (but highly recommended) – the class could have very well had an empty body. Rails would know to look for a table named Users in the database and extract the field information from it. Rails generates automatically for us “finders” that we can use to make queries about objects in pure Ruby. It also provides an elegant DSL to express relationships between various model classes (belongs_to, has_many, etc) In the view layer Rails has traditionally relied on HTML templates with Ruby code embedded in them (html.erb). There are a lot of community contributed alternatives, however, with HAML being the most prominent one. On a similar note Rails allows you to use SASS as a replacement for traditional CSS. Another centerpiece in Rails is the “Don’t Repeat Yourself”(DRY) principle. In the view layer partial templates, layouts and helpers are some of the tools available to help you abide by that principle. You’ll certainly make heavy use of them in your applications so you should pay them some special attention. Database migrations Everyone that has done some serious programming knows that it’s not realistic to presume that the initial database schema won’t ever change – fields get added/removed, new tables get introduced, etc. All those changes are commonly referred to as “migrations” and traditionally every team unrolls its own handling of the problem. On my last job I was tasked at some point to write a tool in Java that analyzed a config file and a directory structure filled with SQL scripts and applied them selectively to various target databases. In Rails you get this functionally for free – you can express your migrations as simple Ruby scripts and you can use rake to generate the appropriate SQL statements for any supported database. Here’s a simple migration script, that creates the Users table: The up method gets invoked when the migration is applied and the down method gets invoked when it’s reverted. Rails 3.1 will offer even more elegant migrations. To execute all migrations: Ajax from within Rails features tight integration with JavaScript and AJAX. Versions prior to 3.1 shipped by default the prototype and scriptaculous JavaScript libraries. In version 3.1 jQuery will replace them as the default JavaScript library. Making and handling AJAX requests in Rails is generally very easy – a big advantage in today world ruled by rich and dynamic web UIs. Extensibility Rails is extendable through a multitude of community supplied plugins that could add incredible functionality to your apps for free. Some of my favorite plugins are jQuery for Rails, client side validations and Rails Admin. Testing is not optional What I particularly like about Rails is that it heavily promotes testing your code. All of the Rails generators would generate test stubs, that you’ll do good to fill in. Rails supports all major Ruby test frameworks – Test::Unit, RSpec, Cucumber. You have fixtures support, test database support, the ability to run unit and functional test separately. I don’t recall using any other framework that pays as much attention to having tests as Rails and for that I can only congratulate the Rails team. Compatibility with Ruby versions There are two major version of Ruby out there presently – Ruby 1.8.7 and Ruby 1.9.2. Ruby 1.9.2 offers substantial language and performance improvements, so you should be pleased to hear that Rails supports both major Ruby versions. Rails 4.0 will drop support for Ruby 1.8.x. Rails can also be run on top of JRuby and Rubinius. Deployment options The most common deployment options for Rails are currently Apache HTTPD or NginX and Phusion Passenger (mod_rails). People shopping for cloud Rails deployment should definitely take a look at Heroku. Rails also runs on alternative Ruby implementations like JRuby and Rubinius (as mentioned above), that offer exciting new possibilities. For instance using JRuby allows you to deploy a Rails app into a Java application server like JBoss or Glassfish and to tap into all those great Java libraries and frameworks around. Using JRuby also gives you the opportunity to deploy your apps on Google’s App Engine. Django A simpler project layout While I had some experience with Rails from a couple of years ago, Django was something totally new to me. I expected it to be more or less Rails for Python, but when I created my first Django app I was surprised to see that the project folder consisted of only three files (I’m obviously not counting the python package file init.py). My initial surprise aside it turned out that most differences were just superficial and that Django and Rails have quite a lot of similarities. I’ll, however, speak a bit more about the different stuff than the similar stuff. MVC(MTV), Django style While Django is a MVC controller framework as well, it’s built around a different mindset. Django is totally configurable and minimalistic framework that empowers the developers to tailor it to their needs. A Django project is comprised of autonomous and reusable apps. Apps on the other hand are comprised of models, views and templates. Django differs a bit in terminology with Rails – the Rails controllers are views in Django and the Rails views are called templates in Django. You can sometimes hear that Django is a Model-Template-View framework – that shouldn’t confuse you. Although the terminology is different the principles are the same. Django’s default ORM is somewhat reminiscent of frameworks like Hibernate. Entity classes declare explicitly the all the attributes. Let’s consider again the User model class: Both approaches have their strengths and weaknesses an usual. In Django’s case we have increased verbosity, but on the other had we don’t have to inquire the database to figure out the exact definition of model records. Like in Rails we get useful “finders” that can be used to query for model objects in pure python (as opposed to using sql). In the template layer While ERB is basically HTML with Ruby embedded in it, Django features a custom templating language with it’s own (extendable) tag library. This generally means that Django templates tend to be a bit cleaner than Rails’s templates, since you’re not allowed to abuse them very much. On the other hand you can do virtually anything by embedding code directly in a template, so as usual – each design decision has its pros and cons. Django supports alternative templating libraries, so you’re covered in case you don’t like the default one. Django also features a powerful form generation/handling facilities that integrate seamlessly with the templating layer. For instance – it very easy to generate a form matching the structure of a domain model object with automatic property validation. You’re in charge Django has doesn’t adhere to the Rails CoC philosophy. It’s assumed that developers know best what layout and configurations options make the most sense in their applications. I haven’t played that much with Django yet, but I still haven’t come by two different Django apps that are structured in the same manner. While I understand the benefits of Django’s approach I still prefer Rails’s approach. I’ve worked long enough to know that you’re rarely in the position to make better decisions about the structure and the defaults of your app, than the exceptional developers with huge experience that develop frameworks like Rails and Django. To illustrate this consider the strong emphasis Rails places on REST. In Django you could certainly use restful access your resources as well, but it’s all up to you. The framework makes no suggestions. You can unroll any URL mapping scheme by simply associating regular expressions in urls.py with callback view functions: from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('', url(r'^$', 'djangodemo.views.home', name='home') url(r'^users', 'djangodemo.view.users', name='list_users')) An url is mapped to the callback function, which in turn either renders a template or directly returns some Http response. Free admin Django has a built-in support to generate an admin UI for your website. This is a very useful feature indeed and is supported in Rails as well through plugins (I’ve mentioned the one I like the best). Database migrations One of the few gripes I have with stock Django is that it doesn’t offer an alternative to Rails’s migrations. Luckily there is South – an extension that provides a simple, stable and database-independent migration layer to prevent all the hassle schema changes over time bring to your Django applications. I highly recommend it to everyone planning to use Django. JavaScript and AJAX Unlike Rails, Django doesn’t bundle any JavaScript libraries. You have to pick a JavaScript framework yourself (which a trivial process). The AJAX support in Django is both basic and extremely powerful in the same time – request.is_ajax(). What this means is that you can check if a request was regular or an AJAX request and respond accordingly. You don’t need much more than that. More details can be found here. The great divide Some of you probably know that Python is currently at a bit of a crossroads. Python 2.x was the stable Python version for many years, but recently it was replaced by Python 3.x. Python 3.x is all around great in my personal opinion, but unfortunately it’s backward incompatible with the older 2.x series. For that reason very few high profile projects still don’t support it – Django is one such project. The current version 1.3 require at least Python 2.4 and will run with every Python up to 2.7. This is a bit of a disappointment since you’ll be missing on a few very cool new features. On a more positive note Python 2.7 did backport some goodies from Python 3, so not all is lost. I’ve read (at totally unofficial places) that Django 2.0 will be targeting Python 3 and I expect it will be available in about a year. Deployment Python is quite mature technology and offers you a nice array of deployment options – Apache, Nginx and my favorite – Google App Engine. Python, being one of the two supported languages on the App Engine (the other one is, of course, Java) makes it very easy to deploy Django apps on the App Engine (though you’ll need the Django support for non-relational databases to be able to use it). The also the possibility to deploy Django apps on Java or .Net infrastructure using Jython or IronPython. Community When you’re selecting the technology for a major project you have to make sure that the technology is in good shape – there is a solid community around it, there is no lack of support, innovation and deployment options. Both Google trends and stackoverflow.com (by the number of question about tagged with django or rails) indicate that Rails currently has larger community than Django. I haven’t had any direct communication with the Django community yet, but I’ve found a lot of excellent resources about Django on-line. Rails has one of the most vibrant, passionate and innovative communities. I’ve had contact with a lot of people from the Rails community and I’m certain that it has played a tremendous role in Rails’s growth. Tooling Traditionally Ruby & Python hackers have been working with just a powerful programmer’s editor like Emacs, vim or TextMate. While there is nothing inherently wrong with this approach (I’m an avid Emacs user myself), I do find IDEs quite helpful when working on larger code bases, with their trademark features such as intelligent autocompletion (aka intellisense), safe refactorings, on-the-fly syntax checking, etc. So here’s what we’ve got: - RubyMine – hands down the best Ruby and Rails IDE I’ve ever used. The list of features is epic as is the quality of the project. It support Rails 3, git, RSpec, Cucumber, sass, haml and many other cool Ruby/Rails related technologies. Sure, it’s a commercial project, but is priced very reasonably. - Aptana Studio – a Web development IDE, built on top of the Eclipse platform. Among many other features it supports Ruby on Rails. - Komodo – an IDE focusing on dynamic programming language. Great support for both Django and Rails development. - PyCharm – from the same company that develops RubyMine, PyCharm is the king of IDEs when it comes down to Python. It has full featured Django support – there is even autocompletion in the Django templates. - PyDev – an Eclipse plug-in for Python and Django development. I have to admit I’m totally biased. Having been a long time Java developer I’ve grown extremely fond of the exceptional IntelliJ IDEA. RubyMine and PyCharm are both based on the IntelliJ platform and bring to the Ruby and Python developers much of the might and magic of IDEA. There are both commercial products, but their price tags are quite low and their quality is great – highly recommended. I’m not affiliated in any way with any of these products – I just happen to like them that much. Resources The are LOTS of resources about Rails and Django on-line. Here are just my favorites. Rails - Rails Guides – best short introduction to Rails ever. Immediately updated for new Rails versions, fantastic starting point for any aspiring Rails developer. - Rails Tutorial – best Rails 3 book on the market and it even has a free on-line edition. Nice follow up of the Rails Guides. - RailsCasts – Ryan Bates in true Ruby hero. He has compiled a unique set of high quality Rails screencasts that often illustrate some advanced techniques. And they are all free. We all owe a very big “Thanks!” to Ryan. Django - Official Docs – best official project documentation I’ve read. It’s actually so good, that I never (well – almost never) bothered to look for anything else. All my questions were answered by the official documentation. Epilogue Choosing Django or Rails is basically a win-win situation – you cannot go wrong. There are too many similarities between the frameworks and the differences are not something paramount. Rails places a heavy emphasis on convention over configuration, provides you with more defaults and does a can do a lot of heavy lifting for you automagically. Django on the other hand let’s you specify most configuration details yourself, without making the configuration burdensome (like that of older Java web frameworks). Rails has always been leading on the way of innovation – constantly integration some of the latest and greatest technologies around (recent examples being jQuery, Coffee Script and SASS). From time to time backward compatibility is sacrificed for the greater good, so that is something that you should consider as well. Django is certainly much more conservative framework as far as backward compatibility is concerned – after all it still support Python 2.4. I guess in the end the choice really boils down to two things – whether you like Ruby or Python better and whether you like the defaults imposed to you by Rails. I’ve planned to write a much longer and detailed article, but it’s summer here and it’s sunday and I’d rather go out and drink a few beers with my friends. Hopefully you’ve enjoyed the article. I’ll try to expand it a bit in the coming days. P.S. Btw, in case you’re wondering – we’ve picked Rails for our company’s projects. It was a very close call, though, since I really liked a lot of aspects of Django as well.
http://batsov.com/articles/2011/06/19/django-vs-rails/
CC-MAIN-2014-15
refinedweb
3,790
62.48
A C++ Macro to Stub Interface Methods In my previous column, I showed how to create a class library in C++ that can be called from a macro, and presented a very simple function in the class library that adds braces for you, suitable for use after typing an if or for statement. In this column, I show you a somewhat meatier piece of code: a macro for use with a class that implements one or more interfaces. When you run the macro, it adds empty function bodies for all the functions in the interface. I developed this as another function in the class library from the last column, so I won't repeat the instructions for setting up your projects and your macros, associating the macro with a toolbar button, or closing Visual Studio each time you rebuild the class library code. Elements, Classes, Interfaces, and Bases When you write a class in Visual C++, the Design Time Environment thinks of it as several things, including a class and a CodeElement. It has base classes, each of which is also a CodeElement. Your class, its bases, and even its functions can all be represented as objects with properties such as Name and Type—and your macros can manipulate those objects. For example, an object that represents a class has a method called AddFunction(), which actually adds functions to one of your classes, right from the macro. That's the heart of this macro: a loop that calls AddFunction() repeatedly to add each function that's in the interface your class implements. This generates the code inside your class, and it's quite fun to see. I found the code pretty hard to write, and you're likely to find it hard to read, for three reasons: - It contains parallel object hierarchies: one under the EnvDTE namespace with classes such as CodeElement, and one under the Microsoft::VisualStudio::VCCodeModel namespace with classes such as VCCodeElement. The functionality is not quite the same in the two hierarchies. - Most of the functions return quite general types, or the properties have quite general types. For example, the Namespaces property of a code model is not a CodeNamespace or a VCCodeNamespace, but rather a CodeElement. That means the code contains a lot of static_cast<> and dynamic_cast<>. (Option Strict Off in Visual Basic hides a lot, doesn't it?) I cast to a Microsoft::VisualStudio::VCCodeModel class only when the methods or properties I want aren't in the equivalent class from the EnvDTE namespace. - The arrays and collections returned from these functions are all one-based, and the Count property tells you how many items are in a collection. Bear with me, though, because going through this exercise gives you more than just the ability to write C++ macros in C++. You can also learn how Visual Studio and its wizards think of your code, and how they work internally. The general structure of the InsertMethods() function is, in pseudo-code: Get a collection of the classes in the file you have open. For each class: * Get a collection of the bases, which includes interfaces. For each base: * Determine if it is an interface, and if so: * Get all the functions in the interface. For each function: * Determine if it is not yet implemented in this file, and if not: * Add the function to the class; * Get all the parameters to the function; * Add the parameters, one at a time, to the function. Page 1 of 3
http://www.developer.com/net/cplus/article.php/3354011/A-C-Macro-to-Stub-Interface-Methods.htm
CC-MAIN-2015-18
refinedweb
583
65.25
15 February 2011 11:14 [Source: ICIS news] SINGAPORE (ICIS)--DuPont Titanium Technologies will increase the price of titanium dioxide (TiO2) sold in the Asia-Pacific region by $300/tonne with effect from 1 April, the company announced on Tuesday. This is the second price hike by DuPont this year after a $200/tonne price increase effective from 1 January that was announced in November 2010. TiO2 is mainly used as a white powder pigment in products such as paints, coatings, plastics, paper, inks, fibres, food and cosmetic. Major TiO2 producers have been raising prices in recent months due to rising raw material costs. The DuPont price hike announcement follows Huntsman’s $200/tonne increase effective from 1 March. DuPont is the world’s largest manufacturer of TiO2 and has plants in the ?xml:namespace>
http://www.icis.com/Articles/2011/02/15/9435349/dupont-to-increase-asia-pacific-tio2-by-300tonne-from-1-april.html
CC-MAIN-2014-42
refinedweb
135
50.16
Since Cheetah supports two basic modes: dynamic and precompiled templates, you have a lot of options when it comes to utilizing Cheetah, particularly in web environments. There is added speed to be gained by using pre-compiled templates, especially when using mod_python with Apache. Precompiling your templates means Apache/mod_python can load your template’s generated module into memory and then execution is only limited by the speed of the Python being executed, and not the Cheetah compiler. You can further optimize things by then pre-compiling the generated Python files (.py) down to Python byte-code (.pyc) so save cycles interpreting the Python. Suppose you have a template that looks something like this: #attr title = "This is my Template" <html> <head> <title>\${title}</title> </head> <body> Hello \${who}! </body> </html> Figure 1. hello.tmpl In order to compile this down to a Python file, you need to only execute the cheetah compile hello.tmpl command. The results will be a Python file (.py) which you can then treat as any other Python module in your code base. Typically for the template in Figure 1, I could easily import it post-compilation as any other Python module: from templates import hello def myMethod(): tmpl = hello.hello(searchList=[{'who' : 'world'}]) results = tmpl.respond() Figure 2. runner.py Note: If you use the #implements directive, respond may not be your “main method” for executing the Cheetah template. You can adjust the example above in Figure 2 by using getattr() to make the lookup of the main method dynamic: def myMethod(): tmpl = hello.hello(searchList=[{'who' : 'world'}]) mainMethod = getattr(tmpl, '_mainCheetahMethod_for_%s' % tmpl.__class__.__name__) results = getattr(tmpl, mainMethod)() Figure 3. Dynamic runner.py
http://packages.python.org/Cheetah/recipes/precompiled.html
crawl-003
refinedweb
281
56.96
Introduction: End. well,that’s pretty Please change the color schema of your blog. Seriously, please! Great info, on the other hand. my eyes are bleeding! Blog link of the week 48 thats a good information on value and reference types storage. so all member fields and property fields get stored on heap though they are value types. The parameters/value types declared in methods in the type are stored on stack (true??). so this gives a thought on whether to define a field as member field/property or pass it as a parameter to the method. consider this.. public class ClassB { public string name; public int age; public int PrintAge() { Console.WriteLine("Age – " + age.ToString()); } public int PrintAge(int paramAge) { Console.WriteLine("Age – " + paramAge.ToString()); } } PrintAge execution when a parameter is passed, would be faster to PrintAge(). isnt?? simply because age (the member field) is stored on heap where as the parameter to method paramAge will be stored on stack. any corrections? am unable to see the figure in the blog..am i already gone blind?? 🙂 Not as such, figure will be there soon. I apolize for the same. PingBack from
https://blogs.msdn.microsoft.com/saurabhv/2004/11/26/how-reference-and-value-types-are-stored-in-memory/
CC-MAIN-2019-51
refinedweb
192
67.76
- Training Library - Containers - Courses - Introduction to Helm Architecture give you a quick overview of the architecture as used within Helm. This will be useful to you, as it helps you to understand the different moving parts and how they work collectively together. The good news is that the Helm 3 architecture has been simplified, yet made more secure at the same time. Often, more secure means more complexity. but this is certainly not the case for Helm 3. Helm 3 uses the following displayed client-only architecture. This architecture, when compared to the previous Helm 2 client server architecture, is both simpler and more secure. Previously, Helm 2 depended on a cluster-hosted component named Tiller. Tiller, configured with a service account in role, needed sufficient permissions to install chart resources into the cluster, potentially across multiple namespaces. The Helm 2 client was designed to communicate through Tiller with Tiller actually performing the duties of resource creation, et cetera. Now, with Helm 3, this is no longer the case. Instead, the Helm 3 client now communicates directly with the Kubernetes API server. The reason for this change stems mainly from the fact that Kubernetes, as of version 1.16, has RBAC, or role-based access control available and enabled by default. With RBAC, the Helm 3 client can now simply leverage the permissions managed and configured through the standard .kube/config file. This is the same file that the kubectl utility uses to authenticate into the cluster. So, to be clear, when using the Helm 3 client to deploy a chart into a Kubernetes cluster, the Helm 3 client will authenticate to the cluster using the same credentials stored and managed within the .kube/config file, the same mechanism that kubectl uses. The permissions required to install the various chart resources will be governed by the RBAC permissions configured within the cluster. Now, before an actual chart installation takes place within a cluster, the chart first needs to be rendered. In Helm 3, this is done client side. The rendering process involves taking each of the templates stored internally within the chart and converting them or rendering them into raw Kubernetes manifest files which the Kubernetes API server understands and can process. Deploying a Helm chart results in a release being created. When it comes to release management within the cluster, Helm 3 stores release information using Kubernetes Secrets. Previously, Helm 2 used configmaps. Whenever a chart modification takes place, such as creating, upgrading, and/or rollbacks, then this results in a new Kubernetes Secret resource being created within the same Kubernetes namespace in which the actual deployment took place. Okay, that completes this lesson. In this lesson, I provided you with a brief overview of the underlying Helm 3 architecture and the key differences between Helm 3 and Helm 2. You learnt the Helm 3 uses a simpler architecture and no longer requires the Tiller component. Okay, go ahead and close this lesson,.
https://cloudacademy.com/course/introduction-to-helm-1034/helm-architecture/
CC-MAIN-2021-43
refinedweb
494
55.03
Offline Evil #archlinux@freenode channel op and general support dude. . files on github, Screenshots, Random pics and the rest Offline What font is that? I guess that's 'Lucida' bundled with maple. Sorry for my English Offline Nice, xmonad inside what ? or what bar/panel is that ? Offline dieelt wrote: Nice, xmonad inside what ? or what bar/panel is that ? It's Xmonad running as window manager for gnome 3 so the bar is gnome-panel in fallback mode with the theme Zukitwo. Offline... usability == arch + i3 + urxvt + vim + ranger + dwb + vlc + cmus + mutt + shitload of scripts Offline Ok, might as well send my xmonad setup, since I got started.. nothing fancy here either... Works ok for me... have some rules for different windows to go different workspaces and dzen2 for launching apps. Also I have modified the tiling views so that there is a tab view without window borders, with which I get a fullscreen window, when there is only one window in the workspace. Other screen is from laptop, so the blue thingy under the terminals came with the screenshot. My xmonad.hs. Oh also have a resolution change/display "detection" script for dual screen/one screen launched on startup: xiniti.rc for slim. Script for resolution: nayttoXmon Last edited by aparaatti (2012-04-01 10:21:58) Offline beautiful set up as well as an excellently eclectic taste in music is that a bash script running in your top bar? mind sharing? Offline beautiful set up as well as an excellently eclectic taste in music is that a bash script running in your top bar? mind sharing? Thanks The right dzen bar is fed by conky; I don't like to call numerous new processes every second or so via shell script. .dzen_conkyrc # conkyrc file for dzen, ^ denotes dzen argument background no out_to_console yes out_to_x no override_utf8_locale yes update_interval 2 update_interval_on_battery 5 total_run_times 0 mpd_host localhost mpd_port 6600 music_player_interval 3 if_up_strictness address TEXT ${if_mpd_playing}[${mpd_elapsed}/${mpd_length}] ^fg(\#F3F2DD)${mpd_smart 57}^fg()$endif ^i(/home/mememe/.dzen/xbm8x8/cpu.xbm) ^fg(\#EEEEEE)${if_match ${cpu} < 10} $else${if_match ${cpu} < 100} $endif$endif${cpu}^fg() ^i(/home/mememe/.dzen/xbm8x8/mem.xbm) ^fg(\#EEEEEE)${if_match ${memperc} < 10} $else${if_match ${memperc} < 100} $endif$endif${memperc}^fg()${if_up wlan0} ^i(/home/mememe/.dzen/xbm8x8/wifi_02.xbm) ^fg(\#EEEEEE)${if_match ${downspeedf wlan0} < 10.0} $else${if_match ${downspeedf wlan0} < 100.0} $endif$endif${downspeedf wlan0} ${if_match ${upspeedf wlan0} < 10.0} $endif${upspeedf wlan0}^fg() @ ^fg(\#EEEEEE)${wireless_link_qual_perc wlan0}^fg()$else ^i(/home/mememe/.dzen/xbm8x8/net_wired.xbm) ^fg(\#EEEEEE)${if_match ${downspeedf eth0} < 10.0} $else${if_match ${downspeedf eth0} < 100.0} $endif$endif${downspeedf eth0} ${if_match ${upspeedf eth0} < 10.0} $endif${upspeedf eth0}^fg()$endif ^fg(\#648F6F)${if_match "${acpiacadapter ADP0}" == "on-line"} ^i(/home/mememe/.dzen/xbm8x8/ac.xbm)^fg()^fg(\#EEEEEE)$else${if_match ${battery_percent BAT0} > 66}^bg(\#A9F3A9)^fg(\#63AE6D) ^i(/home/mememe/.dzen/xbm8x8/bat_full_02.xbm)^fg()$else${if_match ${battery_percent BAT0} > 33}^bg(\#FFF2B1)^fg(\#FFAE73) ^i(/home/mememe/.dzen/xbm8x8/bat_low_02.xbm)^fg()$else^bg(\#FFB1B1) ^fg(\#BF3030)^i(/home/mememe/.dzen/xbm8x8/bat_empty_02.xbm)^fg()$endif$endif^fg(\#555555)$endif ${if_match ${battery_percent} < 10} $else${if_match ${battery_percent} < 100} $endif$endif${battery_percent}^fg() ^bg() ^fg(\#FAFFDA)${time %a %b %d %H:%M} All those "if_match" queries have it look a bit atrocious, but with (tmk) no conky object available to adjust another to a fixed width they are necessary to keep things from moving around. It checks whether mpd is playing, eth0 or wlan0 up, and if the laptop runs on AC or battery to set the displayed objects and icons appropriately. If on battery, that object's color is set according to charge level. Last edited by misc (2012-04-15 16:41:58) Offline dieelt, That thumbnail is over sized in terms of dimensions, but fits under our 50k limit. I worry mostly about the byte count, so I'll leave it alone. Just be aware of our picture policy Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday You assume people are rational and influenced by evidence. You must not work with the public much. -- Trilby ---- How to Ask Questions the Smart Way Online... Sounds like you're using Pseudo Transparency and not True Transparency. Change the [6666] to change the transparency 0000->9999 or AAAA->DDDD and FFFF to be solid. ! URxvt !----------------------------------------------------------------- URxvt*buffered: true URxvt*transparent: false URxvt*depth: 32 URxvt*background: rgba:0000/0000/0000/6666 URxvt*scrollBar: false URxvt*internalBorder: 10 Last edited by Shrak (2012-04-22 00:23:22) Offline Finally got around to tidying up my code. xmonad.hs traybarscript.zsh conky_bottom Here's to hoping it's not a mess like last time! Offline Finally got around to tidying up my code. xmonad.hs traybarscript.zsh conky_bottom Here's to hoping it's not a mess like last time! Nice desktop! I'm new to xmonad and I think I'm gonna start with your config . Can you point me where those icons are? (the ones that are referenced in the conky file). Geeks & Linux Atelier An eye for an eye ... ends in making everybody blind -- Mahatma Gandhi dotfiles Offline I would love to see your vimrc! Even if it's just the tab characters. Offline Offline What does it depend on whether your tabs are colorized? You are using non-graphical vim, right? Offline
https://bbs.archlinux.org/viewtopic.php?pid=1084047
CC-MAIN-2016-36
refinedweb
902
66.33
C language has numerous libraries that include predefined functions to make programming easier. In C language, header files contain the set of predefined standard library functions. Your request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a ‘.h’ an extension. By including a header file, we can use its contents in our program. C++ also offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the “.h” extension but in C, all the header files must necessarily end with the “.h” extension. A header file contains: - Function definitions - Data type definitions - Macros It offers the above features by importing them into the program with the help of a preprocessor directive “#include”. These preprocessor directives are used for instructing compiler that these files need to be processed before compilation. In C program should necessarily contain the header file which stands for standard input and output used to take input with the help of scanf() and printf() function respectively. In C++ program has the header file which stands for input and output stream used to take input with the help of “cin” and “cout” respectively. There are of 2 types of header file: - Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them. - User-defined header files: These files are defined by the user and can be imported using “#include”. Syntax: #include <filename.h> or #include "filename.h" We can include header files in our program by using one of the above two syntax whether it is pre-defined or user-defined header file. The “#include” preprocessor is responsible for directing the compiler that the header file needs to be processed before compilation and includes all the necessary data type and function definitions. Note: We can’t include the same header file twice in any program. Create your own Header File: file:chevron_rightfilter_none - Include your header file with “#include” in your C/C++ program as shown below:chevron_rightfilter_none - Below is the output of the above program: Including Multiple Header Files: You can use various header files in a program. When a header file is included twice within a program, the compiler processes the contents of that header file twice. This leads to an error in the program. To eliminate this error, conditional preprocessor directives are used. Syntax: #ifndef HEADER_FILE_NAME #define HEADER_FILE_NAME the entire header file #endif This construct is called wrapper “#ifndef”. When the header is included again, the conditional will become false, because HEADER_FILE_NAME is defined. The preprocessor will skip over the entire contents of the file and the compiler will not see it twice. Sometimes it’s essential to include several diverse header files based on the requirements of the program. For this, multiple conditionals are used. Syntax: #if SYSTEM_ONE #include "system1.h" #elif SYSTEM_TWO #include "system2.h" #elif SYSTEM_THREE .... #endif Standard Header Files And Their Uses: - #include<stdio.h>: It is used to perform input and output operations using functions scanf() and printf(). - #include<iostream>: It is used as a stream of Input and Output using cin and cout. - #include<string.h>: It is used to perform various functionalities related to string manupulation like strlen(), strcmp(), strcpy(), size(), etc. - #include<math.h>: It is used to perform mathematical operations like sqrt(), log2(), pow(), etc. - #include<iomanip.h>: It is used to access set() and setprecision() function to limit the decimal places in variables. - #include<signal.h>: It is used to perform signal handling functions like signal() and raise(). - #include<stdarg.h>:It is used to perform standard argument functions like va_start() and va_arg(). It is also used to indicate start of the variable-length argument list and to fetch the arguments from the variable-length argument list in the program respectively. - #include<errno.h>: It is used to perform error handling operations like errno(), strerror(), perror(), etc. - #include<fstream.h>: It is used to control the data to read from a file as an input and data to write into the file as an output. - #include<time.h>: It is used to perform functions related to date() and time() like setdate() and getdate(). It is also used to modify the system date and get the CPU time respectively. - #include<float.h>: It contains a set of various platform-dependent constants related to floating point values. These constants are proposed by ANSI C. They allow making programs more portable. Some examples of constants included in this header file are- e(exponent), b(base/radix), etc. - #include<limits.h>: It. Below is the program to illustrate the use of header file: Using math.h, The value is: 729 Using stdlib.h, the string to long int: 12345 Using string.h, the strings s2 and s3: ForGeeks ForGeeks
https://www.geeksforgeeks.org/header-files-in-c-cpp-and-its-uses/?ref=rp
CC-MAIN-2021-10
refinedweb
816
56.76
Published 11 months ago by artmonger I'm passing two variables from the index page to the create page. The output inserts white-space into the characters of the variable if I concatenate the two variables in the controller. Other times, it only gives me the last character, or the first characters and cuts off the last one. Here's the part on my index page: <li> {{ $chicken->variety }} {{ $chicken->name }} <a href="{{ route('/chickens/{variety}{name}/create', ['variety' => $chicken->variety, 'name' => $chicken->name]) }}">create</a> </li> Here's the Route: Route::get('/chickens/{variety}{name}/create', [ 'as' => '/chickens/{variety}{name}/create', 'uses' => '[email protected]' ]); With just one variable, it was working great. I could pass a breed name and I'd get it on the create page, such as "Create a new Sebright", etc. However, I want to pass in a variety slug, such as "Create a new Golden Sebright" or "Create a new "Silver Sebright", etc. Here's my controller method: public function create($variety, $name) { $variety; $name; return view('chickens.create', compact('variety', 'name'); } What do I get? Very strange things, like... "Create a New l" That's the last character in Aseel. or if I click on an Ameraucana, I end up with "Create a New a" Again, the last letter. I tried this, $breed = $variety. ' ' .$name; and then passing $breed to compact()... But I get thinks like "American Buf f". Note, the space between the f's. dd($breed); and I get two strings... One is the first word, the second is the last character of the breed name. I've tried using with(); but I still find problems. What do you think? You should probably separate both variables in the url with a slash. Also, you don't have to repeat the route again in the 'as'. That parameter is for naming the route. // Like this Route::get('/chickens/{variety}/{name}/create', [ 'as' => 'chickens.create', 'uses' => '[email protected]' ]); // Or this if you have an up to date version of Laravel Route::get('/chickens/{variety}/{name}/create', '[email protected]')->name('chickens.create'); // The name isn't mandatory I tried this: Route::get('/chickens/{variety}/{name}/create', '[email protected]'); and I changed my route method to, but I'm getting an error Exception, Route[/chickens/{variety}/{name}/create] not defined... How is that possible? The strings, match. The route() method requires named routing. when I use named routing, I get my page dumping all my chickens. But when I select the create link I only get the last letter of the breed name. That's just strange. Yeah something is going wrong somewhere. Can you show me the controller and view please. Also, if you can show me where you're passing the parameters for the URL (e.g: a form or button). Alternatively, what you could do is just have a generic /chickens/create route and have a couple of select boxes which a user selects for the variety and name. Named routing should have nothing to do with it. Please can you use three backticks ``` before and after your code blocks so we can actually see what you are doing. Please list your routes and your controller. I came up with another solution: ! Your original problem was with this line here: <a href="{{ route('/chickens/{variety}{name}/create', ['variety' => $chicken->variety, 'name' => $chicken->name]) }}">create</a>. When you use the route() method, you give it a name instead of the URL. You were passing the whole route AND the wildcards which is a no no and a recipe for disaster (which happened). When you use the as key on the route or when you chain on ->name('some.name'); is when a route becomes a named route. So for example, to use the route() method: Route::get('/', '[email protected]')->name('home'); Route::get('/', ['uses' => '[email protected]', 'as' => 'home']); // both of them are the same // Then i'd do something like <a href="{{ route('home') }}">a link</a> // if i need to pass one parameter, i would pass it as the second argument <a href="{{ route('home', $user->username) }}">a link</a> // if i need to pass more than one parameter, i would pass an array as the second argument <a href="{{ route('home', [$user->username, $article->slug]) }}">a link</a> // You can also do route model binding where you just pass the whole object to the second argument <a href="{{ route('home', $user) }}">a link</a> P.S: you don't need to declare arguments from a function/method within the function/method. This is what you were doing: public function create($variety, $name) { $variety; $name; return view('chickens.create', compact('variety','name')); } You can just do: public function create($variety, $name) { return view('chickens.create', compact('variety','name')); } Some good feedback there. Also, to understand 'strange String Phenomena' You were hoping to set '/chickens/{variety}{name}/create' as your route You have two variables next to each other with no means to separate them So, if you requested this route; Create a new Golden Sebright Laravel router its trying to assign some part of the string to variety and some to name with no way to delimit them. It might do $variety = 'Create a new Golden Sebrigh' and $name='t' or $variety = 'Create a new G' and $name='olden Sebright' or $variety = 'C' and $name='reate a new Golden Sebright' Laravel has no way of knowing what was in your head about where the split should be. Assume for some SEO reason you want to pass a 'slug' to the controller then just do that but you will need to split it down again which you can do in your route. @foreach($chickens as $chicken) <li> @if($chicken->is_bantam == true) <label>bantam</label> @endif {{ $chicken->variety }} {{ $chicken->name }} <a href="{{ route('chickens.create', $chicken->variety."-" .$chicken->name) }}">create</a> </li> @endforeach </ul> Route should be like; Route::get('/chickens/{variety}-{name}/create', [ 'as' => 'chickens.create', 'uses' => '[email protected]' ]); Note that the delimiter is in the route, separating the parts. Then in controller you will get both variables passed public function create($variety, $name) { Please sign in or create an account to participate in this conversation.
https://laracasts.com/discuss/channels/general-discussion/mysterious-string-phenomena
CC-MAIN-2018-39
refinedweb
1,032
63.8
0 Please help! Im behind in my homework and dont really even understand it anyways. I cluelessly added the addCoin("...");, which i believe is correct. but I dont know what to add to the return statement for public String toString( ) If you are willing to help, plz provide steps as to how yo figured out how to solve. Below is the original problem and requirements: REQUIREMENTS: - Implement a class Purse. A purse contains a collection of coins. - For simplicity, we will only store the coin names in an ArrayList<String>. - Supply a method void addCoin(String coinName) - Add a method toString to the Purse class that prints the coins in the purse in the format Purse[Quarter,Dime,Nickel,Dime] Use the following class in your solution: import java.util.ArrayList; /** A purse holds a collection of coins. */ public class Purse { /** Constructs an empty purse. */ public Purse() { coins = new ArrayList<String>(); } /** Adds a coin to the purse. @param coinName the coin to add */ public void addCoin(String coinName) { . . . } /** Returns a string describing the object. @return a string in the format "Purse[coinName1,coinName2,...]" */ public String toString() { . . . } private ArrayList<String> coins; }
https://www.daniweb.com/programming/software-development/threads/327742/java-purse-coin-collection
CC-MAIN-2016-40
refinedweb
190
69.38
9.27: Drawing a Graphical Health Meter - Page ID - 14646 def drawHealthMeter(currentHealth): for i in range(currentHealth): # draw red health bars pygame.draw.rect(DISPLAYSURF, RED, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10)) for i in range(MAXHEALTH): # draw the white outlines pygame.draw.rect(DISPLAYSURF, WHITE, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10), 1) To draw the health meter, first the for loop on line 2 [317] draws the filled-in red rectangle for the amount of health the player has. Then the for loop on line 4 [319] draws an unfilled white rectangle for all of the possible health the player could have (which is the integer value stored in the MAXHEALTH constant). Note that the pygame.display.update() function is not called in drawHealthMeter().
https://eng.libretexts.org/Bookshelves/Computer_Science/Programming_Languages/Book%3A_Making_Games_with_Python_and_Pygame_(Sweigart)/09%3A_Squirrel_Eat_Squirrel/9.27%3A_Drawing_a_Graphical_Health_Meter
CC-MAIN-2021-31
refinedweb
130
68.6
Qml flickable disable scroll inertia I want to make a flickable-listview to be only scrollable via the mouse wheel or up/down buttons on the scrollbar. I would also like to disable the scroll momentum/inertia that the flickable has so it behaves properly when scrolling in big lists with the scroll wheel and doesn't feel like a touch device. Hi! MyListView.qml import QtQuick 2.7 import QtQuick.Controls 2.0 Rectangle { id: myListView clip: true focus: true property var model: null property int moveSpeed: 300 function moveContent(up) { listView.flick(0, up ? moveSpeed : -moveSpeed ) } ListView { id: listView anchors.fill: parent model: myListView.model delegate: Text { text: number + ": " + name } boundsBehavior: Flickable.StopAtBounds } MouseArea { anchors.fill: parent onWheel: myListView.moveContent( wheel.angleDelta.y>0 ) } Keys.onPressed: { if (event.key === Qt.Key_Up) { myListView.moveContent(true) event.accepted = true } else if (event.key === Qt.Key_Down) { myListView.moveContent(false) event.accepted = true } else { event.accepted = false } } } main.qml import QtQuick 2.7 import QtQuick.Controls 2.0 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") ListModel { id: myModel Component.onCompleted: { for (var i=0; i<50; ++i) append({"number": i, "name":"Pizza"}) } } MyListView { model: myModel color: "orange" anchors.fill: parent } } It doesn't work as expected, at first is too slow, but when making the move speed around 1200 it still has inertia, not as much but still annoying. Is there any trick to always get the pixelDelta? First you should set the property interactive to false (true by default). Then you will have to force the flickable to move (when pressing a button, or when moving the mouse wheel event, for example) by incrementing/decrementing the contentX / contentY properties. Hope it helps.
https://forum.qt.io/topic/80008/qml-flickable-disable-scroll-inertia
CC-MAIN-2018-05
refinedweb
285
60.82
On Sat, Feb 12, 2005 at 08:30:13AM +0100, Petter Reinholdtsen wrote: >[Anibal Monsalve Salazar] >> It's now redirected to The web page on ftp-master is Ganneff's work. It's updated once every hour from the authorative archive. The archive on merkel is updated once every day. I would like to work with Ganneff to make changes to the page on ftp-master. >Great. This is much better than my crude hack. If you plan to >keep this updated all the time, I'll close down my page and point >people to your page. > >>Any input is welcome. > >It would be nice if the changelog for the uploaded package is >available too. > >Another feature I've been wishing for is making more statistics, >for example of averaget waiting time (keeping track of when >packages come and go), and perhaps an history to know when how >often a given package have been in the NEW queue. Some packages >return (shared libraries changing sonames, mplayer, etc), and it >would be nice to let this system tell us instead of trusting >memory. > >I've also considered looking at "out-of-order" processing of >queue entires, to see if there is a pattern for packages processed >faster than the rest of the queue. > >None of this is really important, but it would be nice to have the >information more easily available. Problem is, of course, that as >this isn't important I haven't spent any time to make it happen. >Too much more important stuff to take care of. :) > >Thank you again, for making a much better presentation of the NEW >queue. :) Anibal Monsalve Salazar -- .''`. Debian GNU/Linux : :' : Free Operating System `. `' `- Attachment: signature.asc Description: Digital signature
https://lists.debian.org/debian-devel/2005/02/msg00795.html
CC-MAIN-2017-22
refinedweb
287
73.07
0.47 2014-12-16 - Stop checking warning message contents explictly (Aaron Crane) 0.46 2012-12-23 - Documentation fixes (Brigham Johnson) - Hash ordering fixes for 5.17 (Kent Fredric) 0.45 2011-04-15 - Added new HTML 5 elements to the HTML Tag set. (Theory) 0.44 2010-12-08 - Added support for $TAG_INDENTATION and $EOL (Marc Chantreux) - Add a current_base_path() convenience function (trs) 0.43 2009-11-18 - Test warning fixes (Theory) - Dist fixes suggested by rafl (Sartak)gué [rt.cpan.org #48642] 0.40 2009-07-08 - Fix subname issue with the debugger and specifically Devel::NYTProf - String::BufferStack usage improvements 0.39 2009-03-05 - No code changes; increase Test::Warn dependency to 0.11, as 0.10 was broken 0.38 2009-02-27 - Support, but deprecate, Template::Declare->buffer->data(...) usage objects by hand may need to be adjusted. 0.31_01 2008-12-19 - INCOMPATIBLE: there were inconsistency in arguments passing. show in TD::Tags could pass arguments into template as array reference depending on a way it's called. Now arguments are always passwed the same way they passed into show. This change is only backwards incompatible for those who were using this incorrect behaviour. - stringify argument in TD::Buffer::append as we can deal with an object with overloaded stringification that puts data into buffer when stringified - correctly escape objects with overloaded stringification - use less buffers for operations and a few other small optimizations 0.30 2008-11-26 - Remove the "wrapper" export, its name is too generic and clashes with a lot of existing code. It's a negligible amount of sugar. 0.29 2008-07-01 - Sugar for defining a tag-like wrapper. Thanks Theory! #37624 - Don't load all of CGI.pm to get a list of tags. #37630 - Don't add attrs to the first tag in smart_tag_wrapper. #37622. 0.28 2008-02-14 -. - Added Template::Declare::TagSet::HTML and Template::Declare::TagSet::XUL, respectively, as well as their common base class, Template::Declare::TagSet. Added Template::Declare::TagSet::HTML and Template::Declare::TagSet::XUL, respectively. - Added support for XML namespace: use Template::Declare::Tags 'XUL', 'HTML' => { namespace => 'html' }; and ... 'HTML' => { namespace => 'html', package => 'MyHtml' }; - And we can now say 'use Template::Declare::Tags qw/ HTML XUL /; - Added @Template::Declare::Tags::TAG_SUB_LIST which records all the tag subroutines generated on-the-fly, which is necessary for secondary symbol exporting in Jifty::View::Declare::Helpers. - Implemented C< use Template::Declare::Tags HTML => { from => 'My::HTML::TagSet' } >. - Allow content post-proceessing with a callback. - Added a PITFALLS section to T::D's POD. - Added a global sub append_attr to provide friendly diagnostics and the infamous "Undefined subroutine &Template::Declare::Tags::append_attr called at ..." is now gone.
https://metacpan.org/changes/distribution/Template-Declare
CC-MAIN-2017-09
refinedweb
456
51.85
The best answers to the question “Why do I need 'b' to encode a string with Base64?” in the category Dev. QUESTION: Following this python example, I encode a string as Base64 with: >>> import base64 >>> encoded = base64.b64encode(b'data to be encoded') >>> encoded b'ZGF0YSB0byBiZSBlbmNvZGVk' But, if I leave out the leading b: >>> encoded = base64.b64encode('data to be encoded') I get the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python32\lib\base64.py", line 56, in b64encode raise TypeError("expected bytes, not %s" % s.__class__.__name__) TypeError: expected bytes, not str Why is this? ANSWER: Short Answer You need to push a bytes-like object ( bytes, bytearray, etc) to the base64.b64encode() method. Here are two ways: >>> import base64 >>> data = base64.b64encode(b'data to be encoded') >>> print(data) b'ZGF0YSB0byBiZSBlbmNvZGVk' Or with a variable: >>> import base64 >>>>> data = base64.b64encode(string.encode()) >>> print(data) b'ZGF0YSB0byBiZSBlbmNvZGVk' Why? In Python 3, str objects are not C-style character arrays (so they are not byte arrays), but rather, they are data structures that do not have any inherent encoding. You can encode that string (or interpret it) in a variety of ways. The most common (and default in Python 3) is utf-8, especially since it is backwards compatible with ASCII (although, as are most widely-used encodings). That is what is happening when you take a string and call the .encode() method on it: Python is interpreting the string in utf-8 (the default encoding) and providing you the array of bytes that it corresponds to. Base-64 Encoding in Python 3 Originally the question title asked about Base-64 encoding. Read on for Base-64 stuff. base64 encoding takes 6-bit binary chunks and encodes them using the characters A-Z, a-z, 0-9, ‘+’, “”, and ‘=’ (some encodings use different characters in place of ‘+’ and “”). This is a character encoding that is based off of the mathematical construct of radix-64 or base-64 number system, but they are very different. Base-64 in math is a number system like binary or decimal, and you do this change of radix on the entire number, or (if the radix you’re converting from is a power of 2 less than 64) in chunks from right to left. In base64 encoding, the translation is done from left to right; those first 64 characters are why it is called base64 encoding. The 65th ‘=’ symbol is used for padding, since the encoding pulls 6-bit chunks but the data it is usually meant to encode are 8-bit bytes, so sometimes there are only two or 4 bits in the last chunk. Example: >>> data = b'test' >>> for byte in data: ... print(format(byte, '08b'), end=" ") ... 01110100 01100101 01110011 01110100 >>> If you interpret that binary data as a single integer, then this is how you would convert it to base-10 and base-64 (table for base-64): base-2: 01 110100 011001 010111 001101 110100 (base-64 grouping shown) base-10: 1952805748 base-64: B 0 Z X N 0 base64 encoding, however, will re-group this data thusly: base-2: 011101 000110 010101 110011 011101 00(0000) <- pad w/zeros to make a clean 6-bit chunk base-10: 29 6 21 51 29 0 base-64: d G V z d A So, ‘B0ZXN0’ is the base-64 version of our binary, mathematically speaking. However, base64 encoding has to do the encoding in the opposite direction (so the raw data is converted to ‘dGVzdA’) and also has a rule to tell other applications how much space is left off at the end. This is done by padding the end with ‘=’ symbols. So, the base64 encoding of this data is ‘dGVzdA==’, with two ‘=’ symbols to signify two pairs of bits will need to be removed from the end when this data gets decoded to make it match the original data. Let’s test this to see if I am being dishonest: >>> encoded = base64.b64encode(data) >>> print(encoded) b'dGVzdA==' Why use base64 encoding? Let’s say I have to send some data to someone via email, like this data: >>> data = b'\x04\x6d\x73\x67\x08\x08\x08\x20\x20\x20' >>> print(data.decode()) >>> print(data) b'\x04msg\x08\x08\x08 ' >>> There are two problems I planted: - If I tried to send that email in Unix, the email would send as soon as the \x04character was read, because that is ASCII for END-OF-TRANSMISSION(Ctrl-D), so the remaining data would be left out of the transmission. - Also, while Python is smart enough to escape all of my evil control characters when I print the data directly, when that string is decoded as ASCII, you can see that the ‘msg’ is not there. That is because I used three BACKSPACEcharacters and three SPACEcharacters to erase the ‘msg’. Thus, even if I didn’t have the EOFcharacter there the end user wouldn’t be able to translate from the text on screen to the real, raw data. This is just a demo to show you how hard it can be to simply send raw data. Encoding the data into base64 format gives you the exact same data but in a format that ensures it is safe for sending over electronic media such as email. ANSWER: base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z, a-z, 0-9, +, /* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email. Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax. If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it’s not 8-bit. It’s not really any bits, in fact. 🙂 In your second example: >>> encoded = base64.b64encode('data to be encoded') All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with >>> encoded = 'data to be encoded'.encode('ascii') Or simpler: >>> encoded = b'data to be encoded' Which would be the same thing in this case. * Most base64 flavours may also include a = at the end as padding. In addition, some base64 variants may use characters other than + and /. See the Variants summary table at Wikipedia for an overview. ANSWER: If the string is Unicode the easiest way is: import base64 a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8")) # a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR' b = base64.b64decode(a).decode("utf-8", "ignore") print(b) # b :complex string: ñáéíóúÑ ANSWER: If the data to be encoded contains “exotic” characters, I think you have to encode in “UTF-8” encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))
https://rotadev.com/why-do-i-need-b-to-encode-a-string-with-base64-dev/
CC-MAIN-2022-40
refinedweb
1,154
61.16
Screen is corrupted between rotations Bug Description When X is instructed to rotate the display, there is screen corruption inbetween each rotation. This can easily be reproduced by installing Checkbox and running /usr/share/ It's a little odd that /usr/share/ 1.) dpk -s checkbox 2.) ls /usr/lib/ What if it is simply run with xrotate? Yes (I believe..), i have checkbox. When I run ls /usr/lib/ I have bpickle.py glock.py persist.py REThread.py gdk.py __init__.py __pycache__ xrandr.py I did rotation with the display settings, I have screen corruption just with normal and 180 degrees rotation (so in the portrait screen) other it's fine Please try running /usr/bin/xrotate. At this point, any other test should be considered incomplete Yes /usr/bin/xrotate result also a screen corruption Thank you, moving this bug to Confirmed. Yep, this is presumably a tegra bug. Should be escalated to nvidia. Assigning to Alex , tegra3 related, still Confirmed in Raring, Needs escalation to Nvidia. This bug has been reported on the Ubuntu ISO testing tracker. A list of all reports related to this bug can be found here: http:// When I run /usr/share/ checkbox/ scripts/ rotation_ test I've got this error: Traceback (most recent call last): checkbox/ scripts/ rotation_ test", line 31, in <module> File "/usr/share/ from checkbox.contrib import xrandr ImportError: No module named checkbox.contrib And nothing happens
https://bugs.launchpad.net/ubuntu-nexus7/+bug/1073096
CC-MAIN-2017-51
refinedweb
240
58.48
Using XTemplate when Field Name contains Colon Hello. I have created a DataView that uses a XTemplate. This works great for most of my fields, but some of my fields contain a colon (e.g. namespace:foobar). The XTemplate won't work with that field. I get an error on eval(body) of "fm.foobar" is not a function. Anybody have an idea for this? I tried doing field mapping using an ArrayReader in the Store (mapping namespace:foobar to just foobar), but that didn't seem to take. It's not paying any attention to the Reader when I add the record to the store. I can provide more details and code samples if needed. Thanks. I also have the same problem. Anyone. Please help.
https://www.sencha.com/forum/showthread.php?87703-Using-XTemplate-when-Field-Name-contains-Colon&p=922093
CC-MAIN-2015-27
refinedweb
126
85.99
On Mon, Apr 1, 2013 at 11:16 PM, Daniel Pocock <daniel@pocock.com.au> wrote: > On 01/04/13 22:04, John Paul Adrian Glaubitz wrote: >> On 04/01/2013 09:59 PM, Daniel Pocock wrote: >>> Agreed, but that doesn't complete the picture, as libgl1-mesa-glx >>> doesn't depend on libgl1-mesa-dri: >>> >>> $ apt-cache depends libgl1-mesa-glx >>> ... >>> Recommends: libgl1-mesa-dri >>> >> >> Well, "Recommends" are installed by default, aren't they? However, I'm > > Not during upgrade or dist-upgrade operations. This is specifically an > upgrading issue. From man apt-get: > > " upgrade: > ... under no circumstances are currently installed packages removed, > or packages not already installed retrieved and installed." Correct for apt/squeeze, partly-wrong for apt/wheezy (since 0.8.15.3). A package requiring a new recommends which is in a non-broken policy state previously will be held back just like other packages requiring a new depends in apt/wheezy. In apt/squeeze the policy will break, which you could fix with "apt-get install --fix-policy", but that is going to fix ALL recommends. We are going to be "fine" in this regard as many packages have a new dependency in a new release (upgrade is mostly for between releases). In this case it is at least "multiarch-support". > "dist-upgrade: > ... intelligently handles changing dependencies with new versions of > packages" dist-upgrade on the other hand installs new recommends since the introduction of recommends. Keyword is "new": If you had recommends disabled previously and/or removed a recommends apt will not install this recommendation again. (It compares the recommends list of the old version with the new version and only uninstalled recommends present in the new, but not in the old version are marked for installation). Of course, if the recommends isn't installable you will still get a solution which doesn't include this recommends which will be displayed as usual. You have to install it later by hand then as it now an old recommends … (In stable, uninstallability shouldn't happen though) I guess the confusion comes from the word "dependencies": In APT namespace "dependency" means any relation which is allowed; not just a "Depends". So the sentence should be read as "… handles changing Pre-Depends, Depends, Conflicts, Breaks, Replaces, Provides, Recommends (if enabled, default yes) and Suggests (if enabled, default no) with new versions …" (for the sake of completion: Enhances are not handled) It's just that a user shouldn't really be required to know what those are. (if you digg deaper [usually in non-user facing texts] you will come across "hard", "important", "soft", "negative" and "positive" dependencies to complete the confusion. I will leave it as an exercise for now which subsets are meant with those adjectives) Best regards David Kalnischkies
https://lists.debian.org/debian-devel/2013/04/msg00090.html
CC-MAIN-2016-22
refinedweb
464
50.26
$JAVA_HOMEor %JAVA_HOME%) bindirectory is typically on the Java developer's PATH. The implication of this is that many more useful tools that come with Oracle's JDK distribution are also available on the path. I have blogged about some of these tools including jvisualvm, jconsole, jps, serialver, rmiregistry, xjc, schemagen, jinfo, and jhat and jmap. In this post I cover a tool in this directory that I've not covered before: jrunscript. The jrunscript tool is a "command line script shell" that is described on its JDK 7 tools page as "a command line script shell" that "supports both an interactive (read-eval-print) mode and a batch (-f option) mode of script execution." The page adds further description: This is a scripting language independent shell. By default, JavaScript is the language used, but the -l option can be used to specify a different language. Through Java to scripting language communication, jrunscript supports "exploratory programming" style. As is the case with many tools in the JDK bin directory, this tool comes with this caveat: "NOTE: This tool is experimental and may not be available in future versions of the JDK." That being stated, it has been available in both Java SE 6 and so far in Java SE 7 JDK distributions from Sun/Oracle. The usage for jrunscriptcan be seen by simply typing jrunscript -helpat the command prompt. The next screen snapshot demonstrates this after first showing the current version of Java and Groovy involved. Although these are fairly current versions of both languages, slightly older versions of each (Java SE 6 for example) can be used for most of my examples. The usage of jrunscriptis fairly straightforward as its usage indicates. Using the -qoption instructs jrunscriptto report which scripting engines are available. The default available script engine is Rhino JavaScript as is shown in the next screen snapshot. JavaScript is not the only supported scripting language for jrunscript. In the remainder of this post, I will demonstrate use of Groovy as the scripting language used in conjunction with jrunscript. To run a scripting language other than the out-of-the-box-provided Rhino with jrunscript, a JSR 223-compliant script engine JAR is typically needed as described in JSR-223 script engine for the Java language. Fortunately, in the case of Groovy 1.6 or later, this JSR 223 engine is built into the language. When I place the appropriate Groovy JAR files ( groovy-1.8.0.jarand asm-3.2.jar) on the classpath provided to jrunscriptand pass it the -qoption ("List all scripting engines available and exit") to determine which languages are supported, it now tells me that Groovy is supported in addition to the default Rhino JavaScript. This can be seen in the next screen snapshot. Even with the applicable Groovy JAR files on the classpath, the default scripting language that jrunscriptuses is JavaScript unless a different language is specified with the -loption. The next screen snapshot demonstrates this is the case. I've gotten this far with only needing to specify two Groovy JARs on the classpath when running jrunscript. However, if I do too many operations, other JARs will be needed or else I'll see a NoClassDefFoundError. The next screen snapshot shows invocation of jrunscriptwith three Groovy JARs. More than showing the use of the JARs, the output also demonstrates using jrunscriptinteractively to get calculate a sum, to get the current date/time via the Date class, and to get the current date/time via Calendar.getInstance(). This demonstrates the ability to interactively perform simple Groovy statements and thus do some "exploratory learning." The above output was generated from using jrunscriptwith Groovy interactively. Groovy code can also be written to a file and executed via jrunscript. For example, the file groovyScript.groovycan be created as shown next. groovyScript.groovy def sum = 12 + 13 + 14 def date = new Date() def calendar = Calendar.getInstance() println "Sum: ${sum}" println "Date: ${date}" println "Calendar: ${calendar}" The above file can be executed via jrunscriptas shown in the next screen snapshot. Note that the -loption is specified to instruct jrunscriptthat the code in the file is Groovy. The advantage of running jrunscriptagainst a script file with Groovy code is that variables defined earlier in the script are still available in later statements. The jrunscripttool also supports a -eoption that allows script code to be passed inline to the tool. The next screen snapshot demonstrates doing just this with the -loption again specifying Groovy as the language and the -eoption passing in the script to run. The partial output from running this is included in the screen snapshot. I have demonstrated in this blog post how to use jrunscriptto run Groovy code. In particular, I've shown using Groovy interactively via jrunscript, passing a Groovy script in a single string to jrunscript, and executing jrunscriptagainst a file with Groovy script code. These options all work, but the truth is that they're really more valuable for a non-JVM scripting language like JavaScript than they are for a JVM-based scripting language like Groovy. The difference is that Groovy is already very Java-friendly and has virtually seamless integration with Java. Indeed, there are easier and arguably better ways to run Groovy code from the command line than using jrunscript. I cover these briefly now. If I want to run Groovy code in a file, the obvious choice is to simply use the 'groovy' launcher and run the script. I have demonstrated this in many Groovy posts on this blog. This same groovylauncher also supports a -e option just like jrunscriptdoes. The advantage of the Groovy launcher approach over use of jrunscriptin both cases is a much simpler explicit classpath specification. More information on Groovy from the command line can be found in the Groovy User Guide's Groovy CLI page. The native groovylauncher more than adequately covers jrunscript's ability to allow Groovy code in a file to be executed or Groovy code in a String to be executed in a single command. To match (and exceed) jrunscript's interactive functionality when using Groovy, the obvious choice is Groovy shell. I have covered Groovy Shell in a previous blog post. It is simple to use and is shown in the next screen snapshot. Conclusion For non-JVM scripting languages that provide a JSR 223 compliant scripting engine, jrunscriptcan be a valuable tool. In the case of Groovy, I cannot think of a good reason to pick jrunscriptwith Groovy over simply using the Groovy native launcher ( groovy) and Groovy Shell ( groovysh) directly. This might be the reason that there are not many online resources talking about using Groovy with jrunscript. For more details on use of jrunscriptwith scripting languages other than Groovy, see Use jrunscript to execute JavaScript scripts and Using jrunscript to create a build script.
http://marxsoftware.blogspot.com/2011/06/jrunscript-and-groovy.html
CC-MAIN-2016-40
refinedweb
1,137
61.67
Wiki SCons / NsisSconsTool This is a Tool for SCons that can parse a Nullsoft Scriptable Installation System (NSIS) script (a .nsi file) and determine its dependencies and its actual target name. The following file can be be copied to site-packages/scons/SCons/Tools/ and it will 'just work'. Enhancement note: This uses glob.glob to find the source files if they have filename glob chars, but if (as is usual) the sources are built by some other builder, you might want to use one of the techniques in BuildDirGlob to find them instead, so scons gets all the dependencies correct. Feel free to modify and improve as you wish. - UPDATE: I have patched this tool to work correctly on Windows 64-bit (with Python 64 bit). If this is useful to you, see here:. -- JohnPye - Works for me too! Rather than installing the file in site-packages, I've used it as embedded code in my main trunk/SConstruct and trunk/pygtk/interface/SConscript, which are visible at, so that I don't have to tell users to mess with their default SCons installation. -- JohnPye - I have made changes that allow using makensis in linux, and also basic analysis of !include and !ifdef directives (not included in the script below, which does parse File operations). These changes are provided in a diff. I have also moved to using env.Glob() instead of glob.glob. The final script, with those changes applied to the January 2004 shown below, is here. I did not test the script with Windows makensis.exe so there is a possibility some things were broken there. The only thing I can think of that has possibly been broken, however, is the determination of the SCons install directory in line 146. To use as a tool without overwriting the SCons install directory, I placed it in a subdirectory of the SConstruct directory called "scons_tools" and used: txt env.Tool("nsis", toolpath=["scons_tools"])-- YitzhakSapir The original script for the tool is provided below. #!python # NSIS Support for SCons # Written by Mike Elkins, January 2004 # Provided 'as-is', it works for me! """ This tool provides SCons support for the Nullsoft Scriptable Install System a windows installer builder available at To use it you must copy this file into the scons/SCons/Tools directory or use the tooldir arg in the Tool function and put a line like 'env.Tool("NSIS")' into your file. Then you can do 'env.Installer("foobar")' which will read foobar.nsi and create dependencies on all the files you put into your installer, so that if anything changes your installer will be rebuilt. It also makes the target equal to the filename you specified in foobar.nsi. Wildcards are handled correctly. In addition, if you set NSISDEFINES to a dictionary, those variables will be passed to NSIS. """ import SCons.Builder import SCons.Util import SCons.Scanner # NOTE (4 September 2007): The following import line was part of the original # code on this wiki page before this date. It's not used anywhere below and # therefore unnecessary. The SCons.Sig module is going away after 0.97.0d20070809, # so the line should be removed from your copy of this module. There may be a # do-nothing SCons.Sig module that generates a warning message checked in, so existing # configurations won't break and can help point people to the line that needs removing. #import SCons.Sig import os.path import glob def nsis_parse( sources, keyword, multiple ): """ A function that knows how to read a .nsi file and figure out what files are referenced, or find the 'OutFile' line. sources is a list of nsi files. keyword is the command ('File' or 'OutFile') to look for multiple is true if you want all the args as a list, false if you just want the first one. """ stuff = [] for s in sources: c = s.get_contents() for l in c.split('\n'): semi = l.find(';') if semi != -1: l = l[:semi] hash = l.find('#') if hash != -1: l = l[:hash] # Look for the keyword l = l.strip() spl = l.split(None,1) if len(spl) > 1: if spl[0].lower() == keyword.lower(): arg = spl[1] if arg.startswith('"') and arg.endswith('"'): arg = arg[1:-1] if multiple: stuff += [ arg ] else: return arg return stuff def nsis_path( filename, nsisdefines, rootdir ): """ Do environment replacement, and prepend with the SCons root dir if necessary """ # We can't do variables defined by NSIS itself (like $INSTDIR), # only user supplied ones (like ${FOO}) varPos = filename.find('${') while varPos != -1: endpos = filename.find('}',varPos) assert endpos != -1 if filename[varPos+2:endpos] not in nsisdefines: raise KeyError ("Could not find %s in NSISDEFINES" % filename[varPos+2:endpos]) val = nsisdefines[filename[varPos+2:endpos]] if type(val) == list: if varPos != 0 or endpos+1 != len(filename): raise Exception("Can't use lists on variables that aren't complete filenames") return val filename = filename[:varPos] + val + filename[endpos+1:] varPos = filename.find('${') return filename def nsis_scanner( node, env, path ): """ The scanner that looks through the source .nsi files and finds all lines that are the 'File' command, fixes the directories etc, and returns them. """ nodes = node.rfile() if not node.exists(): return [] nodes = [] source_dir = node.get_dir() for include in nsis_parse([node],'file',1): exp = nsis_path(include,env['NSISDEFINES'],source_dir) if type(exp) != list: exp = [exp] for p in exp: for filename in glob.glob( os.path.abspath( os.path.join(str(source_dir),p))): # Why absolute path? Cause it breaks mysteriously without it :( nodes.append(filename) return nodes def nsis_emitter( source, target, env ): """ The emitter changes the target name to match what the command actually will output, which is the argument to the OutFile command. """ nsp = nsis_parse(source,'outfile',0) if not nsp: return (target,source) x = ( nsis_path(nsp,env['NSISDEFINES'],''), source) return x def quoteIfSpaced(text): if ' ' in text: return '"'+text+'"' else: return text def toString(item,env): if type(item) == list: ret = '' for i in item: if ret: ret += ' ' val = toString(i,env) if ' ' in val: val = "'"+val+"'" ret += val return ret else: # For convienence, handle #s here if str(item).startswith('#'): item = env.File(item).get_abspath() return str(item) def runNSIS(source,target,env,for_signature): ret = env['NSIS']+" " if 'NSISFLAGS' in env: for flag in env['NSISFLAGS']: ret += flag ret += ' ' if 'NSISDEFINES' in env: for d in env['NSISDEFINES']: ret += '/D'+d if env['NSISDEFINES'][d]: ret +='='+quoteIfSpaced(toString(env['NSISDEFINES'][d],env)) ret += ' ' for s in source: ret += quoteIfSpaced(str(s)) return ret def generate(env): """ This function adds NSIS support to your environment. """ env['BUILDERS']['Installer'] = SCons.Builder.Builder(generator=runNSIS, src_suffix='.nsi', emitter=nsis_emitter) env.Append(SCANNERS = SCons.Scanner.Scanner( function = nsis_scanner, skeys = ['.nsi'])) if 'NSISDEFINES' not in env: env['NSISDEFINES'] = {} env['NSIS'] = find_nsis(env) def find_nsis(env): """ Try and figure out if NSIS is installed on this machine, and if so, where. """ if SCons.Util.can_read_reg: # If we can read the registry, get the NSIS command from it try: k = SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'SOFTWARE\\NSIS') val, tok = SCons.Util.RegQueryValueEx(k,None) ret = val + os.path.sep + 'makensis.exe' if os.path.exists(ret): return '"' + ret + '"' else: return None except: pass # Couldn't find the key, just act like we can't read the registry # Hope it's on the path return env.WhereIs('makensis.exe') def exists(env): """ Is NSIS findable on this machine? """ return find_nsis(env) != None: Updated
https://bitbucket.org/scons/scons/wiki/NsisSconsTool?action=info
CC-MAIN-2015-40
refinedweb
1,233
58.48
Cause a window to join a window group. #include <screen/screen.h> int screen_join_window_group(screen_window_t win, const char *name) The handle for the window that is to join the group. This window must have been created with screen_create_window_type() with a type of either SCREEN_CHILD_WINDOW or SCREEN_EMBEDDED_WINDOW. A unique string that identifies the group. This string must have been communicated down from the parent window. Function Type: Delayed Execution This function is used to add a window to a group. Child and embedded windows will remain invisible until they're properly parented. Until the window joins a group, a window of any type behaves like an application window. The window's positioning and visibility are not relative to any other window on the display. In order to join a group parented by an application window, a window must have a type of SCREEN_CHILD_WINDOW or SCREEN_EMBEDDED_WINDOW. Windows with a type of SCREEN_EMBEDDED_WINDOW can join only groups parented by windows of type SCREEN_CHILD_WINDOW. Once a window successfully joins a group, its position on the screen will be relative to the parent. The type of the window determines exactly how the window will be positioned. Child windows are positioned relative to their parent (i.e., their window position is added to the parent's window position. Embedded windows are positioned relative to the source viewport of the parent. Windows in a group inherit the visibility and the global transparency of their parent. 0 if the request for the window joining the specified group was queued, or -1 if an error occurred (errno is set; refer to /usr/include/errno.h for more details).
http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.screen/topic/screen_join_window_group.html
CC-MAIN-2018-26
refinedweb
269
57.67
11 November 2010 10:47 [Source: ICIS news] SINGAPORE (ICIS)--Rabigh Refining and Petrochemical (PetroRabigh) shut its Saudi Arabia linear low density polyethylene (LLDPE) plant last week because of a lack of raw material, sources close to the company said on Thursday. “There is limited LLDPE for sale this week in ?xml:namespace> Another source said: “There might be a technical problem as well, so we are uncertain when it will actually restart.” The 600,000 tonne/year LLDPE plant is located in Company officials were not available for comment. The company experienced operating problems with the plant in September. PetroRabigh is a joint venture between state-owned Saudi Aramco
http://www.icis.com/Articles/2010/11/11/9409285/petrorabigh-shuts-lldpe-plant-on-raw-material-shortage.html
CC-MAIN-2013-48
refinedweb
110
53.92
You can subscribe to this list here. Showing 2 results of 2 Patches item #3066958, was opened at 2010-09-15 16:06 Message generated for change (Comment added) made by wsfulton You can respond by visiting: Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: None Group: None Status: Open Resolution: None Priority: 5 Private: No Submitted By: Mikael Johansson () Assigned to: Nobody/Anonymous (nobody) Summary: Smart pointer const overload support Initial Comment: The attached patch adds a feature for smart pointers which have both a const and non-const operator->(). Calls to const methods are delegated via the const operator->() while calls to non-const methods use the non-const operator->(). Our specific use case is with a object-database system where the smart pointer is a pinning reference on an object. For example when a non-const method is run the object or rather its memory area, it is automatically flagged as dirty. This is also used to implement object versioning where non-const method calls cause a new object version to be created. The patch adds this overload support for normal method calls, member variable getting and setting, static methods and methods added using %extend. The new behavior is only enabled if a smart pointer class has both a const and non-const operator->(), if not the exact same code is generated as before. The patch also includes a test case for the new functionality, it as well as the other tests runs without problem. An example of a smart pointer where calls to A::get() is handled normally, while calls to A::set() marks the object as dirty with the object store. struct A { int get() const; void set(int a); }; struct ptr { A *a; const A *operator->() const { return a; } A *operator->() { dirty(a); return a; } }; ---------------------------------------------------------------------- >Comment By: William Fulton (wsfulton) Date: 2010-09-25 17:43 Thanks, this looks good. A couple of questions before trying it out: - Does it work with const member variables, eg: const X a; const X *b; X *const c; - Does it work with Java or C#, which uses different code in cwrap.c which python/scripting languages don't call. ---------------------------------------------------------------------- You can respond by visiting: Patches item #3075150, was opened at 2010-09-24 21:59 Message generated for change (Comment added) made by wsfulton You can respond by visiting: Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: general Group: None >Status: Closed >Resolution: Fixed Priority: 5 Private: No Submitted By: ulyssessouza () >Assigned to: William Fulton (wsfulton) Summary: Declaring static variables inside a namespace Initial Comment: According to C++ Standard 7.3.1.1 paragraph 2(OK the paper I have is not the official :D but...), the static declaration inside a namespace is deprecated. - Ok! Deprecated doesn't mean it's a problem. - But the problem is that I had a problem with gcc-4.1.2-glibc-2.3.6. The I can assign values to the variables and then in other method(calling a director method) the variables are empty(var == NULL). It happens with the director responsible variables inside the namespace Swig: jclass jclass_%s; jmethodID director_methids[%d]; Ahhh... And sorry... I don't have examples nether runtime test I could provide. ---------------------------------------------------------------------- >Comment By: William Fulton (wsfulton) Date: 2010-09-25 17:09 I don't understand what the problem was, but as it is deprecated in the standard, I've applied the patch. If you know of any compiler flags to detect this usage, please say so, as we can use them to check usage of this elsewhere in SWIG. ---------------------------------------------------------------------- You can respond by visiting:
http://sourceforge.net/p/swig/mailman/swig-devel/?viewmonth=201009&viewday=25
CC-MAIN-2014-42
refinedweb
642
56.69
With seemingly countless commands available from the UNIX command line—a quick, cursory accounting yields more than 1,500—and each of those with a raft of features, it's impossible to remember every option, nuance, and permutation. Worse, because the universe of UNIX commands evolved over a 40-year period, there are few punctilios. For example, -l means "long format" in ls, but other file-related utilities do not assign the same meaning to the option, if that option is available at all. Further, and ironically, some command-line programs support --help, which prints a terse usage hint, but not all do. As powerful as the command line is, the learning curve can be proportionally maddening. At least at first. Over time, like learning any skill, oft-used command permutations become instinctual and part of muscle memory. Moreover, depending on the shell you use, you can commit a frequently used command-line combination to an alias or a shell script, reducing the burden on your memory. Some shells also maintain lengthy histories that persist previously used commands session over session. Alas, memory fades and new challenges arise. To truly master the command line, you can't fight the man. The man system, that is, UNIX's built-in, online reference system. In fact, the UNIX community has a longstanding mantra reserved for the most confounding problems: "RTFM!" or "Read the frickin' man page!" The man system The UNIX man system is composed of two parts: a collection of online documents and an accompanying document reader. Each document is called a man page; a man page can be very brief or quite lengthy, depending on the topic. The document reader is simply another command-line utility, aptly named man. To read the documentation for a piece of software installed on your system, simply type man component, where component is the name of the software. For example, to read about the ls utility, type: $ man ls You can even read about man itself: $ man man Assuming that component is installed and has a man page, you should see a display like Figure 1, which shows the page for ls. If the man page you name doesn't exist, man reports No manual entry for component. (There are other techniques to find a suitable man page besides naming it. More on that in a moment.) Figure 1. The man document reader running within a terminal window Typically, every significant piece of software found on a UNIX machine—including each command-line utility, each system call, each callable function of a programming library, and each file format—includes a complementary man page. Indeed, it's considered proper etiquette to write and provide man pages when you build new software. Historically, the repository for man pages has been anchored at /usr/man. More recently, the central store has moved to /usr/share/man, although the exact location can differ from one UNIX vendor to the next. Additionally, it's not uncommon for a software package to store its man pages in a subdirectory of its root. For instance, some releases of the MySQL database engine store man pages in /usr/local/mysql/man. Any of these strategies is permitted, albeit some extra configuration is required if man pages are allocated among many repositories. Regardless of its location, each repository is subdivided into one or more sections. Each section is realized as an independent subdirectory, and each is named by convention. There's man1, man2, and so on, up through man8, and each one represents a class of commands. Table 1 lists the section names and their contents. Table 1. Man repository sections and their contents In some instances, components in different sections may share the same name. This happens regularly, especially when a software package has multiple parts that work together. For example, the crontab command, which submits jobs to be scheduled, is found in section 1. Meanwhile, the crontab file format, which describes jobs to run, can be found in section 5. To differentiate between a component in one section or another, provide the section number as the first argument: $ man 1 crontab $ man 5 crontab The former command details the command; the latter command shows the file format. If software exists in multiple sections and you do not specify the section number, man shows the matching occurrence from the lowest numbered section. The contents of a man page Although options may vary wildly from command to command, the contents of a man page are highly regular. Indeed, man pages are invaluable because of the conventions. After reading just a handful, you can quickly jump to the right portion of the document to find the information you seek. A minimal man page includes five segments: a name, a synopsis, a description, some examples, and references to other pertinent material. You can see the first three segments shown in Figure 1. - The name field lists the name of the command or function or file format and a precise, one-line description of what the software does. - The synopsis provides a terse shorthand to describe how to use the software. If the topic of the man page is a command, this field shows the mandatory and optional switches, the format of the arguments, and the argument order. If the topic at hand is a system call or a library function, this field shows the formal arguments of the function and what, if any, header files are required to use the function. For example, here is the synopsis for the ducommand on BSD UNIX. du [-H | -L | -P] [-a | -s | -d depth] [-c] [-h | -k | -m | -g] [-x] [-I mask] [file ...] The notation used in a command synopsis is one of the helpful conventions found in the man system (and extends to the usage hints provided by late -model utilities). Here, the notation reads, "Type du; optionally, follow with one of -H, -L, or -P; again, optionally, follow by one of -a, -s, or -d, but if you use the latter, specify a depth; provide -cor not; optionally, follow with one of -h, -k, -m, or -g; and specify -xor not; specify -Iand a mask or omit; and finally, provide the name of one or more files to operate on. The ellipsis ( ...) indicates more than one. Options grouped together, such as the first batch of -H, -L, and -P, work like radio buttons in a graphical user interface (GUI): You choose one of several formats mutually exclusively. The independent options, such as -cand -x, work like check boxes: on or off. Reading this notation and translating it into action becomes second nature very quickly. And here is the synopsis for the open()system call on BSD UNIX: #include <fcntl.h> int open(const char *path, int oflag, ...); This synopsis indicates that the fcntl.hheader file is required, open()returns an integer, and you must specify the path to the file to open and a batch of flags that determine the mode (read-only, read/write, open and truncate, and so on). - The description segment is a protracted discussion about features, usage, and all the options available on the command -line. If you want to know what du -Hdoes, you would read the text in the description. - The examples section shows common uses of the utility and often special cases along with an explanation. - The last section, titled See Also, points to further reading, such as other, related commands, important system files, industry-standard specifications, and more. In addition to the aforementioned sections, you may find a host of other ad hoc sections within a man page. One important variant is titled "Environment." It lists environment variables you can set to affect the operation of the utility. For example, the man page for man names some 10 environment variables you can alter to customize man. One is MANPATH, which lists directories to search for man pages. Stupid man tricks So, how do you use man effectively? Here are some helpful tips: - Customize with MANPATH. If you recall, the shell variable PATH lists directories to search for executables. For example, if you set PATH to /usr/bin:/bin:/usr/local/bin, the shell would search those three directories in the order listed to find command-line programs. Similarly, you can set MANPATH to a colon-separated list of directories to find man pages. For instance, if you set MANPATH to /usr/share/man:/usr/local/mysql/man (each is the root of a repository), manwould search both directories for a matching man page. - Search the man page repositories for content. The manutility can search man pages for strings. To search, type man -k patternto find all pages that contain pattern. One caveat: This operation can be very slow. One alternative is to use apropos. It's an adjunct to manbut searches only the one-line name fields of each page. It does not search as far and wide as man -k, but it's very fast. - Use your favorite pager. The manutility recognizes a number of environment variables to customize output. Set the environment variable PAGER to use your favorite paging application, such as less. Some systems provide Hypertext Markup Language (HTML) versions of man pages; on those systems, set your favorite browser with the BROWSER environment variable. - Hunt for content. Use the search capabilities of your PAGER to quickly find the content you want. For example, if you're browsing the man page for man and your pager is lessand you want to learn more about MANPATH, type /MANPATH(the forward slash is the command to search), and then press Return. The lesspager highlights all occurrences of the string; you can use nand ?to find the next occurrence and previous occurrence of the string, respectively. - Tune out the noise. Use the MANSECT environment variable to list the sections you want to search for man pages (that is, 1, 2, 3, up to 8). Any section that does not appear in MANSECT is ignored. For example, if you want to ignore section 1 and concentrate on section 5, set MANSECT to 5. - Read a man page file. If you're writing a new man page or have downloaded some files from the Internet, you can read a single man page using man's Immediate mode. To read a specific file, run man filename, where filename is a fully qualified path to the file. For example, if you are writing stocks.1—a new command in section 1 to show stock quotes—you can preview it with the command man ./stocks.1. (If you omit the leading path, manlooks for a man page called stocks.1 in your MANPATH.) - Help your fellow with man. If you install a batch of man pages on your system, you can change the global MANPATH to include the new directory and provide those man pages to every user who shares your system. The text file /etc/manpaths lists repositories one per line. You can also establish entire subsystems by creating new lists in the directory /etc/manpaths.d. Type man man.conffor more information. By the way, if you want to list the system-wide man page repositories defined for your system, simply type manpath: $ manpath /usr/local/man:/usr/local/share/man:/usr/share/man:/usr/man However, some versions of man go further and search directories beyond those shown by manpath. On BSD UNIX, for instance, man also searches each directory listed in PATH as well as the parent directory of each path listed in PATH. Thus, if you have /usr/mysql/bin in your PATH, man would search that specific path and look for /usr/mysql/man. Man, what a relief! UNIX systems vary from vendor to vendor, so your man page system may differ (for better or worse) from the features described here. However, now that you know the ins and outs, you can tackle the variations on your own. Just be sure to mind the mantra: Read the frickin' man page. Resources Learn - History of man: Read the history of the UNIX man page system. - FreeBSD man pages: Search for topics in this vast repository of man pages from many versions of UNIX and Linux. - Speaking UNIX: Check out other parts in this series. - Learn more about UNIX shells. -.
http://www.ibm.com/developerworks/aix/library/au-spunix_manpages/index.html
CC-MAIN-2016-26
refinedweb
2,051
63.09
There are many reasons you might end up needing to patch your Dojo source tree. Maintaining patches can be a pain, and sometimes outside of your control entirely. It could be a bug you’ve found, or something you really wish a Dojo component did/didn’t do, or you are having to work against an older release of Dojo, or there’s a patch in trac that fixes an issue you have, but it has not yet been committed. In this post, we’ll present a neat way to make the change, keep what you did explicit so other developers aren’t confused, and maintain it outside the Dojo source. Here’s an example: Dojo 1.3 introduces dojo.create into Dojo Base – a new, handy API for creating DOM elements. But, if you’re already developing with a previous version of Dojo, it won’t be available to you until you upgrade to 1.3. You can create a shim to start using it immediately like this: dojo.provide("yourns.patches.dojo.base"); if(dojo.version.major == 1 && dojo.version.minor < 3) { // a copy of dojo.create, from svn trunk's dojo/_base/html.js // lots of useful doc comments snipped for brevity dojo.create = function(tag, attrs, refNode, pos) { var doc = d.doc; if(refNode){ refNode = d.byId(refNode); doc = refNode.ownerDocument; } if(d.isString(tag)){ tag = doc.createElement(tag); } if(attrs){ d.attr(tag, attrs); } if(refNode){ d.place(tag, refNode, pos); } return tag; // DomNode }; } Now, to use it: // if you've not already registered your namespace, do so... dojo.registerModulePath("yourns", "../yourDirectory"); dojo.require("yourns.patches.dojo.base"); dojo.addOnLoad(function() { dojo.create("div", {innerHTML:"this worked"}, dojo.body()); }); The naming scheme here is: - " yourns" - placeholder for whatever your namespace is. - " patches" - a package/directory to contain all such patches. You might use the same directory to also keep static resources like CSS files that tweak/extend a Dojo CSS rule, or image. For this example, you'll have created a file at ../yourDirectory/patches/dojo/base.js - " dojo.base" - the name of the dojo module/method this patch impacts. To patch dijit.layout.BorderContaineryou might call this " yourns.patches.dijit.layout.BorderContainer", or, bundle up all your Dijit patches into " yourns.patches.dijit". Though as a rule it is best to leave optimization to the build process and focus on clarity of intent and scope in your source. The goal here is to avoid "strange magic from a distance" by putting the change directly into the context in which it applies. You can treat this like any other module in your build profile, just make sure you place it ahead of any code that relies on it being there. When you do upgrade, you can simply remove the patch, and the version check gives you a grace period to do so. The Dojo Toolkit is just that - tools to help you produce better work, faster. The real world of web application development is a much more complicated place than most tutorials and code samples would like you to believe, and most projects throw you a curve ball at some point. Your toolkit should work with you at times like that, and this is just one technique that allows you to adapt gracefully and move on to the next problem to solve. Pingback: Managing Widget Templates in Dojo 1.4 | SitePen Blog()
https://www.sitepen.com/blog/2009/02/04/patching-dojo/
CC-MAIN-2015-32
refinedweb
567
58.38
1590671473 The love of Automation testers, TestNG, is a Java testing framework that can be used to drive Selenium Automation script. When it comes to automation, no one can compete with Selenium online training. If you are planning to dive into the field of automation testing, TestNG can be your topmost choice. For a beginner, it becomes hard to understand the point from where he needs to start. So, in this blog, we have come up with a step by step method to assist you in getting started with your first automation test script. For this, you need to set up an Test Automation environment for selenium with python online training Eclipse first and then go ahead with the script. Let’s do it. Open your browser in the next tab and get started for your first automation test script in TestNG. All you need is just 20 minutes. Setting Up The Environment Step 1: First of all, download java8 or jdk1.8 and install it in your system. You can use the link to download java8. After installing java8, set up the path. To do so, Go to Start→ Computer→ Right click → properties→ Advanced system settings → Environment variable→ New→ After clicking on that you need to enter variable name and variable path. You’ll see the following screen in the ‘Environment variable’ window. Once you click on New, you’ll see the following window. Enter ‘Path’ as the variable name. And Enter the path where your jdk has been installed in the variable path Let’s validate if this is properly installed or not. To do so, open cmd window and type ‘javac’. You’ll see a window with all the details of jdk. If you get it, then it is properly installed, if not, then try again. Step 2: Download Eclipse and Run Select Eclipse IDE for Java EE Developers and install it. Once you install it, an eclipse IDE window will open for writing the script and it will look like this. Step 3: Download TestNG from Eclipse Marketplace For this, Go to Help→ Eclipse Marketplace Click ‘install’ on TestNG for Eclipse. And finish the process. Step 4: Download Selenium 3.11.0 You can use this link to download: Step 5: Download Selenium online training India dependency files Download selenium dependency files for jdk 3.11.0 using the link provided here. Step 6: Create the project Create a Java project To create it, go to file→ New→ Other Select create a Java Project Enter your project name, I am entering ‘FirstAutomationProject’. Note: Do not enter spaces in the name of the project Click Open Perspective You’ll see that a new Java Project is created at the left side. Now, Click on ‘FirstAutomationProject’. You’ll see src file. Right-click on it. Select new→ Other→ Create a new Java Package. Click Finish. Step 7: Create a new TestNG class. Create a new TestNG class under the package’s new pack. Right-click new pack–> New –> Other Check @BeforeTest and @AfterTest. Once you click on Finish, you’re all set to write your automation script. A template TestNG code will open up like this. Step 8: Import Selenium online training Hyderabad Jar Files in dependency files Right-click on FirstAutomationTest→ Import. Click on’ Add external Jar’ and add the Jar dependency files that you’ve downloaded above. Select the .jar file that you’ve downloaded above. Similarly, import the dependency files that you’ve downloaded from the link provided above. Import lib files from the zip extracted dependency files. Select all the files in the lib folder. Once you import all the files, you’re all set to write the code. Writing The Code On the eclipse window that you’re seeing now, write the following code. We are writing code in order to verify the title of the webpage. CODE(self-explanatory): package newpack; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; //comment the above line and uncomment below line to use Chrome //import org.openqa.selenium.chrome.ChromeDriver; public class NewTest { WebDriver driver; @Test public void FirstTest() { // declaration and instantiation of objects/variables System.setProperty(“webdriver.chrome.driver”,“C:\Users\Admin\Downloads\chromedriver_win32\chromedriver.exe”); driver = new ChromeDriver(); //comment the above 2 lines and uncomment below 2 lines to use Chrome //System.setProperty(“webdriver.chrome.driver”,“G:\chromedriver.exe”); //WebDriver driver = new ChromeDriver(); String baseUrl = ""; String expectedTitle = "LambdaTest - Perform all your tests on cloud"; String actualTitle = ""; // launch Chrome(); } } After writing the code, save it and right-click on ‘New Test.java’ → Run as→ TestNG Test. Once you click on it, you’ll see a chrome browser window opening the website that you’ve entered in your code to test. And it will automatically close as soon as the test is completed and in the output section below, you’ll see ‘Test Passed’ as the status of your test on the console below. With this, you have run your first automation test in TestNG. To verify the title of a given web-page matches the one already specified. Nothing matches the feeling you get after doing something new. So, feeling good after executing your first automation script? Let us know your experience in the comment section below for more selenium testing course online. #selenium #seleniumtraining #selenum #certification #webdriver #automation 1620805745 Want to try automated inventory management system for small businesses? Originscale automation software automate your data flow across orders, inventory, and purchasing. TRY FOR FREE #automation #automation software #automated inventory management #automated inventory management system #automation management system #inventory automation17602685 Are you wanting to be an Entrepreneur? A Business using cryptocurrency? Then this article is for you. As a beginner, always one prefers fair play. But to the least, initiating business in the streams of cryptocurrency carries a varying degree of risks. We all know that, Every business packs the profit only if we are ready to take risks. But flabbergast is, you can avoid unnecessary risk, If you choose our Twisted HYIP Investment script. You don’t need to play poker with your hard-earned Money. Using minimal investment, You can start a beneficial business. Craze for cryptocurrency is now seeming to be unlimited, Using the Twisted HYIP platform you will get funds for running the lending business- this is the one line of the process. First, let me make plain, How our traditional HYIP works? You can create a number of investment plans with attractive and promising Rate of interest. Investors will invest in those plans and get their interest periodically. How you will provide them interest? You have to collect the investments and use them for your own project, Trading, Stock marketing and so on. What if you don’t find a right platform to grow your investor’s funds. You will lack in processing their interest, and it will be filthy, right? How it works? So this Twisted HYIP platform clear this shady cloud and brings you the best place to grow your investors’ funds. With our platform you can run Investment as well as lending platform together. You will run a traditional HYIP script for your investors stating the fixed Rate of interest with validity for processing their principle back. Instead of using the crowded funds in different platform, You can use it for lending to borrowers in your platform at an interest rate higher than promised to your investors. Now you can pay back the investors as well as you will get a constant flow of income for you. Instead of generating promised interest rate daily or monthly, You can also make it as a doubler with long term duration. So you can use the investors fund as well as lenders repay again and again. Every investor can monitor their investment growth in their dashboard. They will get back their invested amount plus additional ROI only when their investment gets matures. But they can see, how their wallet is loaded with profits without any risk. Possibility of being a Profitable business Crucial bits of Twisted HYIP Cryptocurrency market is blooming one, as per the voices of many financial expertise, prediction for end of digital currency is a blue moon. This twisted HYIP will create its own market as a perception for profit is getting increased every day among the people. Now are you ready to launch your own lending platform? then Connect with KIR HYIP to know more interesting features about the platform. There is always space to add your ideas. Under a short span of time, launch your own turnkey based lending platform. The World is running behind Profit, what are you waiting for? Join the club now and get the free HYIP software demo! #hyip script #hyip investment script #bitcoin hyip script #buy hyip script #best hyip script #hyip investment script 1596848400, repetitive, and data-intensive tests automatically, helps teams improve software quality and make the most of their always-limited testing resources. Use these top tips to ensure that your software testing is successful and you get the maximum return on investment (ROI): It is impossible to automate all testing, so it is important to determine what test cases should be automated first. The benefit of automated testing is linked to how many times a given test can be repeated. Tests that are only performed a few times are better left for manual testing. Good test cases for automation are ones that are run frequently and require large amounts of data to perform the same action. You can get the most benefit out of your automated testing efforts by automating: Success in test automation requires careful planning and design work. part of the intended application. To test a certain piece of the application’s UI, you would use functional or GUI testing. After determining your goal and which types of tests to automate, you should decide what actions your automated tests will perform. Don’t just create test steps that test various aspects of the application’s behavior at one time. Large, complex automated tests are difficult to edit and debug. It is best to divide your tests into several logical, smaller tests. It makes your test environment more coherent and manageable and allows you to share test code, test data, and processes. You will get more opportunities to update your automated tests just by adding small tests that address new functionality. Test the functionality of your application as you add it, rather than waiting until the whole feature is implemented. When creating tests, try to keep them small and focused on one objective. For example, separate tests for read-only versus reading/write tests. This allows you to use these individual tests repeatedly without including them in every automated test. Once you create several simple automated tests, you can group your tests into one, larger automated test. You can organize automated tests by the application’s functional area, major/minor division in the application, common functions, or a base set of test data. If an automated test refers to other tests, you may need to create a test tree, where you can run tests in a specific order. To get the most out of your automated testing, testing should be started as early as possible and ran as often as needed. The earlier testers get involved in the life cycle of the project the better, and the more you test, the more bugs you find. Automated unit testing can be implemented on day one and then you can gradually build your automated test suite. Bugs detected early are a lot cheaper to fix than those discovered later in production or deployment. With the shift left movement, developers and advanced testers are now empowered to build and run tests. Tools allow users to run functional UI tests for web and desktop applications from within their favorite IDEs. With support for Visual Studio and Java IDEs such as IntelliJ and Eclipse, developers never have to leave the comfort of their ecosystem to validate application quality meaning teams can quickly and easily shift left to deliver software faster. Selecting an automated testing tool is essential for test automation. There are a lot of automated testing tools on the market, and it is important to choose the automated testing tool that best suits your overall requirements. Consider these key points when selecting an automated testing tool: For detailed information about selecting automated testing tools for automated testing, see Selecting Automated Testing Tools. Usually, the creation of different tests is based on QA engineers’ skill levels. It is important to identify the level of experience and skills for each of your team members and divide your automated testing efforts accordingly. For instance, writing automated test scripts requires expert knowledge of scripting languages. Thus, in order to perform these tasks, you should have QA engineers that know the script language provided by the automated testing tool. Some team members may not be versed in writing automated test scripts. These QA engineers may be better at writing test cases. It is better when an automated testing tool has a way to create automated tests that do not require an in-depth knowledge of scripting languages. You should also collaborate on your automated testing project with other QA engineers in your department. Testing performed by a team is more effective for finding defects and the right automated testing tool allows you to share your projects with several testers. Good test data is extremely useful for data-driven testing. The data that should be entered into input fields during an automated test is usually stored in an external file. This data might be read from a database or any other data source like text or XML files, Excel sheets, and database tables. A good automated testing tool actually understands the contents of the data files and iterates over the contents in the automated test. Using external data makes your automated tests reusable and easier to maintain. To add different testing scenarios, the data files can be easily extended with new data without needing to edit the actual automated test. Typically, you create test data manually and then save it to the desired data storage. However, you will find tools that provide. Creating test data for your automated tests is boring, but you should invest time and effort into creating data that is well structured. With good test data available, writing automated tests becomes a lot easier. The earlier you create good-quality data, the easier it is to extend existing automated tests along with the application’s development. Automated tests created with scripts or keyword tests are dependent on the application under test. The user interface of the application may change between builds, especially in the early stages. These changes may affect the test results, or your automated tests may no longer work with future versions of the application. The problem is automated testing tools use a series of properties to identify and locate an object. Sometimes a testing tool relies on location coordinates to find the object. For instance, if the control caption or its location has changed, the automated test will no longer be able to find the object when it runs and will fail. To run the automated test successfully, you may need to replace old names with new ones in the entire project, before running the test against the new version of the application. However, if you provide unique names for your controls, it makes your automated tests resistant to these UI changes and ensures that your automated tests work without having to make changes to the text itself. This also eliminates the automated testing tool from relying on location coordinates to find the control, which is less stable and breaks easily. #automation-testing-tool #automation-testing #automation-tips #automation-software #automation 1600051380 As you already know, TestNG or Test Next Generation is one of the most frequently used automation testing frameworks in Java. Inspired by JUnit and NUnit, Cedric Beust created TestNG with the idea of covering almost all types of testing models, be it functional or end-to-end. The annotations, functionalities, usability, features, and ease-of-use make TestNG a very popular choice of framework. Listed below are some of the major benefits of using TestNG-. #tutorial #performance #java tutorial #selenium automated testing #testng tutorial #testng automation framework #testng framework in selenium
https://morioh.com/p/cc120ef759d2
CC-MAIN-2022-40
refinedweb
2,733
55.34
How can I make a stream go to a printer on an LPT port? Can it be done? If not, is there any other way of outputting to an LPT? How can I make a stream go to a printer on an LPT port? Can it be done? If not, is there any other way of outputting to an LPT? Code:#include <iostream> #include <fstream> #include <stdlib> using namespace std ; int main() { char printer[10] = "LPT1:"; char character; ofstream prnt (printer); if (prnt.fail()) {); } Last edited by Betazep; 02-04-2002 at 03:07 PM. Blue You can get a handle to the port with the CreateFile() API function, look it up in the help with particular reference to the sections dealing with "communication resources". Once you have a handle, you can use any of the normal handle based I/O functions in the API. Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream. I tried to use _bios_printer(); function before, but the only thing I could do is turn my printer on, using _bios_printer(_Init_Printer,0,0);
https://cboard.cprogramming.com/cplusplus-programming/10224-stream-lpt.html?s=
CC-MAIN-2018-05
refinedweb
183
82.24
C++11 gives us two useful indispensable smart pointers, std::unique_ptr and std::shared_ptr. So much has been written about these that there’s no point me re-hashing anything other than to re-iterate that if you are using “naked” owning pointers in your code these days, you are simply doing it wrong. I wanted to mention briefly the use of custom deleters with smart pointers. If you haven’t looked at this aspect of smart pointers before, it basically gives us a way to specify what should happen when the smart pointer goes out of scope. By default, when your smart pointer goes out of scope, delete (or delete[], as appropriate) is called on the resource, ensuring that it is cleaned up. Having the ability to specify how the resource is deallocated means we can use these smart pointers for other tasks, e.g. emulating C#’s “using” keyword. Another example might be for using a smart pointer for storing a FILE* pointer from fopen() and calling fclose() from the custom deleter. A further example: I’ve recently been doing some work with the SDL library. There’s a library function IMG_Load() which takes an image filename as a parameter. It loads the image, and returns a pointer to an SDL_Surface (which represents a bitmap). To free the memory pointed to by the pointer, one needs to call SDL_FreeSurface() with the SDL_Surface pointer as its parameter. One can neither directly delete nor free an SDL_Surface pointer because it’s a pointer to a struct, which presumably contains a pointer to some allocated memory within it. So how to use RAII with this construct? Enter custom deleters – we can specifically tell our smart pointer to call SDL_FreeSurface when our smart pointer goes out of scope. I don’t specifically want to get into SDL specifics any more than I have, so here’s a completely self-contained program to replicate what I’ve been talking about. Note the class “OldThing” which pretends to be an old, non-smart resource-allocating API call. This code also shows the difference between using custom deleters with unique_ptr and shared_ptr which was the original intention of this post. I’ll explain more about the difference after the listing. #include <iostream> #include <memory> class OldThing { public: ~OldThing() { if (allocated_) { std::cout << "MEMORY LEAK!" << std::endl; } } void Deallocate() { std::cout << "Deallocate called." << std::endl; allocated_ = false; } private: bool allocated_{ true }; }; int main() { { OldThing oldThing; // oldThing going out of scope causes a "memory leak" } { // so let's use a smart pointer with a custom "deleter": std::shared_ptr<OldThing> p(new OldThing, [] (OldThing* ot) { ot->Deallocate(); delete ot; } ); } { // So that works OK. But what if we want // to use unique_ptr instead? // 1. Don't try this unless you like // seeing loads of template errors: /* std::unique_ptr<OldThing> p(new OldThing, [] (OldThing* ot) { ot->Deallocate(); delete ot; } ); */ // 2. So we need to include the // deleter's type in the template parameters: std::unique_ptr<OldThing, void(*)(OldThing*)> p(new OldThing, [] (OldThing* ot) { ot->Deallocate(); delete ot; } ); } return 0; } So to compile this with g++, use g++ -std=c++11 -o foo foo.cpp (assuming you’ve called the source foo.cpp). If you run ./foo, you should see the following output, each line corresponding to one of the three scope blocks in main(): MEMORY LEAK! Deallocate called. Deallocate called. Essentially we’re seeing a fake “memory leak” when the non-smart OldThing object goes out of scope, then two calls to Deallocate() from the two smart pointers. No real memory allocation going on, just calls to the “deallocation” method. Note the difference between specifying a deleter for a shared_ptr and a unique_ptr. This is the reason for this post… initially I (without really thinking it through) had some shared_ptrs with custom deleters and figured they should really be unique_ptrs, so I basically had code like the commented out section marked “1”. This generates a spew of template errors and it can be difficult to figure out what’s going wrong (try it and see). But to make sense of why we need to specify the deleter differently for a unique_ptr, let’s think about how the two smart pointers are implemented. A shared_ptr actually sets up a structure in memory which allows for reference counting, weak pointers, etc. It’s only when reference counts drop to zero can the resource be deallocated. Its constructor takes a function object as its second parameter to allow us to specify a deleter. If we don’t need to share this smart pointer, using a shared_ptr is an overhead we don’t need. A unique_ptr is a simpler templated class. If you don’t specify the deleter’s function signature as the second template parameter, the default_deleter is used. So as you can see in the section marked “2” we provide the correct template parameter, a function pointer to a void function that takes an OldThing pointer, which makes it work as expected. Edit: I reviewed this post recently to remind myself about one aspect and realise the way I declare the unique_ptr with a deleter can be simplified to avoid function pointer declarations (which were never very self-explanatory). It just consists of creating the lambda first, then simply using decltype to add the lambda as the template parameter: auto dt = []( Foo *f ) { delete f; std::cout << "Deleter called\n"; }; std::unique_ptr<Foo, decltype(dt)> p( new Foo, dt ); 4 Replies to “C++ Custom Deleters: unique_ptr vs shared_ptr” Sorry, this isn’t related to your post, but I couldn’t make the contact page work. Until recently, I used your crossword helper pages to track down phrases. It seems to have disappeared and I was wondering if you had any plans to bring it back. It’s really useful. Thanks, Alastair Hi Alastair, sorry for the delay in response…! I didn’t think anyone really used that page, but to be honest I used to find it really useful (which is why I wrote it!) so I may well resurrect it. Trouble is I’m so busy at the moment!! Watch this space. Will do! Thanks. Thanks for the explanation. There are not a lot of good documentation on this very specific topic, but your post let me understand how to resolve my problem.
http://www.martyndavis.com/?p=474
CC-MAIN-2017-22
refinedweb
1,052
61.06
I have the following file as the input APPLE 0 118 1 110 1 125 1 135 2 110 3 107 3 115 3 126 ORANGE 0 112 1 119 2 109 2 119 3 112 4 109 4 128 MANGO 0 136 1 143 2 143 3 143 4 136 BANANA 0 5 1 12 1 15 2 13 3 6 3 9 I need to read the above file and have the following information in the output file In APPLE 0 occurs 1 time, 1 occurs 3 times, 2 occurs 1 time, 3 occurs 3 times In ORANGE 0 occurs 1 time, 1 occurs 1 times, 2 occurs 2 time, 3 occurs 1 times, 4 occurs 2 times In MANGO 0 occurs 1 time, 1 occurs 1 times, 2 occurs 1 time, 3 occurs 1 times, 4 occurs 1 times In BANANA 0 occurs 1 time, 1 occurs 2 times, 2 occurs 1 time, 3 occurs 3 times I started off with reading the input file, putting all the rows into an array. Now I am stuck at reading the row string from the array. Once I get the string, I want to parse the string and get the tokens. This is my idea. Do you have any suggestions to do this. Following is the code I did to start with. #include <stdio.h> #include <stdlib.h> #define FNAME "c:\\CProject\\input.txt" #define OFNAME "c:\\CProject\\output.txt" static FILE *fptr; static FILE *fp ; void pause() { printf("\nProgram ended, Press ENTER: "); fflush(stdin); getchar(); } void close_the_file() { close(fptr); } main() { char buffer[300]; int count = 0; atexit(pause); fptr = fopen(FNAME, "r"); //open the text file for reading if (fptr == NULL) { perror("Could not open " FNAME); exit(1); } atexit(close_the_file); if((fp = fopen(OFNAME, "w"))==NULL) //Read all lines from the file { printf("Cannot open file.\n"); exit(1); } char lines[10000]; int j,k; j=0; while (fgets(buffer, sizeof buffer, fptr) != NULL) { fflush(stdin); // ++count; while(!feof(fptr)) { // loop through and store the lines into the array fscanf(fptr, "%c", &lines[j]); j++; // fprintf(fp, "%c", lines[j]); } // ***** to do - read rows and then parse the row string ***** // printf("The lines are:\n",&lines[j]); printf("Number of lines read: %d\n\n", j); for(k=0 ; k<j ; k++) { fprintf(fp, "%c", lines[k]); } } return 0; }
https://www.daniweb.com/programming/software-development/threads/72253/file-parsing-and-then-parsing-the-string
CC-MAIN-2018-05
refinedweb
391
69.96
How Do I Access Other Repl.It Databases From Different Repls? I just want to get one value for one key. I am programming in Node.js and have little to no experience with external APIs, but I tried played around with the Repl.it database URL using a API testing tool (ReqBin) and wasn't able to accomplish anything. Am I supposed to use the replit-database package to access it or do a GET request to pull data from it. Any help would be appreciated. @bigboyyyyyyyy69 Hiya! Just click the tab on the left with the database symbol and it should show a line similar to the one above. Insert that and follow the same steps :). @RayhanADev but u dont create the db in python.. right? could you send an example pls.. @bigboyyyyyyyy69 yep! I had to dig around Github and find the database module. Here's what you do: from replit import db db.db_url = "your-db-url-here" @RayhanADev Also I just thought of something: Changing the value "REPLIT_DB_URL" with os or smth.. is that even possible? Just curious lol Well I just want to say you can't. The database URL will change so you will have to regenerate each time. Anyways, I have an option so you can pass the url when making a client: const client = require("@replit/database"); const DB = new client("[INSERT-URL-HERE]"); and to find that url, just do: process.env.REPLIT_DB_URL in the repl of your choice. @Efish1824 I don't know if its not possible, since on the Repl.it Database page on the docs, () the very bottom section has a tiny place where it suggests it is possible. Heylo @Ste942 There’s a flaw in how they coded ReplDB and integrated it with the Repl so I’ll make it short: 1. Open the Repl which DB you want to use 2. Open the Shell by pressing Ctrl+Shift+S 3. In the shell type printenv. You will see a lotta stuff pop up. Look for the variable named REPLIT_DB_URL. Note that, copy it, whatever 4. In the other Repl type create a client like normal except with ONE small change: and now it should work 😊! Let me know how it goes!
https://replit.com/talk/ask/How-Do-I-Access-Other-ReplIt-Databases-From-Different-Repls/84083
CC-MAIN-2021-21
refinedweb
376
85.28
CFFI-based Python binding for LZF stream compression Project description lzf allows reading and writing files compressed with the LZF compression format. To crib some of the features listed for LibLZF: - Very fast compression speeds. - Mediocre compression ratios - you can usually expect about 40-50% compression for typical binary data Easy to use (just two functions, no state attached). - Freely usable (BSD-type-license) API This package provides reading and writing LZF data as Python file like objects. lzf.open(file, mode='r', encoding=None, errors=None) Open a LZF stream for reading or writing. file may be a path to an on-disk file, or a file-like object open for reading or writing (whatever you pass to mode). mode must be r or w to indicate reading or writing, optionally with b or t to indicate binary or text-mode IO. If the mode is text (the default), then U is also accepted to turn on universal newline mode. encoding and errors are as for the built-in open() function. Note that lzf.open() takes the Python 3 model for text IO, even on Python 2. Unless mode contains 'b', then the returned file-like object will read or write Unicode strings. Examples To open an on-disk LZF-compressed text file and print it linewise: import lzf with lzf.open('/path/to/file.txt.lzf') as f: for line in f: print(line) To compress some binary data with LZF: import lzf with lzf.open('/path/to/file.lzf', 'wb') as f: f.write(b'hello world') To read LZF compressed CBOR structures from a URL: import lzf import cbor2 from urllib.request import urlopen # Use urllib2 in Python 2 SOME_URL = '' with lzf.open(urlopen(SOME_URL), 'rb') as f: print(cbor2.load(f)) (You’ll need cbor2 installed if you want to try this.) Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/lzf/
CC-MAIN-2018-39
refinedweb
334
65.73
Linus Torvalds wrote:.>>So there's really no point in trying to push your agenda by trying to >scare people with MS activities. Linux kernel developers do what's right >because it is _right_, not because somebody else does it.>> Linus>>> >Apple will get it right. I promise it. I have met Dominic, and he is very very sharp. Look at the Tiger demos on their website. Simple interface, looks nice to me.... The one area he might screw up is performance, but I don't care to count on that.WinFS first tried to put it all in the FS, and then it became a user mode library almost certainly because they are making the standard mistakes the database guys make when they try to emulate file systems without changing the core balanced tree algorithms, and their performance sucked and they had to back off. It took 11 years for me to get it right, and they aren't as crazy-err-persistent as I am.;-)We might get lucky and have them produce another NTFS, but then again, when Microsoft focuses on a task, they do much better at it than they do most of the time, and they are focused on WinFS. They have hired very sharp people. We can hope that they don't know how to use them, but when they hire people like Gerard Salton for $1 million a year, there is just possibly a chance that they might try to get their money's worth out of him.You should not be complacent about WinFS being delayed to 2007, because even if I get funding for enhanced ReiserFS semantics tomorrow we also can't get the job done before 2007. This is big science, not writing a device driver.Finally, how much harm will it be if we do it right and it is important and they fail? Suppose I am wrong about them, and we create a powerful unifying namespace for Linux before any other OS does? Is that so bad?Creating a powerful namespace at the heart of Linux is the most important enhancement you can make to the OS. Finally the storage layer is good enough to support putting the relationship between keywords (actually keyobjects in my scheme....) and their documents directly into the FS without losing performance for traditional file system usage patterns, and I get to stop tweaking performance and go have fun with semantics in the next major release.Hans-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2004/8/28/57
CC-MAIN-2017-22
refinedweb
441
70.63
The Java Specialists' Newsletter Issue 0312001-09-26 Category: Language Java version: GitHub Subscribe Free RSS Feed Welcome to the 31st issue of The Java(tm) Specialists' Newsletter, where we look at how Hash Sets can become really confused. I love hearing from my readers, so please send your The best compliment to me is if you forward this newsletter to other Java fans, for example to your local Java User Group (JUG). I remember hearing last year that Visual Basic (shudder) was the fastest growing computer language. A report this year found that Java is now growing faster than Visual Basic, which frankly shudders me even more. There are apparently about 2 million people on this globe hacking away at our poor, dear language. Rather discouraging is that my newsletter is only reaching a meager 0.065% of Java programmers. Then again, this is supposed to be The Java Specialists' Newsletter, so maybe there aren't that many of us out there who should be considered specialists ;-) NEW: Please see our new "Extreme Java" course, combining concurrency, a little bit of performance and Java 8. Extreme Java - Concurrency & Performance for Java 8. A few weeks ago, I received an email from Charles N. May who pointed out that it is quite easy to change an Integer using reflection in the same way that I showed in my article on Insane Strings. This is only possible because for some strange reason, or no reason at all, the data member value within the Integer class was not declared final. value final Charles demonstrated the possible repercussions quite nicely by inserting the same Integer object several times into a java.util.HashSet, each time with different values. The contract of the java.util.Set says: java.util.HashSet java.util.Set java.util.Set: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. e1 e2 e1.equals(e2) It then goes on to say: Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. Interesting, but how do we define mutable, or immutable for that matter? I searched various Java texts but could not find a definition of what is meant by that. Let's try and define it for our use: Immutable Class: A class where the state cannot be changed. Simple enough, but what does state refer to? Is it a state descriptor of all the data members in the class? Or is it just the identity of the class? For example, let's consider the class Employee, which is part of the middle class ... public class Employee { private final String name; private double salary; public Employee(String name, double salary) { this.name = name; this.salary = salary; } public String getName() { return name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } } Is the Employee class mutable? If we say that the state consists of a conglomeration of all the data members then the answer is "Yes". If we say the state consists of the identity, the answer is "No", as we cannot change the state. However, it will get even more confusing as we also have to define identity. I would say that the identity is the part of the class that determines the value of e1.equals(e2) and e1.hashCode(). So, in Employee above, what is the identity? Is it name? Nope, it is actually the location of the object in memory. If we want the identity to be according to the name, we will have to write equals() and hashCode() methods, the details of which are below the scope of TJSN. e1.hashCode() name equals() hashCode() Since mutable is so hard to pin down, we should actually rewrite the javadocs for the java.util.Set interface: Note: Great care must be exercised if objects with a mutable identity are used as set elements. The behaviour of a set is not specified if the value of an object is changed in a manner that affects equals comparisons or its hashcode while the object is an element in the set. By the description above, we should be careful with objects like String, Integer, etc. where the identity can be changed at runtime using reflection. Alright, it is bad coding practice to change private data members using reflection, but Integer could easily have fitted the above description if the value had been final. Then again, as discussed in my "final" newsletter, it is also bad coding practice to not mark data members final when they should be. Incidentally, java.lang.String is a lost cause - we can never make that properly immutable since its identity is contained in an array and arrays are mutable. Once the 1'998'700 monkeys who don't read this newsletter discover you can change Strings, we are all lost! java.lang.String So, what happens when you change the identity of an object while it is in the HashSet? Let's have a look: import java.lang.reflect.Field; // I can't resist using that package import java.util.*; public class HashHashGone { // Did you know that you can make a final static data member // without a value (i.e. blank), as long as you set the value // in the static initializer? I love making every possible // field final as it smokes out a lot of bugs. private static final Field intValue; static { try { intValue = Integer.class.getDeclaredField("value"); intValue.setAccessible(true); } catch(NoSuchFieldException ex) { // we throw a RuntimeException from the static initializer // this will actually generate an Error and kill the thread // that first accessed GhostSet. throw new RuntimeException( "Serious error - no \"value\" field found in Integer"); } } // This method changes the integer passed into the method to // the new value. private static void setInteger(Integer i, int newInt) { try { intValue.set(i, new Integer(newInt)); } catch (IllegalAccessException ex) { throw new RuntimeException( "Serious error - field should have been accessible"); } } // This method will be used later to print a detailed view of // the set, including the value, the class and the identity // hash code of the object. private static void printDetailed(Set set) { System.out.print("["); Iterator it = set.iterator(); while(it.hasNext()) { Object val = it.next(); System.out.print("\t(toString()=" + val + ",class=" + val.getClass().getName() + ",identityHashCode=" + System.identityHashCode(val) + ")"); if (it.hasNext()) System.out.print(", "); System.out.println(); } System.out.println("]"); } public static void main(String[] args) { if (args.length != 2) { System.out.println( "arguments: <initial-intvalue> <num-copies-to-insert-in-Set>"); return; } int initialValue = Integer.parseInt(args[0]); int numberOfCopiesToInsert = Integer.parseInt(args[1]); Integer x = new Integer(initialValue); int currValue = initialValue; Set set = new HashSet(); for (int i = 0; i < numberOfCopiesToInsert; i++) { setInteger(x, ++currValue); set.add(x); } setInteger(x, initialValue); System.out.println("here's a set containing " + numberOfCopiesToInsert + " copies of Integer(" + x + "): "); System.out.println(set); System.out.println("detailed view of set:"); printDetailed(set); System.out.println("and does it contain that Integer?: " + set.contains(x)); System.out.println("can the Integer be removed from the Set?"); System.out.println(set.remove(x)); System.out.println("the Set contents after attempted remove:"); System.out.println(set); setInteger(x, -initialValue); System.out.println( "altering the Integer to its opposite makes the Set contain:"); System.out.println(set); setInteger(x, initialValue); currValue = initialValue; for (int i = 0; i < numberOfCopiesToInsert; i++) { setInteger(x, ++currValue); set.remove(x); } System.out.println("now all the elements have been removed " + "from the Set as it contains:"); System.out.println(set); System.out.println(); } } When I run this with java HashHashGone 42 5, I get the following output: java HashHashGone 42 5 here's a set containing 5 copies of Integer(42): [42, 42, 42, 42, 42] detailed view of set: [ ) ] and does it contain that Integer?: false can the Integer be removed from the Set? false the Set contents after attempted remove: [42, 42, 42, 42, 42] altering the Integer to its opposite makes the Set contain: [-42, -42, -42, -42, -42] now all the elements have been removed from the Set as it contains: [] The HashSet actually contains a HashMap that keeps the entries as keys and values. The HashMap contains a rehash() method, which is called when the table grows past the threshold determined by the number of entries and fill factor. However, contrary to what I believed until I tried it out today, the rehash method does not consider the possibility that there may be two objects in different hash positions, but equal, in the table. Re-hashing will therefore not solve the problem described above. rehash() Moral of the story, assuming there is still morality left in this world? (btw, have you ever considered how similar the words mortal, moral and mutable are?) OK, the moral is? Never create a class where the identity can be changed once the object has been created. That's all for this week. Please take a moment to think of how I could improve this newsletter and pop me an email. Regards Heinz Language Articles Related Java Course
http://www.javaspecialists.eu/archive/Issue031.html
CC-MAIN-2016-36
refinedweb
1,554
56.45
What I'm trying to figure out is when I run this code for smaller numbers it returns the list just fine, but for larger numbers (I would call this small in the context of what I'm working on.) like 29996299, it will run for a long time, I've waited for 45 minutes with no results and had to end up killing the program. What I was wondering was whether there was a more efficient way to handle numbers whose scale was larger than 4 or 5 digits. I've tested a few permutations of the range function to see if there was a better way to handle the limits of the list I want to produce but nothing seems to have any effect on the amount of time it takes to do the computation. I'm new to python and am not that experienced as a programmer. Thank you for your time. ran the program again before submitting this post and it took an hour and a half or so. function of the program is to take the User selected number, use it to generate a lower bound, find all primes between the bound and input and append to list, then generate a secound upper bound and find all primes and then append to list, to create a list that extends forwards and backwards from the initial number. the program works like I expect it to but not as quickly as I need it to since the numbers I'm going to be dealing with are going to get large quickly, almost doubling at each phase. initial_num = input("Please enter a number. ") lower_1 = int(initial_num) - 1000 upper_1 = int(initial_num) list_1 = [] for num in range(lower_1,upper_1): if num > 1: for i in range(2,num): if (num % i) == 0: break else: list_1.append(num) lower_2 = list_1[-1] upper_2 = list_1[-1] + 2000 list_2 = [] for num in range(lower_2,upper_2 +1): if num > 1: for i in range(2,num): if (num % i) == 0: break else: list_2.append(num) list_3 = list_1 + list_2[1:] print list_3 You can use a more efficient algorithm to generate the entire list of prime numbers up to N. This is the Sieve of Erathostenes. Please have a look at the linked article, it even includes an example pseudocode. The basic idea of the algorithm is: At the end you are left with a list of prime numbers. An implementation in Pyhton from here def eratosthenes2(n): multiples = set() for i in range(2, n+1): if i not in multiples: yield i multiples.update(range(i*i, n+1, i)) print(list(eratosthenes2(100))) To reduce memory consumpution you could consider usgin a bitset, storing one bit for each number. That should reduce memory usage by between 32 - 64 times. A bitset implementation is available for python here.
https://codedump.io/share/iZRbraBeeUWk/1/efficient-method-for-generating-lists-of-large-prime-numbers
CC-MAIN-2017-47
refinedweb
474
66.07
Reading Pythonistas/Apples plist file format? Hi, does anyone know how Pyhtonistas plistfiles are being encoded? I always assumed that plists are just XML files in UTF-8 encoding. I however do fail reading pythonistas plist files, specifically : private/var/mobile/Containers/Shared/AppGroup/{Pythonistas app hash}/Library/Preferences/group.pythonista.plist I do keep getting encoding exceptions: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 8: invalid continuation byte I did try ascii, utf-8,and utf-16with no luck. Plists can be stored in different formats – ASCII (rare nowadays), XML, or binary. You might want to use the plistlibmodule from the standard library, it should be able to handle all formats. thanks, that did work (Python really has a lib for everything): import plistlib path = '/private/var/mobile/Containers/Shared/AppGroup/CB0CD8AB-6A20-4ECC-8312-B0822DFFD9A1/Library/Preferences/group.pythonista.plist' with open(path, 'rb') as f: data = plistlib.load(f) print(data) The file however does not contain what I did hope for. Any chance you could shed some light on where the currently active theme is being stored? I know where the theme json files are stored, but I am sort of stumped on how to get the active theme. Ps: I am aware of the theme related editorfunctions, but these have it quirks, which is why I am trying to do it by hand. What quirks specifically? Anyway, you could look at the source code of the editormodule, to see how it gets the current theme (Modules & Templates/Standard Library (3.5)/site-packages/editor.py). In short, it uses NSUserDefaultsvia objc_util. Thanks again, I'll see what I can figure out. About the quirks - This little setup shows what I consider quirky - not everything is being styled correctly. import editor import ui import time class SomeUi(ui.View): def __init__(self): self.frame = (0, 0, 500, 470) self.table_view = ui.TableView(frame=(10, 10, 480, 400)) self.text_view = ui.TextField(frame=(10, 420, 480, 40)) self.add_subview(self.table_view) self.add_subview(self.text_view) editor.apply_ui_theme(self) def wait(dt=1.0): t = time.perf_counter() while time.perf_counter() - t < dt: pass op = SomeUi() op.present('sheet') wait(3) op.close() wait(1) editor.present_themed(op, style='sheet') In a more complex setup I have also experieneced that when reading colors from an uielement styled with the editor.apply_ui_theme()before any ui.View.layout()has ran can give you back a wrong color (-1, 1, 1, 1). Hi, had some time to poke in editoraround. editor.get_theme_dict()does exactly what I want. It should be made officially public (as it is already not internal, but doesn't appear in the autocomplete for some reason). Some mentioning in the docs would also be nice.
https://forum.omz-software.com/topic/4110/reading-pythonistas-apples-plist-file-format
CC-MAIN-2021-39
refinedweb
460
60.92
This action might not be possible to undo. Are you sure you want to continue? Release 1.0 Selenium Project March 26, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Selenium 1 (Selenium RC) 6. . . . . . . . . . . . . 7. .5 Programming Your Test . . . . . . . . . . . . . . . . . . . . . . . . . . . Test Design Considerations 7. .25 3. . . . . . . . . . . 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . .2 RemoteWebDriver . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 WebDriver Implementations . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Introducing Test Design . . . . . . . . . . .3 Installation . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 . . . . .1 Introduction . . . . . . 4.10 Specifying the Path to a Specific Browser . . . . . . . . .24 3. . . . . . . . . . . . . . . . . . . . .2 Next Steps For Using WebDriver . . . .2 Types of Tests . . . . 6. . .4 Location Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. .9 Server Options . . . . . . . . . . . . . . . 40 41 42 42 42 45 45 47 51 55 56 57 58 59 59 61 61 61 62 62 62 62 63 65 65 65 67 69 73 79 80 82 85 89 89 93 94 94 101 101 101 103 104 106 107 108 109 112 Selenium 2. . . .7 Getting and Using WebDriver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 Parallelizing Your Test Runs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii . . . . . . . . . . . . . . . . . . . . . .26 3. . . . . . . . . . . .5 Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . .7 UI Mapping . . . . . . . . . . . . . . . . . . . . . . .5 Wrapping Selenium Calls to Reduce Duplication . . . 6. . . . . . . . . . . . . . .3 AdvancedUserInteractions . . 6. . . . . . 4. . . . . . . .13 Supporting Additional Browsers and Browser Configurations 6. . . . .27 3. . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28 4 Writing a Test Suite . . . . . 6.7 Reporting Results . . . . . . . . . . . . . . . . .6 How XPATH Works in WebDriver . . . . . . . . . . . . . . . . . Executing Selenium-IDE Tests on Different Browsers Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . .2 How Selenium RC Works . . . . . WebDriver: Advanced Usage 5. 5. . . 6. . . . . . . . . . . . . . . . .11 Selenium RC Architecture . . . . Format . . . . 6. . . . . . . . . . . . . . .5 Tips and Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14 Troubleshooting Common Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . User Extensions . . 7. . . . . . . . . . . . . . . .6 Browser Startup Manipulation 5. . . . . . . . . . . . . .4 HTML5 . 5 . . . .1 The 5 Minute Getting Started Guide 4. . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . 5. 4. .6 Learning the API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . .8 Adding Some Spice to Your Tests . . . . . . . . . .9 Data Driven Testing . . . . . . . . . . . . . . . . . . .8 Roadmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . .0 and WebDriver 4. .4 From Selenese to a Program . . . 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Emulating Selenium RC . . . 4. . . . . . . . . . . . . . . . .12 Handling HTTPS and Security Popups . . . . . . . . . . . . . . . . . . . . . . . . .6 ‘Safe Operations’ that Depend on Element Presence 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Explicit and Implicit Waits . . . .9 Further Resources . . . . . . . . . 5. . . . .8 Page Object Design Pattern . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . .3 Validating Results . . . . . . . 6. . . . . . .2 Actions . . . . . . . . . . . . . . . . . . .6 Using User-Extensions With Selenium RC 115 117 117 117 117 118 119 119 123 . . . . . . . . . . . . . 112 8 9 Selenium-Grid User-Extensions 9. . . . . . . . . . . . . . . . . . .1 Configuring Selenium-RC With Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Using User-Extensions With Selenium-IDE 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .NET client driver configuration 11 Java Client Driver Configuration 127 11. . . . . . . . . . . . . . 127 11. . . . . . . . . . . . . . . . . . . . . . . . . .1 Useful XPATH patterns . 9. 9. . . . . . . . . . . . . . . . . . . 9. .4 Locator Strategies . . . . . . . . . . . . .1 Introduction . . . . . 9. .2 Configuring Selenium-RC With Intellij . . . . . . . . . . . . . . . . . .2 Starting to use CSS instead of XPATH . . . . . . . . . . . . . . 143 12 Python Client Driver Configuration 155 13 Locating Techniques 159 13. . . . . . . .10 Handling Errors . . . . .7. . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Accessors/Assertions . . . . . . . . . . . . . . 159 iii . . . . . . . . . . . . . . . . 159 13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 . . . . . iv . 0 Contents: CONTENTS 1 .Selenium Documentation. Release 1. Selenium Documentation.0 2 CONTENTS . Release 1. CHAPTER ONE NOTE TO THE READER–DOCS BEING REVISED FOR SELENIUM 2.0! Hello, and welcome! The Documentation Team would like to welcome you, and to thank you for being interested in Selenium. We are currently updating this document for the Selenium 2.0 release. This means we are currently writing and editing new material, and revising old material. While reading, you may experience typos or other minor errors. If so, please be patient with us. Rather, along with its tight integration with the browser, is unmatched by available proprietary tools. We are very excited to promote Selenium and, hopefully, to expand its user community. In short, we really want to “get the word out” about Selenium. We believe you will be similarly excited once you understand how Selenium approaches test automation. It’s quite different from other automation tools. Whether you are brand-new to Selenium, or have been using it for awhile, we believe this documentation will truly help to spread the knowledge around. We have aimed our writing so that those completely new to test automation can use this document as a stepping stone. However, at the same time we have included a number of advanced, test design topics that should be interesting to the experienced software engineer. In both cases we have written the “SelDocs” 2. there is currently no test automation available. Because of its Javascript based automation engine and the security limitations browsers apply to Javascript. allowing many options for locating UI elements and comparing expected test results against actual application behavior. sometimes there simply is not enough time to build test automation. To make things “worst”. Perhaps the best explanation for why WebDriver and Selenium are merging was detailed by Simon Stewart. manual testing may be more effective. he realized there were better uses of his time than manually stepping through the same tests with every change he made. The entire suite of tools results in a rich set of testing functions specifically geared to the needs of testing of web applications of all types. In 2006 a plucky engineer at Google named Simon Stewart started work on a project he called WebDriver. He developed a Javascript library that could drive interactions with the page. There are times when manual testing may be more appropriate.4 Brief History of The Selenium Project Selenium first came to life in 2004 when Jason Huggins was testing an internal application at ThoughtWorks. however learning all the tools will give you many different options for approaching different test automation problems. If an application has a very tight deadline.3 Introducing Selenium Selenium is set of different software tools each with a different approach to supporting test automation. allowing him to automatically rerun tests against multiple browsers. The Dark Knight is viewed by every human (twice). if the application’s user interface will change considerably in the near future.Selenium Documentation. Selenium had massive community and commercial support. 2. While Selenium was a tremendous tool. Being a smart guy. which underlies all the functionality of Selenium Remote Control (RC) and Selenium IDE. but testers had to work around the limitations of the product. thus avoiding the restrictions of a sandboxed Javascript environment. and it’s imperative that the testing get done within that time frame. “Why are the projects merging? Partly because webdriver addresses some shortcomings in selenium (by being able to bypass the JS sandbox. The WebDriver project began with the aim to solve the Selenium’ pain-points. The Beijing Olympics mark China’s arrival as a global power. then manual testing is the best solution.0 It is not always advantageous to automate test cases. Jump to 2008. 2009. For the short term. Release 1. Introduction . in a joint email to the WebDriver and Selenium community on August 6. Google had long been a heavy user of Selenium. still reeling from the untimely loss of Heath Ledger. the creator of WebDriver. But the most important story of that year was the merging of Selenium and WebDriver. different things became impossible to do. One of Selenium’s key features is the support for executing one’s tests on multiple browser platforms. Most Selenium QA Engineers focus on the one or two tools that most meet the needs of their project. And we’ve got a gorgeous 6 Chapter 2. it wasn’t without it’s drawbacks. for example. then any automation might need to be rewritten anyway. Simon wanted a testing tool that spoke directly to the browser using the ‘native’ method for the browser and operating system. The joining of the two tools provided a common set of features for all users and brought some of the brightest minds in test automation under one roof. These operations are highly flexible. using all sorts of special features new browsers provide and making this restrictions more and more painful. but WebDriver was clearly the tool of the future. Selenium RC was ground-breaking because no other product allowed you to control a browser from a language of your choosing. webapps became more and more powerful over time. That library eventually became Selenium Core. Also. massive mortgage default in the United States triggers the worst international recession since the Great Depression. For instance. Selenium RC was the main Selenium project for a long time. 7 . 2. Selenium 2 still runs Selenium 1’s Selenium RC interface for backwards compatibility.5. Selenium IDE doesn’t provide iteration or conditional statements for test scripts. it is not designed to run your test passes nor is it designed to build all the automated tests you will need. Selenium 1 is still actively supported (mostly in maintenance mode) and provides some features that may not be available in Selenium 2 for a while.5. It is a Firefox plugin and provides an easy-to-use interface for developing automated tests. 2. It supports the WebDriver API and underlying technology. The reasons are partly technical and partly based on the Selenium developers encouraging best practices in test automation which always requires some amount of programming. The Selenium developers recommend for serious.0 is the product of that effort. 2. including a more cohesive and object oriented API as well as an answer to the limitations of the old implementation. including support for several languages (Java. Release 1. HP. This brand new automation tool provides all sorts of awesome features. 2. At the time of writing there is no plan to add such thing. before the WebDriver/Selenium merge brought up Selenium 2.1 Selenium 2 (aka. Selenium IDE has a recording feature.3 Selenium IDE Selenium IDE (Integrated Development Environment) is a prototyping tool for building test scripts.2 Selenium 1 (aka. robust test automation either Selenium 2 or Selenium 1 to be used with one of the many supported programming languages. Perl and C#) and support for almost every browser out there. along with the Selenium 1 technology underneath the WebDriver API for maximum flexibility in porting your tests. Selenium IDE is simply intended as a rapid prototyping tool.5 Selenium’s Tool Suite Selenium is composed of multiple software tools. Selenium RC or Remote Control) As you can read in Brief History of The Selenium Project. Python. Selenium Webdriver) Selenium 2 is the future direction of the project and the newest addition to the Selenium toolkit.Selenium Documentation. PRuby. both the Selenium and WebDriver developers agreed that both tools have advantages and that merging the two projects would make a much more robust automation tool. Each has a specific role. Selenium 2.5. which records user actions as they are performed and then exports them as a reusable script in one of many programming languages that can be later executed.5. Javascript. As you can read in Brief History of The Selenium Project. Note: Even though Selenium IDE has a “Save” feature that allows users to keep the tests in a tablebased format for later import and execution. Specifically.0 API). the newest and more powerful tool.” 2. In addition. 4 Selenium-Grid Selenium-Grid allows the Selenium RC solution to scale for large test suites and for test suites that must be run in multiple environments. Which one you choose depends on you. We recommend those who are completely new to Selenium to read through these sections. run tests Start browser. Linux. Mac Windows. or a slow-running test suite. However. different tests can be run at the same time on different remote machines. Release 1. Introduction . run tests Start browser. Linux. run tests Start browser. and therefore building a new test suite from scratch. Using the IDE you can create simple tests quickly. Linux. 2.7 Supported Browsers IMPORTANT: This list was for Sel 1. Mac Windows. sometimes within seconds. 2.0–we will do that very soon. run tests Start browser. Mac Windows. Linux. run tests Start browser. run tests Start browser. if you must run your test suite on multiple environments you can have different remote machines supporting and running your tests in them at the same time.0 2. Linux. Selenium 1 is provided for backwards compatibility. run tests Start browser.0. Mac Windows. At the time of writing the Selenium developers are planning on the Selenium-WebDriver API being the future direction for Selenium. 8 Chapter 2. In each case Selenium Grid greatly improves the time it takes to run your suite by making use of parallel processing 1 (RC) Start browser. run tests Start browser. both have strengths and weaknesses which are discussed in the corresponding chapters of this document. that is. Also. Mac Windows Windows Windows Windows. if you have a large test suite. It requires updating for Sel2. Linux. Still. Mac Windows. run tests Start browser. First. Selenium Grid allows you to run your tests in parallel. Linux.6 Choosing Your Selenium Tool Many people get started with Selenium IDE. run tests Start browser. We don’t. Mac Windows. recommend you do all your test automation using Selenium IDE. run tests Start browser. Browser Firefox 3. This has two advantages. run tests Partial support possible** Operating Systems Windows. Mac As applicable * Tests developed on Firefox via Selenium IDE can be executed on any other supported browser via a simple Selenium RC command line.5.Selenium Documentation. you can boost its performance substantially by using Selenium Grid to divide your test suite to run different tests at the same time using those different machines. you will probably want to go with Selenium 2 since this is the portion of Selenium that will continue to be supported in the future. Mac Windows. Mac Windows. If you are not already experienced with a programming or scripting language you can use Selenium IDE to get familiar with Selenium commands. run tests Start browser. however. for those who are adopting Selenium for the first time. To effectively use Selenium you will need to build and run your tests using either Selenium 2 or Selenium 1 in conjunction with one of the supported programming languages. An architecture diagram is provided to help illustrate these points. how to implement data-driven tests (tests where one can varies the data between test passes) and other methods of programming common test automation tasks. Flexibility and Extensibility 9 . There are many ways you can add functionality to both Selenium test scripts and Selenium’s framework to customize your test automation. the sourcecode can always be downloaded and modified. since Selenium is Open Source. the installation and setup of Selenium RC is covered here. These customizations are described in various places throughout this document. If you are not experienced in programming. For the more experienced user. This is perhaps Selenium’s greatest strenght when compared with other automation tools. but depending on browser security settings there may be technical limitations that would limit certain features. this chapter may still interest you in that you can use Selenium IDE to do rapid prototyping of your tests. 2. The remaining chapters of the reference present: Selenium IDE Introduces Selenium IDE and describes how to use it to build test scripts. We introduce Selenium to new users and we do not assume prior Selenium experience. https requests. We also demonstrate techniques commonly asked about in the user forum such as how to design setup and teardown functions. In addition. Selenium 1 Explains how to develop an automated test program using the Selenium RC API. for instance. Test Design Considerations This chapter presents programming techniques for use with SeleniumWebDriver and Selenium RC. Selenium-Grid This chapter is not yet developed. This section also demonstrates how your test script can be “exported” to a programming language for adding more advanced capabilities not supported by Selenium IDE. that Selenium RC supports are described. pop-ups. Solutions to common problems frequently difficult for new Sel-R users are described here. examples of common usage. 2. Release 1. The various modes. or configurations.0 ** Selenium RC server can start any executable. this guide can act as a reference. We do assume. 2. handling Security Certificates. and a chapter on test design techniques. Selenium 2 Explains how to develop an automated test program using Selenium 2. but still hoping to learn test automation this is where you should start and you’ll find you can create quite a few automated tests with Selenium IDE. if you are experienced in programming. We’ve provided information on the Selenium architecture. along with their trade-offs and limitations. Many examples are presented in both programming languages and scripting languages. Also. however.Selenium Documentation.8. we recommend browsing the chapter and subheadings. extended and customized.9 What’s in this Book? This user’s guide targets both new users and those who have already used Selenium but are seeking additional knowledge. and the opening of new windows. User extensions Describes ways that Selenium can be modified. that the user has at least a basic understanding of test automation. Also. For the more experienced.8 Flexibility and Extensibility You’ll find that Selenium is highly flexible. using the Selenium Integrated Development Environment. As an administrator of the SeleniumHQ website.10 The Documentation Team–Authors Past and Present In alphabetical order. 10 Chapter 2. we would not have such a great tool to pass on to you. the following people have made significant contributions to the authoring of this user’s guide or with out publishing infrastructure or both. and the continued efforts of the current developers.0 2.Selenium Documentation. And of course. • Dave Hunt • Mary Ann May-Pumphrey • Paul Grandjean • Peter Newhook • Santiago Suarez Ordonez • Tarun Kumar 2. Also thanks goes to Andras Hatvani for his advice on publishing solutions. Patrick helped us understand the our audience. and long term involvement in the Selenium community. we must recognize the Selenium Developers. creator of Selenium RC. He also set us up with everything we needed on the seleniumhq. Release 1.10.1 Acknowledgements A huge special thanks goes to Patrick Lightbody.org website for publishing the documents. Introduction . his support was invaluable when writing the original user’s guide. and to Amit Kumar for participating in our discussions and for assisting with reviewing the document. Without the vision of the original designers. They have truly designed an amazing tool. It also contains a context menu that allows you to first select a UI element from the browser’s currently displayed page and then select from a list of Selenium commands with parameters pre-defined according to the context of the selected UI element. so you will need to click ‘Allow’ to proceed with the installation. as shown in the following screenshot. download the IDE from the SeleniumHQ downloads page Firefox will protect you from installing addons from unfamiliar locations. 3. but also an excellent way of learning Selenium script syntax. 11 . first.2 Installing the IDE Using Firefox.CHAPTER THREE SELENIUM-IDE 3. This chapter is all about the Selenium IDE and how to use it effectively. This is not only a time-saver. It’s an easy-to-use Firefox plug-in and is generally the most efficient way to develop test cases.1 Introduction The Selenium-IDE (Integrated Development Environment) is the tool you use to develop your Selenium test cases. 0 When downloading from Firefox. The Firefox Add-ons window pops up. Selenium-IDE .Selenium Documentation. first showing a progress bar. Release 1. and when the 12 Chapter 3. you’ll be presented with the following window. Select Install Now. Selenium Documentation. After Firefox reboots you will find the Selenium-IDE listed under the Firefox Tools menu.2. 3. Installing the IDE 13 . displays the following.0 download is complete. Restart Firefox. Release 1. 0 3. 14 Chapter 3. simply select it from the Firefox Tools menu. Selenium-IDE .Selenium Documentation.3 Opening the IDE To run the Selenium-IDE. It opens as follows with an empty script-editing window and a menu for loading. or creating new test cases. Release 1. You can set the timeout value for certain commands.4. delete. and specify the format (language) used when saving your test cases.4.0 3. and save test case and test suite files. IDE Features 15 . The right-most button. is the record button.4 IDE Features 3. undo. 3.1 Menu Bar The File menu allows you to create.Selenium Documentation.2 Toolbar The toolbar contains buttons for controlling the execution of your test cases. The Options menu allows the changing of settings. open. and select all operations for editing the commands in your test case. only one item on this menu–UI-Element Documentation–pertains to Selenium-IDE. the one with the red-dot. including a step feature for debugging your test cases. paste. 3. The Edit menu allows copy. The Help menu is the standard Firefox Help menu. add user-defined user extensions to the base set of Selenium commands. Release 1.4. 3 Test Case Pane Your script is displayed in the test case pane. The other tab . The TestRunner is not commonly used now and is likely to be deprecated. See the Options menu for details. Selenium-IDE . If a second parameter is specified by the Reference tab. Pause/Resume: Allows stopping and re-starting of a running test case. Run: Runs the currently selected test. and Value entry fields display the currently selected command along with its parameters. 3. including copy.0 Speed Control: controls how fast your test case runs. This button is for evaluating test cases for backwards compatibility with the TestRunner. Most users will probably not need this button.Source displays the test case in the native format in which the file will be stored. By default. it always goes in the Value field. Step: Allows you to “step” through a test case by running it one command at a time. 16 Chapter 3. When only a single test is loaded this button and the Run All button have the same effect.Selenium Documentation. It has two tabs. one for displaying the command and their parameters in a readable “table” format. The first parameter specified for a command in the Reference tab of the bottom pane always goes in the Target field. this is HTML although it can be changed to a programming language such as Java or C#. These are entry fields where you can modify the currently selected command. The Command. Detailed documentation on rollup rules can be found in the UI-Element Documentation on the Help menu. The Source view also allows one to edit the test case in its raw form. Target. TestRunner Mode: Allows you to run the test case in a browser loaded with the Selenium-Core TestRunner. Run All: Runs the entire test suite when a test suite with multiple test cases is loaded. Use for debugging test cases.4. cut and paste operations. Apply Rollup Rules: This advanced feature allows repetitive sequences of Selenium commands to be grouped into a single action. or a scripting language like Python. Record: Records the user’s browser actions. Release 1. it is critically important to ensure that the parameters specified in the Target and Value fields match those specified in the parameter list in the Reference pane. These messages are often useful for test case debugging. If there is a mismatch in any of these three areas. error messages and information messages showing the progress are displayed in this pane automatically. the command will not run correctly. When entering or modifying commands. 3.4 Log/Reference/UI-Element/Rollup Pane The bottom pane is used for four different functions–Log. UI-Element.Selenium Documentation. Also notice the Info button is a drop-down allowing selection of different levels of information to log.4. the Reference pane will display documentation on the current command. The number of parameters provided must match the number specified.0 If you start typing in the Command field. and the type of parameters provided must match the type specified. While the Reference tab is invaluable as a quick reference. the order of parameters provided must match the order specified. you can then select your desired command from the drop-down. Reference The Reference tab is the default selection whenever you are entering or modifying Selenese commands and parameters in Table mode. IDE Features 17 . Release 1. even if you do not first select the Log tab. whether from Table or Source mode. a drop-down list will be populated based on the first characters you type. and Rollup– depending on which tab is selected. Notice the Clear button for clearing the Log.4. Reference. it is still often necessary to consult the Selenium Reference document. 3. Log When you run your test case. In Table mode. along with the parameters. This will cause unexpected test case failures. As you use the IDE however. a test developer will require all three techniques.” During recording. If you do not want Selenium-IDE to begin recording automatically you can turn this off by going under Options > Options. 3. With Selenium-IDE recording. A paragraph or a heading will work fine. • Following a link usually records a click command. Typically. that is in the chapter on “Selenese” Selenium Commands. Selenium-IDE will automatically insert commands into your test case based on your actions. You will see a context menu showing verify and/or assert commands. 18 Chapter 3. the record button is ON by default. When Selenium-IDE is first opened. this will include: • clicking a link .click command Here are some “gotchas” to be aware of: • The type command may require clicking on some other area of the web page for it to record. Release 1. your test case will continue running commands before the page has loaded all its UI elements. Selenium-IDE will attempt to predict what command. Otherwise.select command • clicking checkboxes or radio buttons .0 UI-Element and Rollup Detailed information on these two panes (which cover advanced features) can be found in the UIElement Documentation on the Help menu of Selenium-IDE.type command • selecting options from a drop-down listbox . Open a web-page of your choosing and select a block of text on the page.. Now. Here we’ll simply describe how to add them to your test case.1 Recording Many first-time users begin by recording a test case from their interactions with a website. The context menu should give you a verifyTextPresent command and the suggested parameter should be the text itself. We won’t describe the specifics of these commands here.click or clickAndWait commands • entering values . there may only be one Selenium command listed. 3.. 3.Selenium Documentation. Let’s see how this works. The first time you use Selenium. You will often need to change this to clickAndWait to ensure your test case pauses until the new page is completely loaded. Frequently.2 Adding Verifications and Asserts With the Context Menu Your test cases will also need to check the properties of a web-page. Selenium-IDE . you will find additional commands will quickly be added to this menu. and deselecting “Start recording immediately on open. right-click the selected text. you will need for a selected UI element on the current web-page.5 Building Test Cases There are three primary methods for developing test cases.5. This requires assert and verify commands.5. go to the browser displaying your test application and right click anywhere on the page. Table View Select the line in your test case where you want to insert the comment. in the Test Case Pane. Now use the Command field to enter the comment.your comment here -->. first parameter (if one is required by the Command). Add an HTML-style comment. For now though. for testing your currently selected UI element.5. selecting verifyElementPresent for an image should later cause that command to be available on the primary context menu the next time you select an image and right-click. i. An empty command will cause an error during execution. Your comment will appear in purple font. Insert Comment Comments may be added to make your test case more readable. an empty comment won’t. Building Test Cases 19 . left-click on the line where you want to insert a new command. 3. 3. Again. the IDE will add a blank line just ahead of the line you selected. in the Test Case Pane. You may need to use Show All Available Commands to see options other than verifyTextPresent. These comments are ignored when the test case is run. if one is required). the more commonly used ones will show up on the primary context menu. This shows many. Once you select these other options.e. Try a few more UI elements. again. Try right-clicking an image. just create empty comments.Selenium Documentation. and second parameter (again. For example. <!-.. Release 1.5. and enter the HTML tags needed to create a 3-column row containing the Command. To do this. To do this. or a user control like a button or a checkbox. along with suggested parameters. Right-click and select Insert Comment. Right-click and select Insert Command. many more commands. these commands will be explained in detail in the chapter on Selenium commands. Source View Select the point in your test case where you want to insert the command. feel free to use the IDE to record and select commands into a test case and then run it. Source View Select the point in your test case where you want to insert the comment. Now use the command editing text fields to enter your new command and its parameters. You can learn a lot about the Selenium commands simply by experimenting with the IDE.0 Also.3 Editing Insert Command Table View Select the point in your test case where you want to insert the command. Be sure to save your test before switching back to Table view. notice the Show All Available Commands menu option. left-click between the commands where you want to insert a new command. Comments may also be used to add vertical white space (one or more blank lines) in your tests. Suppose that a site named. Run a Test Case Click the Run button to run the currently displayed test case. Selenium distinguishes between test cases and test suites. This is useful for debugging your test case. when you are not sure if it is correct. or comment. and Value fields. To continue click Resume. Selenium-IDE . 3. or save the test suite. and from the context menu select Toggle Breakpoint. and you can do a batch run of an entire test suite. This also is used for debugging. simply modify which line you wish– command. you’ll be prompted to save them before saving the test suite.Selenium Documentation. Selenium-IDE displays its Selenium commands in the Test Case Pane. Release 1. Start from the Middle You can tell the IDE to begin running from a specific command in the middle of the test case. You can run a test case all at once. You can double-click it to see if it runs correctly. 3. When you open an existing test case or suite.portal. select a command.7 Using Base URL to Run Test Cases in Different Domains The Base URL field at the top of the Selenium-IDE window is very useful for allowing test cases to be run across different domains. select a command.com had an in-house beta 20 Chapter 3. Run Any Single Command Double-click any single command to run it by itself.4 Opening and Saving a Test Case Like most programs. Target. right-click. there are Save and Open commands under the File menu. right-click. run it one line at a time. This is also available from the context menu. To save your Selenium-IDE tests for later use you can either save the individual test cases. stop and start it. run a single command you are currently developing. It lets you immediately test a command you are constructing. Run a Test Suite Click the Run All button to run all the test cases in the currently loaded test suite.0 Edit a Command or Comment Table View Simply select the line to be changed and edit it using the Command.6 Running Test Cases The IDE allows many options for running your test case.5. Stop in the Middle You can set a breakpoint in the test case to cause it to stop on a particular command. parameter. Source View Since Source view provides the equivalent of a WYSIWYG editor. However. 3. To set a breakpoint. Stop and Start The Pause button can be used to stop the test case while it is running. To set a startpoint. This is useful when writing a single command. and from the context menu select Set/Clear Start Point. The icon of this button then changes to indicate the Resume button. Execution of test cases is very flexible in the IDE. If the test cases of your test suite have not been saved. Release 1. event handling. Any test cases for these sites that begin with an open statement should specify a relative URL as the argument to open rather than an absolute URL (one starting with a protocol such as http: or https:).8. pop up windows. are the set of commands that run your tests. Ajax functionality.news. If an Action fails. or has an error. alerts.portal. Accessors and Assertions. the execution of the current test is stopped.8 Selenium Commands – “Selenese” Selenium commands.com/about. A command is what tells Selenium what to do. They do things like “click this link” and “select that option”. submitting forms. A sequence of these commands is a test script. and table data among other things.0 site named. the test case below would be run against. In addition Selenium commands support testing of window size. For example. one can test the existence of UI elements based on their HTML tags.com/about. Selenium provides a rich set of commands for fully testing your web-app in virtually any way you can imagine. The command set is often called selenese. Selenium Commands – “Selenese” 21 .com.html: This same test case with a modified. mouse position. test for specific content. The Command Reference lists all the available commands. Selenium-IDE will then create an absolute URL by appending the open command’s argument onto the end of the value of Base URL. 3.html: Base URL setting would be run against 3.portal. and we present the many choices you have in testing your web application when using Selenium.news. test for broken links. selection list options. input fields. often called selenese. Selenium commands come in three “flavors”: Actions. • Actions are commands that generally manipulate the state of the application. and many other web-application features. In selenese. Here we explain those commands in detail. These commands essentially create a testing language.portal.Selenium Documentation. When an “assert” fails. All Selenium Assertions can be used in 3 modes: “assert”.9 Script Syntax Selenium commands are simple. logging the failure. They are also used to automatically generate Assertions. This suffix tells Selenium that the action will cause the browser to make a call to the server. The second and third columns may not require values depending on the chosen Selenium command. asserts the page title and then verifies some content on the page: 22 Chapter 3.0 Many Actions can be called with the “AndWait” suffix. Examples include “make sure the page title is X” and “verify that this checkbox is checked”.g. selenium variables. you can “assertText”. For example: verifyText //div//a[2] Login The parameters are not always required. the test will continue execution. “verifyText” and “waitForText”. text patterns. Here are a couple more examples: goBackAndWait verifyTextPresent type type Welcome to My Home Page (555) 666-7066 ${myVariableAddress} id=phone id=address1 The command reference describes the parameter requirements for each command. Here is an example of a test that opens a page. “clickAndWait”. This consists of an HTML table with three columns. For example. they will fail and halt the test if the condition does not become true within the current timeout setting (see the setTimeout action below). the test is aborted. e. and the commands themselves are described in considerable detail in the section on Selenium Commands.g. but they should be present. Selenium-IDE . 3. In some cases both are required. This allows a single “assert” to ensure that the application is on the correct page. etc. Release 1. they consist of the command and two parameters. However. “waitFor” commands wait for some condition to become true (which can be useful for testing Ajax applications). • a text pattern for verifying or asserting expected page content • a text pattern or a selenium variable for entering text in an input field or for selecting an option from an option list. and the final column contains a value. • Accessors examine the state of the application and store the results in variables. but they verify that the state of the application conforms to what is expected. and in still others the command may take no parameters at all. They will succeed immediately if the condition is already true. in others one parameter is required. e. “verify”. labels. and that Selenium should wait for a new page to load. Locators. When a “verify” fails. “storeTitle”.Selenium Documentation. and ” waitFor”. • Assertions are like Accessors. Each table row represents a new Selenium command. it depends on the command. The first column identifies the Selenium command. followed by a bunch of “verify” assertions to test form field values. the second is a target. however they are typically: • a locator for identifying a UI element within a page. Selenium scripts that will be run from Selenium-IDE will be be stored in an HTML text file format. Parameters vary. These are probably the most commonly used commands for building tests. from the Selenium-IDE. if C# is the chosen language. If using an interpreted language like Python with Selenium-RC than some simple programming would be involved in setting up a test suite. we’ll show you a few typical Selenium commands. Additionally. <html> <head> <title>Test Suite Function Tests . The syntax again is simple.10. Nunit could be employed. one after another. Often one will run all the tests in a test suite as one continuous batch-job.0 <table> <tr><td>open</td><td></td><td>/download/</td></tr> <tr><td>assertTitle</td><td></td><td>Downloads</td></tr> <tr><td>verifyText</td><td>//h2</td><td>Downloads</td></tr> </table> Rendered as a table in a browser this would look like the following: open assertTitle verifyText /download/ Downloads Downloads //h2 The Selenese HTML syntax can be used to write and run tests without requiring knowledge of a programming language. Test suites can also be maintained when using Selenium-RC.html" >Test Save</a></td></tr> </table> </body> </html> A file similar to this would allow running the tests all at once./SearchValues. 3.Selenium Documentation. With a basic knowledge of selenese and Selenium-IDE you can quickly produce and run testcases.html" >Test Searching for Values</a></td></tr> <tr><td><a href= ". When using Selenium-IDE. Release 1. An HTML table defines a list of tests where each row defines the filesystem path to each test. An example tells it all./Login.11 Commonly Used Selenium Commands To conclude our introduction of Selenium. 3.Priority 1</title> </head> <body> <table> <tr><td><b>Suite Of Tests</b></td></tr> <tr><td><a href= ". Since the whole reason for using Sel-RC is to make use of programming logic for your testing this usually isn’t a problem. Test Suites 23 . 3. This is done via programming and can be done a number of ways./SaveValues.10 Test Suites A test suite is a collection of tests. Commonly Junit is used to maintain a test suite if one is using Selenium-RC with Java. test suites also can be defined using a simple HTML file.html" >Login</a></td></tr> <tr><td><a href= ". you may want to check many attributes of a page without aborting the test case on the first failure as this will allow you to review all failures on the page and take the appropriate action. specific text is somewhere on the page? 3. specific text is at a specific location on the page? For example. Release 1. verifyTextPresent verifies expected text is somewhere on the page.12 Verifying Page Elements Verifying UI elements on a web page is probably the most common feature of your automated tests. Selenium-IDE .0 open opens a page using a URL. 1. It is important that you understand these different methods because these methods define what you are actually testing. If you’re not on the correct page.Selenium Documentation. however. Called automatically when clickAndWait is used. On the other hand. and start each group with an “assert” followed by one or more “verify” test commands. is present on the page. Selenese allows multiple ways of checking for UI elements. verifyTable verifies a table’s expected contents. an element is present somewhere on the page? 2. An example follows: 24 Chapter 3. 3. and optionally waits for a new page to load. if you are testing a text heading. The best use of this feature is to logically group your test commands.. you’ll probably want to abort your test case so that you can investigate the cause and fix the issue(s) promptly. If. you are testing for the existence of an image on the home page. as defined by its HTML tag. is present on the page. then you only want to test that an image (as opposed to the specific image file) exists somewhere on the page. There’s very little point checking that the first paragraph on the page is the correct one if your test has already failed when checking that the browser is displaying the expected page. verifyText verifies expected text and it’s corresponding HTML tag are present on the page. and the web designers frequently change the specific image file along with its position on the page. click/clickAndWait performs a click operation. waitForElementPresent pauses execution until an expected UI element.13 Assertion or Verification? Choosing between “assert” and “verify” comes down to convenience and management of failures. verifyElementPresent verifies an expected UI element. as defined by its HTML tag. For example. Effectively an “assert” will fail the test and abort the current test case. waitForPageToLoad pauses execution until an expected new page loads. verifyTitle/assertTitle verifies an expected page title. 3. the text and its position at the top of the page are probably relevant for your test. will you test that. whereas a “verify” will fail the test and continue to run the test case.. and that it follows a <div> tag and a <p> tag. It takes a single argument–the text pattern to be verified. Only if this passes will the following command run and “verify” that the text is present in the expected location.2. Assertion or Verification? 25 . and verify. paragraphs. You can check the existence of links.2. is present on the page.2 1. specified by the existence of an <img> HTML tag. Use verifyTextPresent when you are interested in only the text itself being present on the page.1 verifyTextPresent The command verifyTextPresent is used to verify specific text exists somewhere on the page. Here are a few more examples. divisions <div>. 3. only the HTML tag. The test case then “asserts” the first column in the second row of the first table contains the expected value. locators are explained in the next section. Release 1. 2008 1. Locators are explained in the next section. Do not use this when you also need to test where the text occurs on the page.1 1. Command verifyElementPresent Target //div/p/img Value This command verifies that an image.0 Command open assertTitle verifyText assertTable verifyTable verifyTable Target /download/ Downloads //h2 1.2. For example: Command verifyTextPresent Target Marketing Analysis Value This would cause Selenium to search for. Again. and only if this passed will the remaining cells in that row be “verified”.. The first (and only) parameter is a locator for telling the Selenese command how to find the element.3 Value Downloads Selenium IDE June 3. rather then its content.Selenium Documentation.2. This verification does not check the text. etc. One common use is to check for the presence of an image.13.13. that the text string “Marketing Analysis” appears somewhere on the page currently being tested. 3. verifyElementPresent can be used to check the existence of any HTML tag within the page.13. 3. Selenium-IDE . then the first element with a name attribute matching the location will be used. a target is required. but also more explicit. Locating by Id This type of locator is more limited than the identifier locator type. 3. the identifier= in the first three examples above is not necessary. the first element with the id attribute value matching the location will be used. verifyText must use a locator. For instance.14. The various locator types are explained below with examples for each.14 Locating Elements For many Selenium commands. you can verify that specific text appears at a specific location on the page relative to other UI components on the page. and consists of the location strategy followed by the location in the format locatorType=location.Selenium Documentation. If no element has a matching id attribute. The locator type can be omitted in many cases.13. This target identifies an element in the content of the web application.3 verifyText Use verifyText when both the text and its UI element must be tested.1 Locating by Identifier This is probably the most common method of locating elements and is the catch-all default when no recognised locator type is used. If you choose an XPath or DOM locator. 26 Chapter 3. Use this when you know an element’s id attribute. Release 1. With this strategy. Command verifyText Target //table/tr/td/div/p Value This is my text and it occurs right after the div inside the table.0 3. 3. your page source could have id and name attributes as follows: 1 2 3 4 5 6 7 8 9 <html> <body> <form id= "loginForm" > <input name= "username" type= "text" /> <input name= "password" type= "password" /> <input name= "continue" type= "submit" value= "Login" /> </form> </body> <html> The following locator strategies would return the elements from the HTML snippet above indicated by line number: • identifier=loginForm (3) • identifier=password (4) • identifier=continue (5) • continue (5) Since the identifier type of locator is the default. As HTML can be an implementation of XML (XHTML). becomes very important. If multiple elements have the same value for a name attribute. The default filter type is value (matching the value attribute). the test will still pass. then you can use filters to further refine your location strategy. Selenium users can leverage this powerful language to target elements in their web applications.14. Locating Elements 27 . You may or may not want to also test whether the page structure changes. testing via id and name attributes. XPath extends beyond (as well as supporting) the simple methods of locating by id 3. the three types of locators above allow Selenium to test a UI element independent of its location on the page. In the case where web designers frequently alter the page. or really via any HTML property.Selenium Documentation. Release 1. Locating by XPath XPath is the language used for locating nodes in an XML document. 1 2 3 4 5 6 7 8 9 10 <html> <body> <form id= "loginForm" > <input name= "username" <input name= "password" <input name= "continue" <input name= "continue" </form> </body> <html> type= type= type= "password" /> "submit" value= "Login" /> "button" value= "Clear" /> • name=username (4) • name=continue value=Clear (7) • name=continue Clear (7) • name=continue type=button (7) Note: Unlike some types of XPath and DOM locators. but its functionality must be regression tested. So if the page structure and organization is altered. First input element with attribute named ‘name’ and the value ‘username’ • //form[@id=’loginForm’]/input[1] (4) . Release 1.Selenium Documentation. By finding a nearby element with an id or name attribute (ideally a parent element) you can locate your target element based on the relationship.0 or name attributes.First form element in the HTML • xpath=//form[@id=’loginForm’] (3) . This is much less likely to change and can make your tests more robust. but in order to learn more. the following references are recommended: • W3Schools XPath Tutorial • W3C XPath Recommendation 28 Chapter 3.First input child element of the form element with attribute named ‘id’ and the value ‘loginForm’ • //input[@name=’continue’][@type=’button’] (7) . it is not necessary to include the xpath= label when specifying an XPath locator. Since only xpath locators start with “//”.) .Absolute path (would break if the HTML was changed only slightly) • //form[1] ) .Fourth input child element of the form element with attribute named ‘id’ and value ‘loginForm’ These examples cover some basics. Absolute XPaths contain the location of all elements from the root (html) and as a result are likely to fail with only the slightest adjustment to the application. and opens up all sorts of new possibilities such as locating the third checkbox on the page. One of the main reasons for using XPath is when you don’t have a suitable id or name attribute for the element you wish to locate. or relative to an element that does have an id or name attribute. 1 2 3 4 5 6 7 8 9 10 <html> <body> <form id= "loginForm" > <input name= "username" <input name= "password" <input name= "continue" <input name= "continue" </form> </body> <html> type= type= type= "password" /> "submit" value= "Login" /> "button" value= "Clear" /> • xpath=/html/body/form[1] (3) . You can use XPath to either locate the element in absolute terms (not advised). Selenium-IDE . then the first match will be used. Since only dom locators start with “document”.XPath suggestions are just one of the many powerful features of this very useful add-on. Locating Hyperlinks by Link Text This is a simple method of locating a hyperlink in your web page by using the text of the link. it is not necessary to include the dom= label when specifying a DOM locator.Selenium Documentation. 1 2 3 4 5 6 7 <html> <body> <p>Are you sure you want to do this?</p> <a href= "continue. If two links with the same text are present.forms[0] (3) 3. 1 2 3 4 5 6 7 8 9 10 <html> <body> <form id= "loginForm" > <input name= "username" <input name= "password" <input name= "continue" <input name= "continue" </form> </body> <html> type= type= type= "password" /> "submit" value= "Login" /> "button" value= "Clear" /> • dom=document.with interactive examples. There are also a couple of very useful Firefox Add-ons that can assist in discovering the XPath of an element: • XPath Checker . which can be simply the element’s location using the hierarchical dotted notation.14.0 • XPath Tutorial . • Firebug . Release 1.html" >Continue</a> <a href= "cancel.forms[’loginForm’] (3) • dom=document.getElementById(’loginForm’) (3) • dom=document.html" >Cancel</a> </body> <html> • link=Continue (4) • link=Cancel (5) Locating by DOM The Document Object Model represents an HTML document and can be accessed using JavaScript. This location strategy takes JavaScript that evaluates to an element on the page. Locating Elements 29 .suggests XPath and can be used to test XPath results. Note: Most experienced Selenium users recommend CSS as their locating strategy of choice as it’s considerably faster than XPath and can find the most complicated objects in an intrinsic HTML document.0 • document.passfield (5) • css=#loginForm input[ <input class= "required" name= "username" type= "text" /> <input class= "required passfield" name= "password" type= "password" /> <input name= "continue" type= "submit" value= "Login" /> <input name= "continue" type= "button" value= "Clear" /> </form> </body> <html> • css=form#loginForm (3) • css=input[name="username"] (4) • css=input.forms[0]. CSS uses Selectors for binding style properties to elements in the document.elements[’username’] (4) • document. Release 1.Selenium Documentation.elements[0] (4) • document.forms[0]. You’ll find additional references there. See Locating by Identifier. These Selectors can be used by Selenium as another locating strategy.username (4) • document.forms[0]. Implicit Locators You can choose to omit the locator type in the following situations: • Locators without an explicitly defined locator strategy will default to using the identifier locator strategy. Selenium-IDE .forms[0]. A good reference exists on W3Schools. Locating by CSS CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents. the best place to go is the W3C publication.required[type="text"] (4) • css=input. [ ] (character class) which translates to “match any single character found inside the square brackets. Below is an example of two commands that use globbing patterns. verifyAlert. Command click verifyTitle Target link=glob:Film*Television Department glob:*Film*Television* Value The actual title of the page reached by clicking on the link was “De Anza Film And Television Department . and verifyPrompt.. Only two special characters are supported in the Selenium implementation: * which translates to “match anything. because globbing patterns are the default. However.15. via the use of special characters. The glob pattern’s asterisk will match “anything or nothing” between the word “Film” and the word “Television”. by using a pattern rather than the exact text. However.1 Globbing Patterns Most people are familiar with globbing as it is utilized in filename expansion at a DOS or Unix/Linux command line such as ls *.15 Matching Text Patterns Like locators. By using a pattern rather than the exact text.” A dash (hyphen) can be used as a shorthand to specify a range of characters (which are contiguous in the ASCII character set). the click command will work even if the link text is changed to “Film & Television Department” or “Film and Television Department”. nothing. Using a pattern for both a link and a simple test that the link worked (such as the verifyTitle above does) can greatly reduce the maintenance for such test cases. There are three types of patterns: globbing. the verifyTitle will pass as long as the two words “Film” and “Television” appear (in that order) anywhere in the page’s title. globbing is used to display all the files ending with a . you can prefix the pattern with a glob: label.c. what text is expected rather than having to specify that text exactly. link locators can utilize a pattern. Globbing is fairly limited. • Locators starting with “document” will use the DOM locator strategy. verifyTitle.” the test would still pass. For example. 3. or many characters. you can also omit the label and specify just the pattern itself. A few examples will make the functionality of a character class clear: [aeiou] matches any lowercase vowel [0-9] matches any digit [a-zA-Z0-9] matches any alphanumeric character In most other contexts. Matching Text Patterns 31 . if the page’s owner should shorten the title to just “Film & Television Department. the ?.” i. verifyText. Patterns allow you to describe. Selenium globbing patterns only support the asterisk and character class. The actual link text on the page being tested was “Film/Television Department”. globbing includes a third special character. regular expressions. assertConfirmation. Release 1. And as has been mentioned above. See Locating by XPath. See Locating by DOM 3.15. To specify a globbing pattern parameter for a Selenese command. In this case.Menu”. and exact. Examples of commands which require patterns are verifyTextPresent. 3.0 • Locators starting with “//” will use the XPath locator strategy.e. patterns are a type of parameter frequently required by Selenese commands. a single character.c extension that exist in the current directory.Selenium Documentation. 5} | () MATCH any single character character class: any single character that appears inside the brackets quantifier: 0 or more of the preceding character (or group) quantifier: 1 or more of the preceding character (or group) quantifier: 0 or 1 of the preceding character (or group) quantifier: 1 through 5 of the preceding character (or group) alternation: the character/group on the left or the character/group on the right grouping: often used with alternation and/or quantifier Regular expression patterns in Selenese need to be prefixed with either regexp: or regexpi:.2}:[0-9]{2} [ap]m Value Let’s examine the regular expression above one part at a time: Sunrise: * [0-9]{1. Alaska contains info on the sunrise time: Command open verifyTextPresent Target. “anything or nothing. Selenium-IDE .Selenium Documentation. The first one uses what is probably the most commonly used regular expression pattern–.* instead of just *). For example. including the Linux/Unix command-line utilities grep. The only differences are the prefix (regexp: instead of glob:) and the “anything or nothing” pattern (. and awk. the latter is case-insensitive. regular expression patterns allow a user to perform many tasks that would be very difficult otherwise.yahoo. [] * + ? {1. The more complex example below tests that the Yahoo! Weather page for Anchorage. Command click verifyTitle Target link=regexp:Film.*Television Department regexp:. Whereas Selenese globbing patterns support only the * and [ ] (character class) features.” It is the equivalent of the one-character globbing pattern * (a single asterisk).com/forecast/USAK0012.* Value The example above is functionally equivalent to the earlier example that used globbing patterns for this same test.0 Regular Expression Patterns Regular expression patterns are the most powerful of the three types of patterns that Selenese supports. Regular expressions are also supported by most high-level programming languages. many text editors. This two-character sequence can be translated as “0 or more occurrences of any character” or more simply.html regexp:Sunrise: *[0-9]{1. and a host of tools. Selenese regular expression patterns offer the same wide array of special characters that exist in JavaScript.*Film. A few examples will help clarify how regular expression patterns can be used with Selenese commands. sed. Release 1.*Television. Below are a subset of those special characters: PATTERN . In Selenese. suppose your test needed to ensure that a particular table cell contained nothing but a number. The former is case-sensitive.* (“dot star”). regexp: [0-9]+ is a simple pattern that will match a decimal number of any length. Be aware. It uses no special characters at all. one command after another. while the AndWait alternative (e. causing Selenium to raise a timeout exception. if you use an AndWait command for an action that does not trigger a navigation/refresh. The best approach would be to wait for the needed element in a dynamic period and then continue the execution as soon as the element is found. This happens because Selenium will reach the AndWait‘s timeout without seeing any navigation or refresh being made. if there was an earlier select option labeled “Real Numbers. 3. the exact: prefix could be used to create an exact pattern as shown below: select //select exact:Real * But the same effect could be achieved via escaping the asterisk in a regular expression pattern: select //select regexp:Real \* It’s rather unlikely that most testers will ever need to look for an asterisk or a set of square brackets with characters inside them (the character class for globbing patterns). For example. This is done using waitFor commands.Selenium Documentation. 3.” it would be the option selected rather than the “Real *” option. globbing patterns and regular expression patterns are sufficient for the vast majority of us. The AndWait alternative is always used when the action causes the browser to navigate to another page or reload the present one. load or other uncontrolled factors of the moment. clickAndWait) tells Selenium to wait for the page to load after the action has been done.17 The waitFor Commands in AJAX applications In AJAX driven web applications. checking for the desired condition every second and continuing to the next command in the script as soon as the condition is met. as waitForElementPresent or waitForVisible.g. it simply runs in sequence.0 Exact Patterns The exact type of Selenium pattern is of marginal usefulness. The asterisk in the glob:Real * pattern will match anything or nothing. which wait dynamically. the following code might work or it might not. 3. the exact pattern would be one way to do that. So. data is retrieved from server without refreshing the page. Using andWait commands will not work as the page is not actually refreshed. So. The “AndWait” Commands 33 . 3. click) will do the action and continue with the following command as fast as it can.18 Sequence of Evaluation and Flow Control When a script runs. Release 1. Thus. Pausing the test execution for a certain period of time is also not a good approach as web element might appear later or earlier than the stipulated period depending on the system’s responsiveness.16.16 The “AndWait” Commands The difference between a command and its AndWait alternative is that the regular command (e. leading to test failures.g. if you wanted to select an item labeled “Real *” from a dropdown. select //select glob:Real * In order to ensure that the “Real *” item would be selected. if you needed to look for an actual asterisk character (which is special for both globbing and regular expression patterns). your test will fail. 1 storeElementPresent This corresponds to verifyElementPresent. Many useful tests can be conducted without flow control. programming logic is often needed. Here are a couple more commonly used store commands. consider a JavaScript snippet or the goto_sel_ide. enclose the variable in curly brackets ({}) and precede it with a dollar sign like this. It takes two parameters.) or iteration (for. etc. 3. 2. If this is your case. 3. The plain store command is the most basic of the many store commands and can be used to simply store a constant value in a selenium variable. some organizations prefer to run their scripts from SeleniumIDE whenever possible (for instance. when they have many junior-level people running tests for them. for a functional test of dynamic content. A Selenium variable may also be used within a locator expression. you’ll want to use the stored value of your variable. does not support condition statements (if-else. Command verifyText Target //div/p Value ${userName} A common use of variables is for storing input for an input field. To access the value of a variable. Run the script using Selenium-RC and a client library such as Java or PHP to utilize the programming language’s flow control features. possibly involving multiple pages. Selenium variables can be used to store values passed to your test program from the command-line. It simply stores a boolean value–“true” or “false”–depending on whether the UI element is found. When flow control is needed. from another program. However. Release 1. Also. or when programming skills are lacking). An equivalent store command exists for each verify and assert command. while.js extension.19. Install the goto_sel_ide. However. Command store Target paul@mysite. when combined with a data-driven test design (discussed in a later section). Most testers will export the test script into a programming language file that uses the Selenium-RC API (see the Selenium-IDE chapter). the text value to be stored and a selenium variable. etc. Selenium-IDE .Selenium Documentation. Use the standard variable naming conventions of only alphanumeric characters when choosing a name for your variable. Command type Target id=login Value ${userName} Selenium variables can be used in either the first or second parameter and are interpreted by Selenium prior to any other operations performed by the command.org Value userName Later in your script. by itself. there are three options: 1. 34 Chapter 3.). 3. Run a small JavaScript snippet from within the script using the storeEval command.js extension.19 Store Commands and Selenium Variables You can use Selenium variables to store constants at the beginning of a script.0 Selenese. or from a file. even when the parameter is not specified to be of type script. 3. and waitForEval. These parameters require no special syntax. All variables created in your test case are stored in a JavaScript associative array.3 storeEval This command takes a script as its first parameter.toLowerCase() Value name uc lc JavaScript Usage with Non-Script Parameters JavaScript can also be used to help generate values for parameters. StoreEval allows the test to store the result of running the script in a variable. is stored in the variable. Whenever you wish to access or manipulate a variable within a JavaScript snippet.20. in this case. Embedding JavaScript within Selenese is covered in the next section.20. It uses a locater to identify specific page text. you must refer to it as storedVars[’yourVariableName’]. An associative array has string indexes rather than sequential numeric indexes. as in javascript {*yourCodeHere*}. Release 1. StoreText can be used to extract text from the page being tested. 3. verifyEval. The text.Selenium Documentation. In most cases. storeEval.0 3. However. A Selenium-IDE user would simply place a snippet of JavaScript code into the appropriate field. special syntax is required–the JavaScript snippet must be enclosed inside curly braces and preceded by the label javascript.toUpperCase() storedVars[’name’]. JavaScript and Selenese Parameters 35 . if found. Below is an example in which the type command’s second parameter value is generated via JavaScript code using this special syntax: 3. you’ll want to access and/or manipulate a test case variable inside the JavaScript snippet used as a Selenese parameter. 3. Command store storeEval storeEval Target Edith Wharton storedVars[’name’]. in this case the JavaScript String object’s toUpperCase method and toLowerCase method.19.20 JavaScript and Selenese Parameters JavaScript can be used with two types of Selenese parameters: script and non-script (usually expressions). normally the Target field (because a script parameter is normally the first or only parameter).1 JavaScript Usage with Script Parameters Several Selenese commands specify a script parameter including assertEval..2 storeText StoreText corresponds to verifyText.19. The associative array containing your test case’s variables is named storedVars. echo statements can be used to print the contents of Selenium variables. Popups. } } function show_alert(){ alert( "I’m blocking!" ).0 Command store type Target league of nations q Value searchString javascript{storedVars[’searchString’].open( "newWindow.nodeValue=resultText. Selenium-IDE ." ).The Selenese Print Command Selenese has a simple command that allows you to print text to your test’s output. and Multiple Windows Suppose that you are testing a page that looks like this.childNodes[0]. output(response).html" ." ).21 echo . output( "Alert is gone. if (confirmation==true){ output( "Confirmed. } else{ output( "Rejected!" ). "Selenium" ).windowName). Finally. These notes also can be used to provide context within your test result reports.toUpperCase()} 3." ). } function show_confirm(){ var confirmation=confirm( "Chose an option. Release 1. Command echo echo Target Testing page footer now. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <!DOCTYPE HTML> <html> <head> <script type= "text/javascript" > function output(resultText){ document.22 Alerts. Username is ${userName} Value 3. which can be useful for finding where a defect exists on a page in the event your test finds a problem. } </script> </head> <body> 36 Chapter 3.Selenium Documentation.getElementById( ’output’ ). This is useful for providing informational progress notes in your test which display on the console as your test is running. } function open_window(windowName){ window. } function show_prompt(){ var response = prompt( "What’s the best web QA tool?" . Now run through the same steps with Selenium IDE recording. Selenium can cover JavaScript pop-ups. with false halting the test. just because you cannot see the pop-up doesn’t mean you don’t have do deal with it. To handle a pop-up.. as well as moving focus to newly opened popup windows. If you fail to assert the presence of a pop-up your next command will be blocked and you will get an error similar to the following [error] Error: There was an unexpected Confirmation! [Chose an option.22. 3. This is because the function calls are actually being overridden at runtime by Selenium’s own JavaScript. it is helpful to understand the commonality between.22. Release 1. If you remove that step and replay the test you will get the following error [error] Error: There was an unexpected Alert! [I’m blocking!]. This will return true or false.1 Alerts Let’s start with asserts because they are the simplest pop-up to handle. and verify the text is added after you close the alert.0 34 35 36 37 38 39 40 41 42 43 44 45 <input type= "button" id= <input type= "button" id= <input type= "button" id= <a href= "newWindow. To begin. But before we begin covering alerts/confirms/prompts in individual detail.Selenium Documentation. Popups. Alerts. You’ll notice that after you close the alert the text “Alert is gone. Alerts. Your test will look something like this: Command open click assertAlert verifyTextPresent Target / btnAlert I’m blocking Alert is gone.” But this is Selenium-IDE handling and closing the alert for you. and Multiple Windows 37 . However. Value You may be thinking “Thats odd. you can use assertAlertPresent. If you just want to assert that an alert is present but either don’t know or don’t care what text it contains. You must include an assertion of the alert to acknowledge it’s presence. JavaScript pop-ups will not appear.” is displayed on the page. you must call it’s assertFoo(pattern) function.] 3. open the HTML sample above in a browser and click on the “Show alert” button. I never tried to assert that alert. Fortunately. You may notice that you cannot replay this test. To set a breakpoint. by default Selenium will select OK when a confirmation pops up. That will prevent you from having to manually logout each time you rerun your test case. 3. and from the context menu select Toggle Breakpoint. 3. Your test may look something like this: Command open click chooseCancelOnNextConfirmation assertConfirmation verifyTextPresent Target / btnConfirm Choose and option. Then click the Run button to run your test case from the beginning up to the breakpoint. Release 1.1 Breakpoints and Startpoints The Sel-IDE supports the setting of breakpoints and the ability to start and stop the running of a test case. Selenium-IDE . suppose your test case first logs into the website and then performs a series of tests and you are trying to debug one of those tests. from any point within the test case. That is. with assertConfirmation and assertConfirmationPresent offering the same characteristics as their alert counterparts. because Selenium complains that there is an unhandled confirmation. This is a normal part of test case development. You can login once. To set a startpoint. then run your test case from a startpoint placed after the login portion of your test case. but you need to keep rerunning your tests as you are developing them. 38 Chapter 3.0 Confirmations Confirmations behave in much the same way as alerts.Selenium Documentation. Try recording clicking on the “Show confirm box” button in the sample page. select a command. right-click.23 Debugging Debugging means finding and fixing errors in your test case. It is also sometimes useful to run a test case from somewhere in the middle to the end of the test case or up to a breakpoint that follows the starting point. select a command. right-click. If this is new to you. you only need to login once. then assert the output text. To do this. one can run up to a specific command in the middle of the test case and inspect how the test case behaves at that point. It can be reset by calling chooseOkOnNextConfirmation.23. set a breakpoint on the command just before the one to be examined. Selenium can’t know that you’re cancelling before you open a confirmation) Simply switch these two commands and your test will run fine. but click on the “Cancel” button in the popup. For example. This is because the order of events Selenium-IDE records causes the click and chooseCancelOnNextConfirmation to be put in the wrong order (it makes sense if you think about it. We won’t teach debugging here as most new users to Selenium will already have some basic experience with debugging. However. and from the context menu select Set/Clear Start Point. Then click the Run button to execute the test case beginning at that startpoint. However. Rejected Value The chooseCancelOnNextConfirmation function tells Selenium that all following confirmation should return false. we recommend you ask one of the developers in your organization. 23. Click the Find button. Simply right-click the webpage and select ‘View->Page Source. The HTML opens in a separate window. This feature can be very useful for learning more about locators. 3. with highlighting on the portion representing your selection. Note that the first 3. when debugging a test case. From Table view. the separate HTML window will contain just a small amount of source. This locator assistance is presented on the Selenium-IDE window as a drop-down list accessible at the right end of the Target field (only when the Target field contains a recorded locator-type argument).5 Locator Assistance Whenever Selenium-IDE records a locator-type argument. and certain assert and verify commands. and is often needed to help one build a different type of locator than the type that was recorded. click. Release 1.23.23.Selenium Documentation. Repeatedly select the Step button. 3. select just that portion of the webpage for which you want to see the source. clickAndWait. It can be used with any command that identifies a UI element on a webpage.e. among others. i.3 Find Button The Find button is used to see which UI element on the currently displayed webpage (in the browser) is used in the currently selected Selenium command. follow these steps: 1. In this case.4 Page Source for Debugging Often. Below is a snapshot showing the contents of this drop-down for one command. you simply must look at the page source (the HTML for the webpage you’re trying to test) to determine a problem. Immediately pause the executing test case with the Pause button. Then rightclick the webpage and select View Selection Source. type. Debugging 39 .0 3.2 Stepping Through a Testcase To execute a test case one command at a time (“step through” it). 1.23. Start the test case running with the Run button from the toolbar. 1. Now look on the webpage: There should be a bright green rectangle enclosing the element specified by the locator parameter. 3. Firefox makes this easy. This is useful when building a locator for a command’s first parameter (see the section on locators in the Selenium Commands chapter). Use its Search feature (Edit=>Find) to search for a keyword to find the HTML for the UI element you’re trying to test. Alternatively. it stores additional information which allows the user to view other possible locator-type arguments that could be used instead. select any command that has a locator parameter.23. Users who want to create or modify a test suite by adding pre-existing test cases must manually edit a test suite file. In the latter case. Each cell of each row in the <tbody> section contains a link to a test case. The test suite pane can be manually opened or closed via selecting a small dot halfway down the right edge of the pane (which is the left edge of the entire Selenium-IDE window if the pane is closed). Selenium-IDE does not yet support loading pre-existing test cases into a test suite. Selenium-IDE . Release 1. The test suite pane will be automatically opened when an existing test suite is opened or when the user selects the New Test Case item from the File menu.24 Writing a Test Suite A test suite is a collection of test cases which is displayed in the leftmost pane in the IDE. charset=UTF-8" > <title>Sample Selenium Test Suite</title> </head> 40 Chapter 3. The example below is of a test suite containing four test cases: <html> <head> <meta http-equiv= "Content-Type" content= "text/html.0 column of the drop-down provides alternative locators. the new test case will appear immediately below the previous test case. 3. whereas the second column indicates the type of each alternative. A test suite file is an HTML file containing a one-column table.Selenium Documentation. However. User Extensions 41 .js. at the time of this writing. Often this is in the form of customized commands although this extensibility is not limited to additional commands./d.25. a bug prevents Windows users from being able to place the test cases elsewhere than with the test suite that invokes them./b. you must close and reopen Selenium-IDE in order for the extensions file to be read./c. put the pathname to its location on your computer in the Selenium Core extensions field of Selenium-IDE’s Options=>Options=>General tab. Perhaps the most popular of all Selenium-IDE extensions is one which provides flow control in the form of while loops and primitive conditionals. that is indeed the case. There are a number of useful extensions created by users.Selenium Documentation. And on Mac OS and Linux systems. After selecting the OK button. Any change you make to an extension will also require you to close and reopen SeleniumIDE. 3. 3./a. This extension is the goto_sel_ide.html" >B Links</a></td></tr> <tr><td><a href= ". For an example of how to use the functionality provided by this extension. Release 1.html" >D Links</a></td></tr> </tbody> </table> </body> </html> Note: Test case files should not have to be co-located with the test suite file that invokes them. look at the page created by its author.html" >A Links</a></td></tr> <tr><td><a href= ". IMPORTANT: THIS SECTION IS OUT OF DATE–WE WILL BE REVISING THIS SOON.html" >C Links</a></td></tr> <tr><td><a href= ".0 <body> <table cellpadding= "1" cellspacing= "1" border= "1" > <thead> <tr><td>Test Cases for De Anza A-Z Directory Links</td></tr> </thead> <tbody> <tr><td><a href= ". To install this extension.25 User Extensions User extensions are JavaScript files that allow one to create his or her own customizations and features to add additional functionality. This is under the Options=>Options=>Format tab. you will be using with Selenium-RC for developing your test programs. Note: At the time of this writing. allows you to select a language for saving and displaying the test case. See issue 1010. tests developed with Selenium-IDE can be run against other browsers. 3. 3. i.0 Information on writing your own extensions can be found near the bottom of the Selenium Reference document. PHP. The -htmlSuite command-line option is the particular feature of interest. error loading test case: no command found You’ve used File=>Open to try to open a test suite file. 3. for more information.27 Executing Selenium-IDE Tests on Different Browsers While Selenium-IDE can only run tests against Firefox.26 Format Format. However the author has altered the C# format in a limited manner and it has worked well. Java. this feature is used to translate your test case into a programming language. under the Options menu. This topic is covered in the Run Selenese tests section on Selenium-RC chapter. program code supporting your test is generated for you by Selenium-IDE. Your test case will be translated into a series of functions in the language you choose. If you will be using Selenium-RC to run your test cases. If you are able to reproduce this reliably then please provide details so that we can work on a fix. this feature is not yet supported by the Selenium developers. This message can be occasionally displayed in the Table tab when Selenium IDE is launched.e. Selenium-IDE . An enhancement request has been raised to improve this error message. Essentially. 42 Chapter 3. Then simply save the test case using File=>Save. Also. Use File=>Open Test Suite instead.28 Troubleshooting Below is a list of image/explanation pairs which describe frequent sources of problems with SeleniumIDE: Table view is not available with this format. note that if the generated code does not suit your needs. using a simple command-line interface that invokes the Selenium-RC server. Each supported language has configuration settings which are editable. Select the language. See issue 1008. you can alter it by editing a configuration file which defines the generation process. Release 1. The workaround is to close and reopen Selenium IDE.Selenium Documentation. The default is HTML. . make sure that your actual test case files have the . Release 1.init]” nresult: “0x80520012 (NS_ERROR_FILE_NOT_FOUND)” location: “JS frame :: chrome://selenium-ide/content/fileutils.js :: anonymous :: line 48” data: no] One of the test cases in your test suite cannot be found. Also. Make sure that the test case is indeed located where the test suite indicates it is located. and the second required parameter (if one exists) must go in the Value field. See issue 1011. This is sometimes due to putting the variable in the Value field when it should be in the Target field or vice versa. the first required parameter must go in the Target field.html extension both in their filenames. it indicates that you haven’t actually created the variable whose value you’re trying to access. In the example above. Whenever your attempt to use variable substitution fails as is the case for the open command above. For any Selenese command.e.0 This type of error may indicate a timing problem. investigate using an appropriate waitFor* or *AndWait command before the failing command. Selenium-IDE is very space-sensitive! An extra space before or after a command will cause it to be unrecognizable. and in the test suite file where they are referenced. “Component returned failure code: 0x80520012 (NS_ERROR_FILE_NOT_FOUND) [nsIFileInputStream..28.. the two parameters for the store command have been erroneously placed in the reverse order of what is required. Try putting a pause 5000 before the command to determine whether the problem is indeed related to timing. the element specified by a locator in your command wasn’t fully loaded when the command was executed. 3. If so. An enhancement request has been raised to improve this error message. i. error loading test case: [Exception.Selenium Documentation. Troubleshooting 43 . In the example above. Release 1. Selenium-IDE is correct that the actual value does not match the value specified in such test cases.0 This defect has been raised. Thus. This defect has been raised. Be sure you have specified the proper pathname to the extensions file via Options=>Options=>General in the Selenium Core extensions field. See issue 1012. Selenium-IDE . Selenium-IDE must be restarted after any change to either an extensions file or to the contents of the Selenium Core extensions field. Selenium-IDE is correct to generate an error. 44 Chapter 3. The problem is that the log file error messages collapse a series of two or more spaces into a single space. which is confusing. but is misleading in the nature of the error. This type of error message makes it appear that Selenium-IDE has generated a failure where there is none. See issue 1013. Also. Your extension file’s contents have not been read by Selenium-IDE. However. note that the parameter for verifyTitle has two spaces between the words “Selenium” and “web” The page’s actual title has only one space between these words.Selenium Documentation. 0 AND WEBDRIVER As you can see in the Brief History of The Selenium Project The Selenium developers are working towards a Selenium 2. Now. The primary new feature will be the integration of the WebDriver API into Selenium 1.example. which will help make your tests easier to read and maintain. as opposed to the proxy server with Selenium-RC.selenium.0 release.selenium. 4. we’ll refer to that as $WEBDRIVER_HOME. { public class Selenium2Example 45 .openqa.selenium. which searches for the term “Cheese” on Google and then outputs the result page’s title to the console. This “Getting Started” guide introduces you to WebDriver’s API and helps get you started becoming familiar with it. org. org.selenium.1 Java package org. It aims to provide a friendly API that’s easy to explore and understand.CHAPTER FOUR SELENIUM 2. import import import import org.openqa.openqa. so it can be used equally well in a unit testing or from a plain old “main” method. An easy way to get started is this example. and you usually don’t need to remember to start any additional processes or run any installers before using it. and in particular to verify that they work as expected. 4.1 The 5 Minute Getting Started Guide WebDriver is a tool for automating testing web applications.FirefoxDriver. This will address a number of limitations along with providing an alternative programming interface.WebElement.firefox. Start by Downloading the latest binaries and unpack them into a directory. org. You’re now ready to write some code.selenium.openqa. open your favourite IDE and: • Start a new project in your favourite IDE/editor • Add a reference to all the libraries in $WEBDRIVER_HOME You can see that WebDriver acts just as a normal library does: it’s entirely self-contained.WebDriver.openqa. The goal is to develop an object-oriented API that provides additional support for a larger number of browsers along with improved support for modern advanced web-app testing problems.1. It’s not tied to any particular test framework.By. From now on. out.2 C# using OpenQA.submit().0 public static void main(String[] args) { // Create a new instance of the Firefox driver // Notice that the remainder of the code relies on the interface.sendKeys( "Cheese!" ).Console.Navigate(). class GoogleSuggest { static void Main(string[] args) { IWebDriver driver = new FirefoxDriver().get( ". System. When you run this program. driver.getTitle()).google.Quit().Firefox.com/" ).println( "Page title is: " + driver. you’ll see the list of suggestions being printed to the console.WriteLine( "Page title is: " + driver. Selenium 2.FindElement(By. WebDriver will find the form for us from the element element.google. you shall use a page that requires Javascript to work properly. such as Google Suggest. // not the implementation. // Enter something to search for element.Name( "q" )). Release 1. You will also be using the Firefox Driver. // Check the title of the page System.findElement(By. IWebElement query = driver. //Close the browser driver. query. Make sure that Firefox is installed on your machine and is in the normal location for your OS.1. //Notice navigation is slightly different than the Java version //This is because ’get’ is a keyword in C# driver. } } 4. } } In this next example.GoToUrl( ". // Find the text input element by its name WebElement element = driver. // Now submit the form. That’s all 46 Chapter 4.Selenium Documentation.SendKeys( "Cheese" ).0 and WebDriver .name( "q" )). using OpenQA. // And now use this to visit Google driver.quit().com" ).Selenium. WebDriver driver = new FirefoxDriver().Selenium.Title). These are: Name of driver HtmlUnit Driver Firefox Driver Internet Explorer Driver Chrome Driver Available on which OS? All All Windows All Class to instantiate org.selenium.2. let’s start with the HtmlUnit Driver: WebDriver driver = new HtmlUnitDriver().openqa.2. the “onload” event has fired) before returning control to your test or script.com" ). which means that you can’t watch what’s happening. Next Steps For Using WebDriver 47 . This can be measured and quantified.2 Navigating The first thing you’ll want to do with WebDriver is navigate to a page.openqa. you may wish to choose a driver such as the Firefox Driver. For sheer speed.htmlunit. this idea is referred to as “safety”.HtmlUnitDriver org. However.2 Next Steps For Using WebDriver 4. WebDriver. In the Next Steps section you will learn more about how to use WebDriver for things such as navigating forward and backward in your browser’s history.openqa. If you need to ensure such pages are fully loaded then you can use “waits”. and it falls into two parts. and how to use frames and windows. If you’re ready. and will depend on their familiarity with the application under test.InternetExplorerDriver org. but there are several implementations. 4. Which you use depends on what you want to do. the HtmlUnit Driver is great. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. and your testing framework. which refers to whether or not an observer believes the tests work as they should.get( ". WebDriver will wait until the page has fully loaded (that is. This varies from person to person. To support higher “perceived safety”. Often.1 Which Implementation of WebDriver Should I Use? WebDriver is the name of the key interface against which tests should be written. This has the added advantage that this driver actually renders content to a screen.0 there is to using WebDriver! Hopefully. there’s “actual safety”.Selenium Documentation. It also provides a more complete discussion of the examples than The 5 Minute Getting Started Guide. As a developer you may be comfortable with this. this additional flexibility comes at the cost of slower overall speed.openqa.2. The normal way to do this is by calling “get”: driver. but sometimes it’s good to be able to test using a real browser. Secondly. Release 1. especially when you’re showing a demo of your application (or running the tests) for an audience.FirefoxDriver org. it is possible to pick the most appropriate driver for a given test.selenium.selenium.ChromeDriver You can find out more information about each of these by following the links in the table. which refers to whether or not the tests work as they should.firefox. Firstly. 4. By writing your tests against the WebDriver interface.ie. To keep things simple. but it’s not graphical. this will have whet your appetite for more. or the CSS properties that apply to it.chrome.selenium.google. let’s take the Next Steps! 4. and so can be used to detect information such as the position of an element on a page. there’s “perceived safety”. A side-effect of this is that typing something into a text field won’t automatically clear it. what you type will be appended to what’s already there. we need to find one. which makes it possible to test keyboard shortcuts such as those used on GMail. a NoSuchElementException will be thrown.2. given an element defined as: <input type= "text" name= "passwd" id= "passwd-id" /> you could find it using any of: WebElement element.findElement(By. 48 Chapter 4.3 Interacting With the Page Just being able to go to places isn’t terribly useful.ARROW_DOWN). What we’d really like to do is to interact with the pages. Keys.4 Filling In Forms We’ve already seen how to enter text into a textarea or text field. List<WebElement> allOptions = select. You can easily clear the contents of a text field or textarea: element. Instead.xpath( "//select" )). the HTML elements within a page. 4. If there’s more than one element that matches the query. If nothing can be found.name( "passwd" )).findElement(By. not all of them will make sense or be valid. for example) an exception will be thrown. For example. Selenium 2. Dealing with SELECT tags isn’t too bad: WebElement select = driver. more specifically. element = driver. What can you do with it? First of all.out.xpath( "//input[@id=’passwd-id’]" )). you may want to enter some text into a text field: element. for (WebElement option : allOptions) { System. Don’t worry! WebDriver will attempt to do the Right Thing. Release 1. but what about the other elements? You can “toggle” the state of checkboxes. element = driver. It is possible to call sendKeys on any element.findElements(By.sendKeys( " and some" . option. and you can use “setSelected” to set something like an OPTION tag selected.2.0 and WebDriver .format( "Value is: %s" .0 4. then only the first will be returned. or. and if you call a method that makes no sense (“setSelected()” on a “meta” tag. but be careful! The text must be an exact match! You should also be careful when using XPATH in WebDriver.findElement(By.tagName( "option" )). So.id( "passwd-id" )). element = driver. WebDriver offers a number of ways of finding elements.Selenium Documentation. First of all.getValue())).findElement(By. WebDriver has an “Object-based” API.sendKeys( "some text" ). You can simulate pressing the arrow keys by using the “Keys” class: element. we represent all types of elements using the same interface: Web Element. you’ve got an element. This means that although you may see a lot of possible methods you could invoke when you hit your IDE’s auto-complete key combination.clear(). You can also look for a link by its text.println(String. this isn’t the most efficient way of dealing with SELECT elements.findElement(By.deselectAll(). then the NoSuchElementException will be thrown: element. printing out their values.setSelected().5 Getting Visual Information And Drag And Drop Sometimes you want to extract some visual information out of an element. } This will find the first “SELECT” element on the page. RenderedWebElement element = (RenderedWebElement) element.name( "source" )) RenderedWebElement target = (RenderedWebElement) driver.submit().Selenium Documentation. If the element isn’t in a form.findElement(By. you probably want to submit it.xpath( "//select" ))). Not all drivers render their content to the screen (such as the HtmlUnit Driver). or on to another element: RenderedWebElement element = (RenderedWebElement) driver.name( "target" )). Release 1. and then select the OPTION with the displayed text of “Edam”. select.2.click(). This will deselect all OPTIONs from the first SELECT on the page. element. either moving an element by a certain amount. One way to do this would be to find the “submit” button and click it: driver. and selecting each in turn.findElement(By. // Assume the button has the ID "submit" :) Alternatively. 4.2. and cycle through each of it’s OPTIONs in turn.id( "submit" )). but if it does you can gather additional information such as the size and location of the element. Once you’ve finished filling out the form. perhaps to see if it’s visible or where it is on screen. As you can see.name( "q" )).selectByVisibleText( "Edam" ).6 Moving Between Windows and Frames It’s rare for a modern web application not to have any frames or to be constrained to a single window.2.findElement(By.0 option. Next Steps For Using WebDriver 49 . you can use drag and drop.dragAndDropOn(target). If you call this on an element within a form. which provides useful methods for interacting with these. WebDriver will walk up the DOM until it finds the enclosing form and then calls submit on that. WebDriver has the convenience method “submit” on every element. Select select = new Select(driver. select.findElement(By. so it’s not safe to assume that the cast will work. 4. You can find out this information by casting the element to a RenderedWebElement: WebElement plain = driver. WebDriver supports moving between named windows using the “switchTo” method: 4. In addition. WebDriver’s support classes include one called “Select”. But how do you know the window’s name? Take a look at the javascript or link that opened it: <a href= "somewhere. Because loading a page is such a fundamental requirement.7 Popup Dialogs Starting with Selenium 2.Selenium Documentation. With this object you can now accept. the method to do this lives on the main WebDriver interface. This will return the currently open alert object. you can access the alert with the following: Alert alert = driver. there is built in support for handling popup dialog boxes. It’s possible to access subframes by separating the path with a dot. After you’ve triggerd and action that would open a popup. 4.8 Navigation: History and Location Earlier. That is: driver. prompts. you can pass a “window handle” to the “switchTo(). but it’s simply a synonym to: driver.html" target= "windowName" >Click here to open a new window</a> Alternatively. This interface works equally well on alerts.navigate(). it’s possible to iterate over every open window like so: for (String handle : driver.to( ". confirms. 4.alert().example. and you can specify the frame by its index too. All frames are evaluated as if from *top*.0 and WebDriver .switchTo().window(handle). read it’s contents or even type into a prompt.switchTo().child" ).window()” method.frame( "frameName" ). Release 1.0 beta 1.com" ). WebDriver has a number of smaller. Refer to the JavaDocs for more information. dismiss.frame( "frameName.getWindowHandles()) { driver.2. 50 Chapter 4. and navigation is a useful task.get(". would go to the frame named “child” of the first subframe of the frame called “frameName”.com")) As you’ve seen. we covered navigating to a page using the “get” command ( driver. Selenium 2. All calls to driver will now be interpreted as being directed to the particular window.switchTo().window( "windowName" ). } You can also swing from frame to frame (or into iframes): driver.0 driver. Knowing this. task-focused interfaces.switchTo().0. 2. this is based on HtmlUnit.out.0 To reiterate: “navigate().3 WebDriver Implementations 4. Pros • Fastest implementation of WebDriver • A pure Java solution and so it is platform independent.format( "%s -> %s" .back(). • Supports JavaScript 4.9 Cookies Before we leave these next steps.get( ". you may be interested in understanding how to use cookies.to()” and “get()” do exactly the same thing. you need to be on the domain that the cookie will be valid for: // Go to the correct domain driver. "value" ).manage().3. One’s just a lot easier to type than the other! The “navigate” interface also exposes the ability to move backwards and forwards in your browser’s history: driver. Next Steps! This has been a high level walkthrough of WebDriver and some of its key capabilities. It’s just possible that something unexpected may happen when you call these methods if you’re used to the behaviour of one browser over another.getCookies(). As the name suggests. driver.Selenium Documentation.example. Please be aware that this functionality depends entirely on the underlying browser.navigate().navigate().com" ).forward(). 4. loadedCookie. for (Cookie loadedCookie : allCookies) { System. You may want to look at the Test Design Considerations chapter to get some ideas about how you can reduce the pain of maintaining your tests and how to make your code more modular. First of all.println(String.3. // Now set the cookie.addCookie(cookie).10 Next.2. WebDriver Implementations 51 . loadedCookie. driver. // And now output all the available cookies for the current URL Set<Cookie> allCookies = driver.getName(). 4.manage(). Release 1.1 HtmlUnit Driver This is currently the fastest and most lightweight implementation of WebDriver. This one’s valid for the entire domain Cookie cookie = new Cookie( "key" .g } 4. 2 Firefox Driver Pros • Runs in a real browser and supports JavaScript • Faster than the Internet Explorer Driver Cons • Slower than the HtmlUnit Driver Before Going Any Further The Firefox Driver contains everything it needs in the JAR file. do we enable HtmlUnit’s JavaScript capabilities and run the risk of teams running into problems that only manifest themselves there. If you want to dig deeper. but it is no different from any other browser: it has its own quirks and differences from both the W3C standard and the DOM implementations of the major browsers. or do we leave JavaScript disabled.3.0 and WebDriver . If you test JavaScript using HtmlUnit the results may differ significantly from those browsers. we reassess this decision: we hope to enable JavaScript by default on the HtmlUnit at some point. This will cause the HtmlUnit Driver to emulate Internet Explorer’s JavaScript handling by default. Enabling JavaScript If you can’t wait. Although the DOM is defined by the W3C each browser out there has its own quirks and differences in their implementation of the DOM and in how JavaScript interacts with it. 4. knowing that there are more and more sites that rely on JavaScript? We took the conservative approach. Release 1. and WebDriver will do everything else for you. we had to make a choice.Selenium Documentation. When we say “JavaScript” we actually mean “JavaScript and the DOM”. With each release of both WebDriver and HtmlUnit.setJavascriptEnabled(true). enabling JavaScript support is very easy: HtmlUnitDriver driver = new HtmlUnitDriver(). With WebDriver. despite its ability to mimic other browsers. and by default have disabled support when we use HtmlUnit.jar or webdriver-all. then all you need to do is put the webdriver-firefox.jar on your CLASSPATH. carry on reading! 52 Chapter 4. If you’re just interested in using this driver. driver. though. Selenium 2.0 Cons • Emulates other browser’s JavaScript behaviour (see below) JavaScript in the HtmlUnit Driver None of the popular browsers uses the JavaScript engine used by HtmlUnit (Rhino). HtmlUnit has an impressively complete implementation of the DOM and has good support for using JavaScript. 3.getProperty() and set using System. This defaults to driver.zip” which may be downloaded from the website.3 Internet Explorer Driver This driver has been tested with Internet Explorer 6. It has also been successfully tested on Vista. Pros • Runs in a real browser and supports JavaScript Cons • Obviously the Internet Explorer Driver will only work on Windows! • Comparatively slow (though still pretty snappy :) Installing Simply add webdriver-all.firefox.exe By default. WebDriver Implementations 53 . 4. though some configuration is required.reap_profile Normally the Firefox binary is assumed to be in the default location for your particular operating system: OS Expected Location of Firefox Linux firefox (found using “which”) Mac /Applications/Firefox.3.app/Contents/MacOS/firefox Windows XP %PROGRAMFILES%\Mozilla Firefox\firefox. You do not need to run an installer before using the Internet Explorer Driver. contains all the dependencies (including the common library) required to run the Firefox Driver.profile WebDriver creating an anonymous profile webShould be “true” if temporary files and profiles should not be deleted driver. Release 1. driver.jar to your CLASSPATH. 4. In order to use it: • Copy all the “jar” files on to your CLASSPATH.0 Important System Properties The following system properties (read using System.Selenium Documentation. the Firefox driver creates an anonymous profile Installing a Downloaded Binary The “wedriver-all.exe Windows Vista \Program Files (x86)\Mozilla Firefox\firefox. 7 and 8 on XP.firefox. Selenium Documentation. the Chrome Driver may allow you to verify that your site works in Safari. 4. Note that Chrome Driver is one of the newest drivers. Important System Properties The following system properties (read using System.0 Required Configuration Add every site you intend to visit to your “Trusted Sites” If you do not do this.4 Chrome Driver See below for instructions on how to install the Chrome Driver.0 and above.reap_profile What it means The location of the binary used to control Chrome. Pros • Runs in a real browser and supports JavaScript • Because Chrome is a Webkit-based browser.exe C:\Users%USERNAME%\AppData\Local\Google\Chrome\Application\chrome.exe 54 Chapter 4.setProperty() in Java code or the -DpropertyName=value command line flag) are used by the Chrome Driver: Property webdriver. Selenium 2.getProperty() and set using System. Cons • Slower than the HtmlUnit Driver Before Going Any Further The Chrome Driver contains everything it needs in the JAR file. then you will not be able to interact with the page.chrome. then all you need to do is put webdriver-all. Release 1.3.app/Contents/MacOS/GoogleChrome or /User/:username/:as_to_the_left %HOMEPATH%\Local Settings\Application Data\Google\Chrome\Application\chrome. Note that since Chrome uses its own V8 JavaScript engine rather than Safari’s Nitro engine. Should be “true” if temporary files and profiles should not be deleted Normally the Chrome binary is assumed to be in the default location for your particular operating system: OS Linux Mac Windows XP Windows Vista Expected Location of Chrome /usr/bin/google-chrome /Applications/Google Chrome. The Chrome Driver_ works with Google Chrome version 4. Please report any problems through the issue tracker.0 and WebDriver .jar on your CLASSPATH. JavaScript execution may differ. If you’re just interested in using this driver.bin webdriver. and WebDriver will do everything else for you.UnderlyingWebDriver() //Finally, close the browser. Call stop on the WebDriverBackedSelenium instance //instead of calling driver.quit(). Otherwise, the JVM will continue running after //the browser has been closed. selenium.stop(); 4.4); 4.6 4.6.1 Matching Implicit Attributes. 4.6. How XPATH Works in WebDriver 57 add the following dependency to your pom.0 and WebDriver .webdriver</groupId> <artifactId>webdriver-support</artifactId> <version>0.xml: <dependency> <groupId>org. and add all the JARs to your CLASSPATH. 4.9. Remote Web Driver client and the support packages.seleniumhq.Selenium Documentation.7376</version> </dependency> 58 Chapter 4.9. HtmlUnit Driver.7 Getting and Using WebDriver 4.7376</version> </dependency> If you want to use the Internet Explorer Driver.7376</version> </dependency> If you want to use the Chrome Driver.webdriver</groupId> <artifactId>webdriver-ie</artifactId> <version>0.xml: <dependency> <groupId>org.0 4.seleniumhq.2 With Maven If you want to use the HtmlUnit Driver.webdriver</groupId> <artifactId>webdriver-chrome</artifactId> <version>0.zip” you can download from the site. The support packages give you useful helper classes.9.7376</version> </dependency> Finally.9. This will give you the Chrome Driver. you need to add the following dependency to your pom. Firefox Driver. you need to add the following dependency to your pom. such as the LiftStyleApi and the PageFactory. you need to add the following dependency to your pom.7.webdriver</groupId> <artifactId>webdriver-htmlunit</artifactId> <version>0.1 From a New Download Unpack the “webdriver-all. Selenium 2.9.xml: <dependency> <groupId>org. you should add the following dependency to your pom.seleniumhq.webdriver</groupId> <artifactId>webdriver-firefox</artifactId> <version>0.seleniumhq.xml: <dependency> <groupId>org. if you like to use any of our support classes.7.xml: <dependency> <groupId>org. Internet Explorer Driver.seleniumhq. Release 1.7376</version> </dependency> If you want to use the Firefox Driver. Roadmap 59 .0 4.Selenium Documentation.8.8 Roadmap The roadmap for WebDriver is available here 4. Release 1.9 Further Resources You can find further resources for WebDriver in WebDriver’s wiki 4. Selenium Documentation. Selenium 2. Release 1.0 60 Chapter 4.0 and WebDriver . 2 RemoteWebDriver You’ll start by using the HtmlUnit Driver.openqa.WebDriver. org. // not the implementation. you won’t see a new browser window open.WebElement.openqa.findElement(By.google. // Find the text input element by its name WebElement element = driver.1 Explicit and Implicit Waits Todo 5.example.HtmlUnitDriver.selenium.submit(). } } 61 . // Enter something to search for element.selenium.out. // Check the title of the page System. WebDriver driver = new HtmlUnitDriver().selenium.get( ". org.openqa.com" ).CHAPTER FIVE WEBDRIVER: ADVANCED USAGE 5. org.openqa.getTitle()).println( "Page title is: " + driver.selenium. package org. Because of this. WebDriver will find the form for us from the element element.name( "q" )).sendKeys( "Cheese!" ). // Now submit the form.htmlunit. // And now use this to visit Google driver. This is a pure Java driver that runs entirely in-memory.openqa.By. public class HtmlUnitExample { public static void main(String[] args) { // Create a new instance of the html unit driver // Notice that the remainder of the code relies on the interface.selenium. import import import import org. } } Compile and run this.jar locally to run this ICapabilities desiredCapabilities = DesiredCapabilities.Title).6 Browser Startup Manipulation Todo Topics to be included: 62 Chapter 5.Selenium Documentation. Selenium makes accessing HtmlUnit easy from any language.0b1. IWebDriver driver = new RemoteWebDriver(desiredCapabilities).FindElement(By.Name( "q" )). element.HtmlUnit().0 HtmlUnit isn’t confined to just Java. class Example { static void Main(string[] args) { //to use HtmlUnit from .3 AdvancedUserInteractions Todo 5.ca/" ). System.4 HTML5 Todo 5.GoToUrl( ". driver.WriteLine( "Page title is: " + driver. Congratulations.ReadLine(). //The rest of the code should look very similar to the Java library IWebElement element = driver.Quit().5 Cookies Todo 5.Console. Note that you’ll need to run the remote WebDriver server to use HtmlUnit from C# using OpenQA. using OpenQA.Submit().Selenium.Net Webdriver relies on a slightly different API to navigate to //web pages because ’get’ is a keyword in .Net driver. Release 1.Selenium. Below is the same example in C#.Navigate(). element. //the .Remote.SendKeys( "Cheese!" ). System. WebDriver: Advanced Usage . you’ve managed to get started with WebDriver! 5. You should see a line with the title of the Google search results as output on the console.Net we must access it through the RemoteWebDriver //Download and run the selenium-server-standalone-2. Release 1.Selenium Documentation.0 • restoring cookies • changing firefox profile • running browsers with plugins 5.7.7 Parallelizing Your Test Runs Todo 5. Parallelizing Your Test Runs 63 . Selenium Documentation. WebDriver: Advanced Usage .0 64 Chapter 5. Release 1. Python. 6.1 Introduction As you can read in Brief History of The Selenium Project. PRuby.2 How Selenium RC Works First. Selenium 1 is still actively supported (mostly in maintenance mode) and provides some features that may not be available in Selenium 2 for a while. before the WebDriver/Selenium merge brought up Selenium 2. 65 . intercepting and verifying HTTP messages passed between the browser and the AUT.. • Client libraries which provide the interface between each programming language and the Selenium RC Server. HP.2. the newest and more powerful tool. and acts as an HTTP proxy. Perl and C#) and support for almost every browser out there. Here is a simplified architecture diagram. Javascript.. 6. including support for several languages (Java. interprets and runs the Selenese commands passed from the test program. we will describe how the components of Selenium RC operate and the role each plays in running your test scripts.CHAPTER SIX SELENIUM 1 (SELENIUM RC) 6. Selenium RC was the main Selenium project for a long time..1 RC Components Selenium RC components are: • The Selenium Server which launches and kills browsers. 2. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands.0 The diagram shows the client libraries communicate with the Server passing each Selenium command for execution. Selenium 1 (Selenium RC) . This occurs when your test program opens the browser (using a client library API function). 66 Chapter 6. executes the Selenium command. The browser. This means you can use any programming language that can send HTTP requests to automate Selenium tests on the browser. and reports back to your program the results of running those tests.Selenium Documentation. Release 1. 6. This runs the Selenese action or verification you specified in your test script.2 Selenium Server Selenium Server receives Selenium commands from your test program. The RC server bundles Selenium Core and automatically injects it into the browser. interprets them. The Server receives the Selenese commands from your test program using simple HTTP GET/POST requests. using its JavaScript interpreter. actually a set of JavaScript functions which interprets and executes Selenese commands using the browser’s built-in JavaScript interpreter. Selenium-Core is a JavaScript program. These folders have all the components you need for using Selenium RC with the programming language of your choice. i.3.0 6. if you already have a Selenese test script created in the SeleniumIDE. 6. 6. • Set up a programming project using a language specific client driver. So to create a test program. which doesn’t require any special installation. Once you’ve chosen a language to work with. 6.1 Installing Selenium Server The Selenium RC server is simply a Java jar file (selenium-server. java -jar selenium-server. The client library takes a Selenese command and passes it to the Selenium Server for processing a specific action or test against the application under test (AUT).3 Client Libraries The client libraries provide the programming support that allows you to run Selenium commands from a program of your own design. Your program can receive the result and store it into a program variable and report it as a success or failure. See the Selenium-IDE chapter for specifics on exporting RC code from Selenium-IDE. There is a different client library for each supported language.2 Running Selenium Server Before starting any tests you must start the server.e.sh on Linux) containing the command above.3. you simply write a program that runs a set of Selenium commands using a client library API.jar).bat on Windows and .3. For the server to run you’ll need Java installed and the PATH environment variable correctly configured to run it from the console.. a set of functions.3 Installation After downloading the Selenium RC zip file from the downloads page.Selenium Documentation. The client library also receives the result of that command and passes it back to your program. you’ll notice it has several subfolders. You can check that you have Java correctly installed by running the following on a console: 6. or possibly take corrective action if it was an unexpected error. Installation 67 . Just downloading the zip file and extracting the server in the desired directory is sufficient. which run Selenium commands from your own program. Then make a shortcut to that executable on your desktop and simply double-click the icon to start the server.2. you can generate the Selenium RC code. there is a programming function that supports each Selenese command. The Selenium-IDE can translate (using its Export menu item) its Selenium commands into a client-driver’s API function calls. And. A Selenium client library provides a programming interface (API).jar This can be simplified by creating a batch or shell executable file (. Go to the directory where Selenium RC’s server is located and run the following from a command-line console. optionally. you simply need to: • Install the Selenium RC Server. Release 1. Within each interface. see the Appendix sections Configuring Selenium RC With Eclipse and Configuring Selenium RC With Intellij. • From Selenium-IDE. or you can write your own simple main() program.jar files to your project as references. Netweaver. 6.) 68 Chapter 6.3 Using the Java Client Driver • Download Selenium RC from the SeleniumHQ downloads page. You can either use JUnit. These concepts are explained later in this section.0 java -version If you get a version number (which needs to be 1.3.py • Either write your Selenium test in Python or export a script from Selenium-IDE to a python file. etc. • Execute your test from the Java IDE or from the command-line. 6.Selenium Documentation. Release 1. you’re ready to start using Selenium RC.5 Using the .3.4 Using the Python Client Driver • Download Selenium RC from the SeleniumHQ downloads page • Extract the file selenium. • Add the selenium-java-client-driver. Selenium 1 (Selenium RC) . however NUnit is very useful as a test engine.5 or later).jar.3. • Extract the file selenium-java-client-driver. 6.jar. If you’re not familiar yet with NUnit. • Add to your test’s path the file selenium. export a script to a Java file and include it in your Java project.) • Create a new project. or TestNg to run your test. • Add to your project classpath the file selenium-java-client-driver. NetBeans. • Open your desired Java IDE (Eclipse. you can also write a simple main() function to run your tests.py • Run Selenium server from the console • Execute your test from a console or your Python IDE For details on Python client driver configuration. see the appendix Python Client Driver Configuration. • Run Selenium server from the console. The API is presented later in this chapter. For details on Java test project configuration. IntelliJ. or write your Selenium test in Java using the selenium-java-client API.NET Client Driver • Download Selenium RC from the SeleniumHQ downloads page • Extract the folder • Download and install NUnit ( Note: You can use NUnit as your test engine. IntegrationTests.4.NET client driver configuration.6 Using the Ruby Client Driver • If you do not already have RubyGems. see the Selenium-Client documentation 6.Net IDE (Visual Studio. Release 1.Net). From Selenese to a Program 69 . In this section.Selenium Documentation. from the NUnit GUI or from the command line For specific details on .0 • Open your desired . • Run Selenium RC server from the console.NET client driver configuration with Visual Studio.core. ThoughtWorks. Imagine recording the following test with Seleniumopen / type q selenium rc IDE.Core.Net language (C#. VB.UnitTests. framework. • Run Selenium server from console • Run your test either from the IDE.1 Sample Test Script Let’s start with an example Selenese test script.Selenium. or export a script from Selenium-IDE to a C# file and copy this code into the class file you just created. we provide several different language-specific examples.google. 6.4 From Selenese to a Program The primary task for using Selenium RC is to convert your Selenese into a programming language. 6. see the appendix .com 6.Selenium.3. These concepts are explained later in this chapter. SharpDevelop.dll) • Add references to the following DLLs: nmock.dll. Mini::Test or RSpec). nunit.4. For details on Ruby client driver configuration. • Execute your test in the same way you would run any other Ruby script. nunit. • Write your own simple main() program or you can include NUnit in your project for running your test.dll • Write your Selenium test in a . install it from RubyForge • Run gem install selenium-client • At the top of your test script. ThoughtWorks.dll.dll and ThoughtWorks. add require "selenium/client" • Write your test script using any Ruby test harness (eg Test::Unit.Selenium. clickAndWait btnG assertTextPresent Results * for selenium rc Note: This example would work with the Google search page. MonoDevelop) • Create a class library (. Threading. namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium. Release 1. NUnit. ". selenium. verificationErrors = new StringBuilder().WaitForPageToLoad( "30000" ). System.Google Search" . select one of these buttons. } catch (Exception) { // Ignore errors if unable to close the browser } Assert. To see an example in a specific language.Click( "btnG" ). If you have at least basic knowledge of an object. selenium. System.Start(). } [Test] public void TheNewTest() { selenium. private StringBuilder verificationErrors. selenium.Stop(). [SetUp] public void SetupTest() { selenium = new DefaultSelenium( "localhost" .2 Selenese as Programming Code Here is the test script exported (via Selenium-IDE) to each of the supported programming languages.AreEqual( "" .4. selenium.0 6.ToString()).Open( "/" ).RegularExpressions. Selenium. } [TearDown] public void TeardownTest() { try { selenium.Type( "q" . you will understand how Selenium runs Selenese commands by reading one of these examples.Framework. "*firefox" .Text.oriented programming language. "selenium rc" ). selenium.GetTitle()).Selenium Documentation. } } } 70 Chapter 6. 4444. Selenium 1 (Selenium RC) . verificationErrors. In C#: using using using using using using System. Assert.AreEqual( "selenium rc . System.Text. browser_url => ". From Selenese to a Program 71 .php’ .*. Release 1.open( "/" ).4. "selenium rc" ). Test::Exception. Test::More "no_plan" . $sel->click_ok( "btnG" ).google. $sel->is_text_present_ok( "Results * for selenium rc" ). selenium.tests. In PHP: <?php require_once ’PHPUnit/Extensions/SeleniumTestCase. } } In Perl: use use use use use use strict. import com. public class NewTest extends SeleneseTestCase { public void setUp() throws Exception { setUp( ". warnings.example. class Example extends PHPUnit_Extensions_SeleniumTestCase { function setUp() { 6. my $sel = Test::WWW::Selenium->new( host => "localhost" . Test::WWW::Selenium.isTextPresent( "Results * for selenium rc" )). browser => "*firefox" .0 In Java: /** Add JUnit framework to your classpath if not already there * for this example to work */ package com. import java. "*firefox" ). $sel->open_ok( "/" ).Pattern. "selenium rc" ).util.selenium.com/" ). selenium.click( "btnG" ). } public void testNew() throws Exception { selenium. port => 4444.type( "q" .google.waitForPageToLoad( "30000" ). assertTrue(selenium.Selenium Documentation. Time::HiRes qw( sleep ) . $sel->wait_for_page_to_load_ok( "30000" ).regex.thoughtworks. $sel->type_ok( "q" . selenium.com/" . selenium. 4444. "( " / " ) sel.google. time.TestCase): def setUp(self): self.0 $this->setBrowser( " *firefox " ). " selenium rc " ). $this->setBrowserUrl( "( " Results * for selenium rc " )) def tearDown(self): self.verificationErrors = [] self. self.click( " btnG " ) sel.Selenium Documentation.google. " ht @selenium.start end @selenium.assertEqual([].com/ " ).failUnless(sel.new( " localhost " . " *firefox " . Release 1.com/ " ) self. " *firefox " . re class NewTest(unittest. 4444.verificationErrors) in Ruby: require " selenium " require " test/unit " class NewTest < Test::Unit::TestCase def setup @verification_errors = [] if $selenium @selenium = $selenium else @selenium = Selenium::SeleniumDriver.selenium. } function testMyTestCase() { $this->open( " / " ).selenium = selenium( " localhost " .set_context( " test_new " ) 72 Chapter 6.selenium sel. } } ?> in Python: from selenium import selenium import unittest.type( " q " . $this->click( " btnG " ). Selenium 1 (Selenium RC) . $this->assertTrue($this->isTextPresent( " Results * for selenium rc " )).wait_for_page_to_load( " 30000 " ) self. " selenium rc " ) sel. $this->type( " q " .start() def test_new(self): sel = self. $this->waitForPageToLoad( " 30000 " ).stop() self. 6.5.5 Programming Your Test Now we’ll illustrate how to program your own tests using examples in each of the supported programming languages.NET if you are using one of those languages. Optionally. @verification_errors end def test_new @selenium.wait_for_page_to_load " 30000 " assert @selenium.open " / " @selenium. The language-specific APIs tend to differ from one to another.1 Java For Java. Some development environments like Eclipse have direct support for these via plug-ins.click " btnG " @selenium. optionally modifying the result. • Write a very simple main program that executes the generated code. Also.is_text_present( " Results * for selenium rc " ) end end In the next section we’ll explain how to build a test program using the generated code. you will need to change the browser-open parameters in the statement: 6. There are essentially two tasks: • Generate your script into a programming language from Selenium-IDE. or NUnit for . people use either JUnit or TestNG as the test engine. This makes it even easier.type " q " .0 end def teardown @selenium. Programming Your Test 73 . Teaching JUnit or TestNG is beyond the scope of this document however materials may be found online and there are publications available. PHP 6. " selenium rc " @selenium. you can adopt a test engine platform like JUnit or TestNG for Java.stop unless $selenium assert_equal []. Here. • Java • C# • Python • Ruby • Perl. You will probably want to rename the test class from “NewTest” to something of your own choosing.5.Selenium Documentation. Release 1. If you are already a “java-shop” chances are your developers will already have some experience with one of these test frameworks. we show language-specific examples. so you’ll find a separate explanation for each. util. // We instantiate and start the browser } public void testNew() throws Exception { selenium. using System.com/"). You’ll use this for instantiating a // browser and making it do what you need.NET Client Driver works with Microsoft.click( "btnG" ).NET testing framework like NUnit or the Visual Studio 2005 Team System. 4444.type( "q" . public class NewTest extends SeleneseTestCase { // We create our Selenium test case public void setUp() throws Exception { setUp( ". // This is the driver’s import.waitForPageToLoad( "30000" ). The Selenium-IDE generated code will look like this.open( "/" ). using System.com/" . The generated code will look similar to this. Release 1. Selenium 1 (Selenium RC) .tests. 74 Chapter 6. // These are the real test steps } } 6. It includes the using statement for NUnit along with corresponding NUnit attributes identifying the role for each member function of the test class.google. "*firefox" ).regex.NET.google.example. Also. import java.selenium. // We specify the package of our tests import com.google. Selenium-IDE assumes you will use NUnit as your testing framework.thoughtworks. "*iehta". selenium. selenium. assertTrue(selenium.com/").0 selenium = new DefaultSelenium("localhost". selenium. ". package com. 4444. You can see this in the generated code below.*.Selenium Documentation. You can remove the module if it’s not used in your // script. "selenium rc" ). // Selenium-IDE add the Pattern module because it’s sometimes used for // regex validations.5. This example has comments added manually for additional clarity.2 C# The .isTextPresent( "Results * for selenium rc" )).Text. It can be used with any . you will need to change the browser-open parameters in the statement: selenium = new DefaultSelenium("localhost".Pattern. You will probably have to rename the test class from “NewTest” to something of your own choosing. ". "*iehta". AreEqual( "" . verificationErrors = new StringBuilder().AreEqual( "Google" . selenium. private StringBuilder verificationErrors.Framework.com/" ).Start().google. "*iehta" . } catch (Exception) { // Ignore errors if unable to close the browser } Assert. [SetUp] public void SetupTest() { selenium = new DefaultSelenium( "localhost" . System.0 using using using using System.Threading. Assert. verificationErrors.google. Release 1.com/" ).Stop(). selenium.Text.Open( " Documentation. selenium. Programming Your Test 75 .5. // Assert Title of page. } [TearDown] public void TeardownTest() { try { selenium. NUnit. } [Test] public void TheNewTest() { // Open Google search engine. ". namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium. 4444. // Provide search term as "Selenium OpenQA" 6.ToString()).RegularExpressions.GetTitle()). Selenium. IsTrue(selenium. // Wait for page to load.openqa. time. You’ll use this class for instantiating a # browser and making it do what you need. ". "Selenium OpenQA" ). " *firefox " .3 Python Pyunit is the test framework to use for Python.selenium.html>_. // Click on Search button.org/library/unittest.Click( "btnG" ). // Assert that "www. 6. To learn Pyunit refer to its official documentation <. # You can remove the modules if they are not used in your script. class NewTest(unittest. selenium. 4444. The basic test structure is: from selenium import selenium # This is the driver’s import.com/ " ) self. Release 1.5. // Read the keyed search term and assert it.python.TestCase): # We create our unittest test case def setUp(self): self.org" )).verificationErrors = [] # This is an empty array where we will store any verification errors # we find in our tests self. Here you should put the actions you need 76 Chapter 6.AreEqual( "Selenium OpenQA" . Assert. // Assert that page title is .IsTextPresent( "www. and TeardownTest() in turn. selenium.GetValue( "q" )).start() # We instantiate and start the browser def test_new(self): # This is the test code. selenium.WaitForPageToLoad( "5000" ).Google Search" Assert. you can write a simple main() program that instantiates the test object and runs each of the three methods. selenium.openqa. Or alternatively."Selenium OpenQA .selenium = selenium( " localhost " .org" is available in search results.Google Search" . } } } You can allow NUnit to manage the execution of your tests. SetupTest(). TheNewTest().AreEqual( "Selenium OpenQA .0 selenium. re # This are the basic imports added by Selenium-IDE by default.GetTitle()). import unittest. Selenium 1 (Selenium RC) . Assert.Selenium Documentation.Type( "q" . stop() # we close the browser (I’d recommend you to comment this line while # you are creating and debugging your tests) self. This is a problem because the official Ruby driver for Selenium is the Selenium-Client gem.” and change the test method’s name to something other than “test_untitled. 6. # If you prefer RSpec. def setup # This array is used to capture errors and display them at the # end of the test run.5. not the old Selenium gem.assertEqual([]. the Selenium gem is no longer even under active development.open( " / " ) sel. Release 1. change Selenium::Client::Driver.is_text_present( " Results * for selenium rc " )) # These are the real test steps def tearDown(self): self. On line 1. see the examples in the Selenium-Client # documentation. as described above. Ruby 1. In fact. sel = self.5.8’s default test framework. sel. it is advisable to update any Ruby scripts generated by the IDE as follows: 1. Therefore. On line 11. " selenium rc " ) sel.click( " btnG " ) sel.selenium. # load the Selenium-Client gem require " selenium/client " # Load Test::Unit.type( " q " .0 # the browser to do during your test.new Selenium::SeleniumDriver.Selenium Documentation.4 Ruby Selenium-IDE generates reasonable Ruby.failUnless(sel.” Here is a simple example created by modifying the Ruby code generated by Selenium IDE. self. Programming Your Test 77 .verificationErrors) # And make the test fail if we found that any verification errors # were found 6.new to You probably also want to change the class name to something more informative than “Untitled.selenium # We assign the browser to the variable "sel" (just to save us from # typing "self.selenium" each time we want to call the browser).wait_for_page_to_load( " 30000 " ) self. but requires the old Selenium gem. change require "selenium" to require "selenium/client" 2. require " test/unit " class Untitled < Test::Unit::TestCase # The setup method is called before each test. # Notice that the star (*) is a wildcard that matches any # number of characters. :browser => " *chrome " . # Note that we don’t need to set a timeout here.type " q " . because that # was specified when we created the new driver instance.click " btnG " # Wait for the search results page to load. 78 Chapter 6.new \ :host => " localhost " . :port => 4444. " selenium rc " # Click the button named "btnG" @selenium. Selenium 1 (Selenium RC) . @verification_errors end # This is the main body of your test. @selenium. Release 1. def teardown # Stop the browser session. @selenium.0 @verification_errors = [] # Create a new instance of the Selenium-Client driver. assert @selenium. :timeout_in_second => 60 # Start the browser session @selenium. push it onto the array of errors.open " / " # Type ’selenium rc’ into the field named ’q’ @selenium. above.google. @selenium = Selenium::Client::Driver.Selenium Documentation. if any.is_text_present( " Results * for selenium rc " ) rescue Test::Unit::AssertionFailedError # If the assertion fails. above. @selenium. :url => ". @selenium.set_context( " test_untitled " ) end # The teardown method is called after each test. assert_equal [].start # Print a message in the browser-side log and status bar # (optional).wait_for_page_to_load begin # Test whether the search results contain the expected text. def test_untitled # Open the root of the site we specified when we created the # new driver instance.com/ " .stop # Print the array of error messages. com/ " ) self. however.Selenium Documentation. Release 1. PHP The members of the documentation team have not used Selenium RC with Perl or PHP. If you are using Selenium RC with either of these two languages please contact the Documentation Team (see the chapter on contributing).selenium.com/" . 6. 4444. In Python: self.start() 6. ". $this->setBrowserUrl(". In Perl: my $sel = Test::WWW::Selenium->new( host => "localhost" .6.google.0 @verification_errors << $! end end end 6. "*firefox" ). port => 4444.google.5. 6. assuming you understand Selenese.5 Perl. browser => "*firefox" . " *firefox " .com/" selenium.google. "*firefox" . In Java: setUp( ". 4444.1 Starting the Browser In C#: selenium = new DefaultSelenium( "localhost" . much of the interface will be self-explanatory.6 Learning the API The Selenium RC API uses naming conventions that.6.com/" ).Start(). to support Perl and PHP users. ". Learning the API 79 .com/"). We would love to include some examples from you and your experiences. In PHP: $this->setBrowser("*firefox").selenium = selenium( " localhost " . browser_url => ". we explain the most critical and possibly less obvious aspects. Here.google. 80 Chapter 6. like open or type or the verify commands. NUnit. include library code for reporting results. Selenium 1 (Selenium RC) . Java has two commonly used test frameworks.7. These methods execute the Selenium commands. This also is optional in some client drivers. 6.6. " @selenium. " string to type " ) In the background the browser will actually perform a type operation. For example. Usually. this is the same machine as where the client is running.NET also has its own. In some clients this is an optional parameter. 4444.new( " localhost " . essentially identical to a user typing input into the browser.7 Reporting Results Selenium RC does not have its own mechanism for reporting results. " *firefox " . i. Note that some of the client libraries require the browser to be started explicitly by calling its start() method. The parameters required when creating the browser instance are: host Specifies the IP address of the computer where the server is located. This is required by all the client libs and is integral information for starting up the browser-proxy-AUT communication. . port Specifies the TCP/IP socket where the server is listening waiting for the client to establish a connection. 6.Selenium Documentation. Rather.start Each of these examples opens the browser and represents that browser by assigning a “browser instance” to a program variable.2 Running Commands Once you have the browser initialized and assigned to a variable (generally named “selenium”) you can make it run Selenese commands by calling the respective methods from the browser variable. That’s great. by using the locator and the string you specified during the method call. but what if you simply want something quick that’s already done for you? Often an existing library or test framework can meet your needs faster than developing your own test reporting code. This program variable is then used to call methods from the browser.type( " field-id " . 6. JUnit and TestNG. to call the type method of the selenium object: selenium. along with their primary function of providing a flexible test engine for executing your tests. These.e.1 Test Framework Reporting Tools Test frameworks are available for many programming languages.0 In Ruby: @selenium = Selenium::ClientDriver. it allows you to build your reporting customized to your needs using features of your chosen programming language. This is a required parameter. For example. so in this case localhost is passed. Release 1. browser The browser in which you want to run the tests. url The base url of the application under test. but short. See TestNG Report for more. Test Reports in Java • If Selenium Test cases are developed using JUnit then JUnit Report can be used to generate test reports.7.Selenium Documentation.7. As you begin to use Selenium no doubt you will start putting in your own “print statements” for reporting progress. • ReportNG is a HTML reporting plug-in for the TestNG framework. There are good books available on these test frameworks however along with information on the internet. 6. That may gradually lead to you developing your own reporting. Reporting Results 81 . The TestNG framework generates an HTML report which list details of tests. 6. possibly in parallel to using a library or test framework.4 Test Reporting Examples To illustrate. These often support a variety of formats such as HTML or PDF. ReportNG provides a simple.7. See ReportNG for more. It is intended as a replacement for the default TestNG HTML report. 6. Refer to JUnit Report for specifics. we’ll direct you to some specific tools in some of the other languages supported by Selenium. that’s beyond the scope of this user guide. colour-coded view of the test results. for a very nice summary report try using TestNG-xslt. 6.0 We won’t teach the frameworks themselves here.3 What’s The Best Approach? Most people new to the testing frameworks will being with the framework’s built-in reporting features. • If Selenium Test cases are developed using TestNG then no external task is required to generate test reports.7. after the initial. We will simply introduce the framework features that relate to Selenium along with some techniques you can apply. The ones listed here are commonly used and have been used extensively (and therefore recommended) by the authors of this guide. • Also. From there most will examine any available libraries as that’s less time consuming than developing your own. A TestNG-xslt Report looks like this.2 Test Report Libraries Also available are third-party libraries specifically created for reporting test results in your chosen programming language. learning curve you will naturally develop what works best for your own situation. Regardless. Release 1. In addition. In addition you can report progress information using I/O. we have written this section to illustrate the use of common programming techniques to give you greater ‘verification power’ in your automated testing. Program flow is controlled using condition statements and iteration. Selenium 1 (Selenium RC) . For these reasons and others. Test Reports for Python • When using Python Client Driver then HTMLTestRunner can be used to generate a Test Report. Test Reports for Ruby • If RSpec framework is used for writing Selenium Test Cases in Ruby then its HTML report can be used to generate a test report. Logging Selenium extends the Java client driver to add this Selenese logging ability. You will find as you transition from the simple tests of the existence of page elements to tests of dynamic functionality involving multiple web-pages and varying data that you will require programming logic for verifying expected results. adding programming logic to your tests. Refer to RSpec Report for more.0 See TestNG-xslt for more. It’s the same as for any program.Selenium Documentation. you may need exception handling for error recovery. See HTMLTestRunner. You can do some conditions by embedding javascript in Selenese parameters.8 Adding Some Spice to Your Tests Now we’ll get to the whole reason for using Selenium RC. the Selenium-IDE does not support iteration and standard condition statements. Note: If you are interested in a language independent log of what’s going on. however iteration is impossible. Logging the Selenese Commands • Logging Selenium can be used to generate a report of all the Selenese commands in your test along with the success or failure of each. 82 Chapter 6. take a look at Selenium Server Logging 6. Release 1. Please refer to Logging Selenium. and most conditions will be much easier in a programming language. Basically. In this section we’ll show some examples of how programming language constructs can be combined with Selenium to solve common testing problems. we can iterate over the search results for a more flexible and maintainable solution. But multiple copies of the same code is not good program practice because it’s more work to maintain.8. assertTrue( "Expected text: " +s+ " is missing on page. when running the following line: selenium. let’s check the Selenium search results.type( "q" .type( "q" . Adding Some Spice to Your Tests 83 . Release 1." . "selenium " +s).1 Iteration Iteration is one of the most common things people need to do in their tests. "rc" . sel. Or. sel. foreach (String s in arr) { sel. } 6.2 Condition Statements To illustrate using conditions in tests we’ll start with an example. For example. By using a programming language.8. // Execute loop for each String in array ’arr’. perhaps for verifying your test results you need to process a “result set” returned from a database.waitForPageToLoad( "30000" ).Selenium Documentation. This test could use the Selenese: open type clickAndWait assertTextPresent type clickAndWait assertTextPresent type clickAndWait assertTextPresent / q btnG Results * for selenium rc q btnG Results * for selenium ide q btnG Results * for selenium grid selenium rc selenium ide selenium grid The code has been repeated to run the same steps 3 times. "selenium " +s). In C#: // Collection of String values. "grid" }.click( "btnG" ). If element ‘q’ is not on the page then an exception is thrown: 6.open( "/" ).8. sel. A common problem encountered while running Selenium tests occurs when an expected element is not available on page. String[] arr = { "ide" . although the code is simple and can be easily adapted to the other supported languages. sel. For example.isTextPresent( "Results * for selenium " + s)). If you have some basic knowledge of an object-oriented programming language you shouldn’t have difficulty understanding this section.0 The examples in this section are written in C# and Java. 6. Using the same Google search example we used earlier. you may want to to execute a search multiple times. // If element is available on page then perform type operation.getEval(script). // Create array in java scrip script += "inputFields = window.// Create array in java scri script += "var cnt = 0. For some tests that’s what you want.Selenium Documentation. script += "for(var i=0.printf( "Element: " +q+ " is not available on page.length.0 com. public static String[] getAllCheckboxIds () { String script = "var inputId = new Array().split( ".document.id .length." ." ). 6. Release 1. script += "inputId.id !=’undefined’ " + "&& inputFields[i]. A better approach is to first validate if the element is really present and then take alternatives when it it is not.selenium. String[] checkboxIds = selenium. } else { System. "}" + // end of if. // Counter for check box ids.toString(). But often that is not desirable as your test script has many other subsequent tests to perform.thoughtworks." .3 Executing JavaScript from Your Test JavaScript comes very handy in exercising an application which is not directly supported by selenium." ) } The advantage of this approach is to continue with test execution even if some UI elements are not available on page." . Remember to use window object in case of DOM expressions as by default selenium window is referred to. Selenium 1 (Selenium RC) . Consider an application having check boxes with no static identifiers.isElementPresent( "q" )) { selenium. "Selenium rc" )." . Let’s look at this using Java.id !=null " + "&& inputFields[i]. // Loop through the script += "if(inputFields[i]. // If input fie script += "inputId[cnt]=inputFields[i]. i++) {" ." ). "}" . if(selenium.out.8. In this case one could evaluate JavaScript from selenium RC to get ids of all check boxes and then exercise them. 84 Chapter 6.images.SeleniumException: ERROR: Element q not found This can cause your test to abort." ." + // increment the counter.getEval( "window. // Split the s return checkboxIds.// Convert array in to string. The getEval method of selenium API can be used to execute JavaScript from selenium RC. } To count number of images on a page: selenium.type( "q" . not the test window. script += "var inputFields = new Array().document. i<inputFields.getElementsByTagName(’input’). // end of for." + // Save check box id to inp "cnt++.getAttribute(’type’) == ’checkbox’) {" . However.1 Proxy Configuration If your AUT is behind an HTTP proxy which requires authentication then you should configure http. 6. run the server with the -h option. so we’ve provided explanations for some of the more important options.0. the server is started by running the following. The provided descriptions will not always be enough. $ java -jar selenium-server.proxyHost.9 Server Options When the server is launched.9.9. command line options can be used to change the default server behaviour.0 6.proxyPassword using the following command. Recall. http. Selenium by default ran the application under test in a sub frame as shown here. prior to version 1.proxyPort.proxyUser and http.proxyPort=8080 -Dhttp. 6.proxyHost=proxy. $ java -jar selenium-server. Server Options 85 .jar To see the list of options.jar -Dhttp.9.2 Multi-Window Mode If you are using Selenium 1.0 you can probably skip this section. since multiwindow mode is the default behavior.Selenium Documentation.jar -h You’ll see a list of all the options you can use with the server and a brief description of each. Release 1. $ java -jar selenium-server.com -Dhttp. 6. http. 0 Some applications didn’t run correctly in a sub frame. 86 Chapter 6.Selenium Documentation. Selenium 1 (Selenium RC) . Release 1. and needed to be loaded into the top frame of the window. The multi-window mode option allowed the AUT to run in a separate window rather than in the default frame where it could then have the top frame it required. you will need to explicitly specify the profile.exe -profilemanager 6.0.9.0. to create a separate Firefox profile. then type and enter one of the following: firefox. However. Release 1. Open the Windows Start menu.Selenium Documentation.3 Specifying the Firefox Profile Firefox will not run two instances simultaneously unless you specify a separate profile for each instance. so if you are using Selenium 1.0 and later runs in a separate profile automatically. First. Selenium RC 1. follow this procedure.0 For older versions of Selenium you must specify multiwindow mode explicitly with the following option: -multiwindow As of Selenium RC 1. if you want to run your test within a single frame (i. you can probably skip this section.e.9. if you’re using an older version of Selenium or if you need to use a specific profile for your tests (such as adding an https certificate or having some addons installed). using the standard for earlier Selenium versions) you can state this to the Selenium Server using the option -singlewindow 6. Server Options 87 . select “Run”. 6. the server will start the tests and wait for a specified number of seconds for the test to complete.jar -log selenium.5 Selenium Server Logging Server-Side Logs When launching selenium server the -log option can be used to record valuable debugging information reported by the Selenium Server to a text file.exe -P Create the new profile using the dialog. This command line is very long so be careful when you type it. and the ID number of the thread that logged the message.9. tell it to use this new Firefox profile with the server command-line option -firefoxProfileTemplate and specify the path to the profile using it’s filename and directory path. For instance: java -jar selenium-server.jar -htmlSuite "*firefox" " firefox.com" "c:\absolute This will automatically launch your HTML suite. regardless of whether they are profile files or not. Note: When using this option. the command will exit with a non-zero exit code and no results file will be generated. run all the tests and save a nice HTML report with the results. For example: 20:44:25 DEBUG [12] org.9.selenium.google. not a single test. Selenium 1 (Selenium RC) .SeleniumDriverResourceHandler Browser 465828/:top frame1 posted START NEW The message format is 88 Chapter 6. java -jar selenium-server. if the test doesn’t complete within that amount of time. Also be aware the -htmlSuite option is incompatible with -interactive You cannot run both at the same time.server. Note this requires you to pass in an HTML Selenese suite.4 Run Selenese Directly Within the Server Using -htmlSuite You can run Selenese html files directly within the Selenium Server by passing the html file to the server’s command line. Then when you run Selenium Server.Selenium Documentation. -firefoxProfileTemplate "path to the profile" Warning: Be sure to put your profile in a new folder separate from the default!!! The Firefox profile manager tool will delete all files in a folder if you delete a profile. The log file also includes the logger name. More information about Firefox profiles can be found in Mozilla’s Knowledge Base 6. Release 1.openqa.log This log file is more verbose than the standard console logs (it includes DEBUG level logging messages). it cannot run that loaded code against www. The Same Origin Policy dictates that any code loaded within the browser can only operate within that website’s domain.mysite2. pass the -browserSideLog argument to the Selenium Server.mysite. To access browser-side logs. if the browser loads JavaScript code when it loads www. Specifying the Path to a Specific Browser 89 . java -jar selenium-server.Selenium Documentation. To work within this policy. use the *custom specifier followed by the full path to the browser’s executable: *custom <path to browser> 6. This is called XSS (Cross-site Scripting). This security restriction is applied by every browser in the market and its objective is to ensure that a site’s content will never be accessible by a script from another site.com. 6. It cannot perform functions on another website.10. Browser-Side Logs JavaScript on the browser side (Selenium Core) also logs important messages. 6. Also. these can be more useful to the end-user than the regular Selenium Server logs.10 Specifying the Path to a Specific Browser You can specify to Selenium RC a path to a specific browser. this is used to allow your tests to run against a browser not directly supported by Selenium RC. a script placed on any website you open would be able to read information on your bank account if you had the account page opened on other tab. in many cases. It’s not fundamental for a Selenium user to know this.jar -browserSideLog -browserSideLog must be combined with the -log argument. Selenium-Core (and its JavaScript commands that make all the magic happen) must be placed in the same origin as the Application Under Test (same URL).11. This is useful if you have different versions of the same browser and you wish to use a specific one. When specifying the run mode.1 The Same Origin Policy The main restriction that Selenium faces is the Same Origin Policy.com–even if that’s another of your sites.0 TIMESTAMP(HH:mm:ss) LEVEL [THREAD] LOGGER .11 Selenium RC Architecture Note: This topic tries to explain the technical implementation behind Selenium RC. to log browserSideLogs (as well as all other DEBUG level logging messages) to a file. but could be useful for understanding some of the problems you might find in the future. Release 1. 6.MESSAGE This message may be multiline. If this were possible. To understand in detail how Selenium RC Server works and why it uses proxy injection and heightened privilege modes you must first understand the same origin policy. So for example. It acts as a “web server” that delivers the AUT to the browser. tells the browser that the browser is working on a single “spoofed” website that the Server provides. essentially. 1 90 Chapter 6. Release 1. Being a proxy gives Selenium Server the capability of “lying” about the AUT’s real URL. 6. however.Selenium Documentation. Its use of the Selenium Server as a proxy avoids this problem. this is why any HTTP request that the browser does will pass through Selenium server and the response will pass through it and not from the real server. restricted by the Same Origin Policy. It. the Selenium Server acts as a client-configured 1 HTTP proxy 2 .11. The proxy is a third person in the middle that passes the ball between the two parts. Selenium RC is not. that sits between the browser and the Application Under Test. In Proxy Injection Mode. Selenium 1 (Selenium RC) .0 Historically. It then masks the AUT under a fictional URL (embedding Selenium-Core and the set of tests and delivering them as if they were coming from the same origin). Selenium-Core was limited by this problem since it was implemented in JavaScript. Here is an architectural diagram. Note: You can find additional information about this topic on Wikipedia pages about Same Origin Policy and XSS. For example. you can force Selenium RC to launch the browser as-is. when a browser is not directly supported. In addition. It should display this message or a similar one: "Unable to connect to remote server. you can launch Firefox with a custom configuration like this: cmd=getNewBrowserSession&1=*custom c: \P rogram Files \M ozilla Firefox \f irefox.e.. One may need to set the MOZ_NO_REMOTE environment variable to make Mozilla browsers behave a little more predictably. We present them along with their solutions here. but if you launch the browser using the “*custom” run mode.13. Unix users should avoid launching the browser using a shell script.NET and XP Service Pack 2) If you see a message like this. Release 1. Normally this just means opening your browser preferences and specifying “localhost:4444” as an HTTP proxy..Inner Exception Message: No connection could be made because the target machine actively refused it. See the SeleniumHQ. firefox-bin) directly. cmd=getNewBrowserSession&1=*custom c: \P rogram Files \M ozilla Firefox \M yBrowser.. but instructions for this can differ radically from browser to browser.14. Consult your browser’s documentation for details.. an exception will be thrown in your test program. This can also be done from the Server in interactive mode. you may still run your Selenium tests against a browser of your choosing by using the “*custom” run-mode (i.1 Running Tests with Different Browser Configurations Normally Selenium RC automatically configures the browser." (using .Selenium Documentation. be sure you started the Selenium Server.org website for supported browsers. 6..14 Troubleshooting Common Problems When getting started with Selenium RC there’s a few potential problems that are commonly encountered. Selenium 1 (Selenium RC) . Be aware that Mozilla browsers can vary in how they start and stop.exe&2=htt Note that when launching the browser this way. 94 Chapter 6.exe&2=h 6. you must manually configure the browser to use the Selenium Server as a proxy..g.1 Unable to Connect to Server When your test program cannot connect to the Selenium Server. it’s generally better to use the binary executable (e. in place of *firefox or *iexplore) when your test application starts the browser. without using an automatic configuration. then there is a problem with the connectivity between the Selenium Client Library and the Selenium Server. With this. you pass in the path to the browsers executable within the API call. If so.0 6.13 Supporting Additional Browsers and Browser Configurations The Selenium API supports running against multiple browsers in addition to Internet Explorer and Mozilla Firefox. 6. 0) cannot start because the browser is already open and you did not specify a separate profile.lang. When you use Selenium-IDE to export your script. most people begin by running thier test program (with a Selenium Client Library) and the Selenium Server on the same machine. however.0 When starting with Selenium RC. The error from the test program looks like this: Error: java. Release 1. Assuming your operating system has typical networking and TCP/IP settings you should have little difficulty.4 Firefox Refused Shutdown While Preparing a Profile This most often occurs when your run your Selenium RC test program against Firefox. 6. you can use common networking tools like ping. you didn’t specify a separate profile when you started the Selenium Server.14. the most likely cause is your test program is not using the correct URL. 6. but if the Selenium Server cannot load the browser you will likley see this error.14. your system administrator can assist you. (500) Internal Server Error This could be caused by • Firefox (prior to Selenium 1.2 Unable to Load the Browser Ok.14. the connectivity should be fine assuming you have valid TCP/IP connectivity between the two machines. Check the parameters you passed to Selenium when you program opens the browser. • The run mode you’re using doesn’t match any browser on your machine. Troubleshooting Common Problems 95 . 6. Also check the user group to be sure there are no known issues with your browser and the “*custom” parameters. ifconfig(Unix)/ipconfig (Windows). • You specified the path to the browser explicitly (using “*custom”–see above) but the path is incorrect. You must manually change the URL to the correct one for your application to be tested. it inserts a dummy URL. In truth. many people choose to run the tests this way. See the section on Firefox profiles under Server Options.Selenium Documentation. sorry. you do want to run Selenium Server on a remote machine. If you have difficulty connecting.14. telnet. This can easily happen. not a friendly error message. but the browser doesn’t display the website you’re testing. but you already have a Firefox browser session running and.RuntimeException: Firefox refused shutdown while preparing a profile Here’s the complete error message from the server: 6. If unfamilar with these.3 Selenium Cannot Find the AUT If your test program starts the browser successfully. To do this use “localhost” as your connection parameter. We recommend beginning this way since it reduces the influence of potential networking problems which you’re getting started. Check to be sure the path is correct. etc to ensure you have a valid network connection. If. To check double-check your java version. or *custom.GET /selenium-server/driver/?cmd=getNewBrowserSession&1=*fir efox&2=http%3a%2f%2fsage-webapp1.lock To resolve this...com HTTP/1.lang..822 WARN .92 does not support Firefox 3. run this from the command line.minor version 49.5.. But don’t forget to check which browser versions are supported by the version of Selenium you are using. Try 96 Chapter 6.Selenium Documentation.waitForFullProfileToBeCreated(FirefoxCustomProfileLauncher. Selenium Server attempts To configure the global proxy settings in the Internet Options Control Panel. Selenium RC 0.browserlaunchers.java:277) . Standard Edition (build 1.google. or you may simply need to add it to your PATH environment variable..FirefoxCustomProfileLaunc her.0_07-b03..selenium. *iexplore.5.. mixed mode) If you see a lower version number. java version "1..openqa.5 Versioning Problems Make sure your version of Selenium supports the version of your browser.. When in doubt... java -version You should see a message showing the Java version..5. you could be having a problem with Internet Explorer’s proxy settings.browserlaunchers.. Release 1. 16:20:27. then it must be because the Selenium Server was not correctly configured as a proxy..0_07" Java(TM) 2 Runtime Environment.. 6. 6.14..idc. you may need to update the JRE. *opera.server. The Selenium Server requires Java 1..5 or higher. At times you may be lucky (I was).0_07-b03) Java HotSpot(TM) Client VM (build 1. The “selenium-server” directory doesn’t exist on google.com/seleniumserver/“.7 404 error when running the getNewBrowserSession command If you’re getting a 404 error while attempting to open a page on “)” while starting server This error says you’re not using a correct version of Java.selenium.919 INFO .RuntimeException: Firefox refused shutdown while preparing a profile at org.14. Caused by: org. • *iexplore: If the browser is launched using *iexplore. You must make sure that those are correctly configured when Selenium Server launches the browser. see the section on Specifying a Separate Firefox Profile 6.Preparing Firefox profile...FirefoxCustomProfileLaunc her$FileLockRemainedException: Lock file still present! C:\DOCUME~1\jsvec\LOCALS ~1\Temp\customProfileDir203138\parent. it only appears to exist when the proxy is properly configured.openqa...14.0 16:20:03..6 Error message: “(Unsupported major.. Selenium 1 (Selenium RC) .. For example. use the latest release version of Selenium with the most widely used version of your browser.server.. Proxy Configuration highly depends on how the browser is launched with *firefox.qa.1 java.. To login to a site that requires HTTP basic authentication. you should never see SSL certificate warnings. like this: open(“”.14. *opera) we automatically hard-code the proxy for you. • SSL certificate warnings: Selenium RC automatically attempts to spoof SSL certificates when it is enabled as a proxy. – You may also try configuring your proxy manually and then launching the browser with *custom. or the wrong port.. use a username and password in the URL.Selenium Documentation. you’ll need to start Selenium Server with “-Dhttp. see more on this in the section on HTTPS.8 Permission Denied Error The most common reason for this error is that your session is attempting to violate the same-origin policy by crossing domain boundaries (e. You may need to know how to manage these. then the browser will be unable to connect to the Internet. Click on the “Connections” tab and click on “LAN Settings”. Often it is impossible to reproduce the problem with a debugger because the trouble stems from race conditions which are not reproducible when the debugger’s overhead is added to the system.9 Handling Browser Popup Windows There are several kinds of “Popups” that you can get during a Selenium test. as described in RFC 1738.0 looking at your Internet Options control panel. otherwise you’ll get a 404 error.com/blah/blah/blah“). If your browser is configured correctly. If you’re encountering 404 errors and have followed this user guide carefully post your results to user group for some help from the user community.14. Read the section about the The Same Origin Policy. Proxy Injection carefully. To check whether you’ve configured the proxy correctly is to attempt to intentionally configure the browser incorrectly. see the Proxy Configuration for more details. Troubleshooting Common Problems 97 .g. Permission issues are covered in some detail in the tutorial. If you had successfully configured the browser’s proxy settings incorrectly. which is one way to make sure that one is adjusting the relevant settings. 6. or are no longer available (after the page has started to be unloaded). • For other browsers (*firefox.. or with *iehta browser launcher. • HTTP basic authentication dialogs: These dialogs prompt for a username/password to login to the site. You may not be able to close these popups by running selenium commands if they are initiated by the browser and not your AUT. 6. Try configuring the browser to use the wrong proxy server hostname.14. accesses a page from and then accesses a page from) or switching protocols (moving from to). This error can be intermittent. Release 1. and so ther are no known issues with this functionality. Each type of popup needs to be addressed differently. • *custom: When using *custom you must configure the proxy correctly(manually). Double-check that you’ve configured your proxy settings correctly. This error can also occur when JavaScript attempts to find UI objects which are not yet available (before the page has completely loaded). You can specify the path to firefox-bin directly. • modal JavaScript alert/confirmation/prompt dialogs: Selenium tries to conceal those dialogs from you (by replacing window. 6. 6. Selenium 1 (Selenium RC) . If you’re seeing an alert pop-up.page”. If executing Firefox through a shell script.. leaving the browser running. Selenium may not recognize windows loaded before the onload function. like this. 0).page”.13 Problems With Verify Commands If you export your tests from Selenium-IDE. 6.” and try again. why isn’t my Firefox browser session closing? On Unix/Linux you must invoke “firefox-bin” directly.alert. 6. cmd=getNewBrowserSession&1=*firefox /usr/local/firefox/firefox-bin&2=firm and window. Release 1.js -> user_pref(“browser.14. See the sections on these topics in Chapter 4. so make sure that executable is on the path. On most Linux distributions. refer to the HTTPS section for how to do this.0 needed to invoke “firefox-bin” directly. which is usually too early for us to protect the page. it’s probably because it fired during the page load process.14. window.14. make sure that the real executable is on the path.11 Firefox *chrome doesn’t work with custom profile Check Firefox profile folder -> prefs. the real firefox-bin is located on: 98 Chapter 6.c 6.e.10 On Linux.14. so if you are using a previous version.startup. Again.0 browser to trust our dangerous “CyberVillains” SSL certificate authority. before the parent page’s javascript window. These interceptors work best in catching new windows if the windows are loaded AFTER the onload() function.15 Firefox on Linux On Unix/Linux. when it comes time to kill the browser Selenium RC will kill the shell script.onload() function runs)? No.google.12 Is it ok to load a custom pop-up as the parent page is loading (i.14.prompt) so they won’t stop the execution of your page. you may find yourself getting empty verify strings from your tests (depending on the programming language used).Selenium Documentation. Comment this line like this: “//user_pref(“browser. versions of Selenium before 1.14. Note: This section is not yet developed. Selenium relies on interceptors to determine window names as they are being loaded.startup. 6. Selenese contains commands for asserting or verifying alert and confirmation popups.14 Safari and MultiWindow Mode Note: This section is not yet developed. 0). x. you should use: //td[@style="BACKGROUND-COLOR:yellow"] This is a problem if your test is intended to work on multiple browsers.x/" If necessary.17 Where can I Ask Questions that Aren’t Answered Here? Try our user group 6.x/firefox-bin " 6.bashrc file: export PATH= "$PATH:/usr/lib/firefox-x. like this: " *firefox /usr/lib/firefox-x. Opera or Safari but not with IE.14. For example: //td[@style="background-color:yellow"] This would work perfectly in Firefox. 6. Troubleshooting Common Problems 99 .14. IE interprets the keys in @style as uppercase. So. to add that path to the user’s path. So.Selenium Documentation.x/ Where the x. Release 1. you will have to add the following to your . but you can easily code your test to detect the situation and try the alternative locator that only works in IE.16 IE and Style Attributes If you are running your tests on Internet Explorer and you cannot locate elements using their style attribute.x.x.14. even if the source code is in lowercase. you can specify the path to firefox-bin directly in your test.0 /usr/lib/firefox-x.x is the version number you currently have.x. 3. If the test fails you will immediately know the test did not pass. please refer to Chapter 3 first. perhaps often. Validating Results 103 . of course. so you have no information on their status. an image. the text. and easy to change in your test. you won’t get feedback from TestNG or JUnit. assertText You should now be familiar with these commands. You only care that a specific element. The disadvantage: when a check does fail. Do you want your test to terminate. Verify When should you use an assert command and when should you use a verify command? This is up to you. use assertText since this is the strictest type of checkpoint.3. there are other checks which were never performed. and the mechanics of using them.1 Assert vs. Asserts are more commonly used then verifys due to their immediate feedback. If your test uses only verify commands you are guaranteed (assuming no unexpected exceptions) the test will run to completion whether the checks find defects or not. say a paragraph. Test engines such as TestNG and JUnit have plugins for commonly used development environments (Chap 5) which conveniently flag these tests as failed tests. verify commands will not terminate the test. that is what you want. The difference is in what you want to happen when the check fails. It will ensure that a particular type of element exists (and if using XPath can ensure it exists relative to other objects within the page). Sometimes.3 Validating Results 7. In contrast. If you use an assert.0 7. Perhaps your web-designers are frequently changing the page and you don’t want your test to fail every time they do this because the changes themselves are expected periodically. It depends on the requirements for your test. is at a specific location. The advantage: you have an immediate visual of whether the checks passed. only the HTML tag is what is relevant. say. or to continue and simply record that the check failed? Here’s the trade-off. Release 1. If you are running hundreds of tests. If in doubt. However. assume you still need to check that something is on the page. you will need to decide • Do I only check that the text exists on the page? (verify/assertTextPresent) • Do I only check that the HTML element exists on the page? That is. 7. the element and it’s text content? (verify/assertText) There is no right answer. or an image. the test will stop at that point and not run any subsequent checks. assertElementPresent.2 Trade-offs: assertTextPresent. and the immediate feedback of asserts will be more appropriate. You will need to look at the results of a console printout or a log output. 7. The disadvantage: you have to do more work to examine your test results. When constructing your tests. image. If not. (verify/assertElementPresent) • Must I test both. this will be time-consuming. In this case you can use verify/assertElementPresent. That is. each with it’s own log.3. You can always change it later but at least you won’t be missing any potential failures. But you don’t care what the content is.Selenium Documentation. depend on the requirements for the application you’re testing. or heading text. or other content is not to be checked. They are easy concepts. This can fail if either the HTML element (tag) OR the text is not what your test is expecting. Which. Getting a feel for these types of decisions will come with time and a little experience. Verify/assertText is the most specific test type. And you will need to take the time to look through this output every time you run your test. So. for your test script to click this button you simply need to use the following selenium command. Sometimes though. but it is still a static tag. and also makes your test code more readable. this UI element will always have this Identifier. Locating via a link’s text is often convenient and performs well. when this page is displayed. Also. If you must test that an image displaying the company logo appears at the top of the page within a header section XPath may be the better locator. in Selenium 1. you must use an XPath locator. <a class= "button" id= "adminHomeForm" onclick= "return oamSubmitForm(’adminHomeForm’. For example. if the link text is likely to change frequently. assuming the ID or name within the page source is well-named. if there is a link that must occur within the second paragraph within a <div> section. click adminHomeForm Or. Release 1. you can use XPath to specify this. With XPath (and DOM) you can locate an object with respect to another object on the page. a dynamic element is a page element who’s identifer varies with each instance of the page.0 104 Chapter 7. If the page source does not have an ID or name attribute you may have no choice but to use an XPath locator. locating by the <a> element would be the better choice. Its ID remains constant with all instances of.Selenium Documentation. This technique is speciic to links though. 7. somewhere on the page. That is. DOM locators are available simply to support legacy tests. Xpath has been known to be especially slow in Internet Explorer version 7. XPath statements take longer to process since the browser must run it’s XPath processor." href= "#" >View Archived Allocation Events</a> This HTML anchor tag defines a button with an ID attribute of “adminHomeForm”.4. Test Design Considerations .) There is an advantage to using XPath that locating via ID or name attributes do not have.0 7.2 Locating Dynamic Elements As was described earlier in the section on types of tests.1 Choosing a Location Strategy There are multiple ways of selecting an object on a page. (DOM locators are no longer commonly used since Xpath can do everything they can and more. With ID and name locators. you can only specify that they occur on the page that is. ’adminHomeForm:_ID38’). For example.4.4 Location Strategies 7. The HTML will be the same each time this page is loaded in the browser. It’s a fairly complex anchor tag when compared to most HTML tags. <input type= "checkbox" value= "true" id= "addForm:_ID74:_ID75:0:_ID79:0:checkBox" name= "addForm:_ID74:_ID75:0:_ID79:0:checkBox" /> This defines a checkbox. Location Strategies 105 . using a standard locator would look something like the following. String[] checkboxids = selenium. however. again in Selenium-RC selenium. It can be done like this. The next time this page is loaded the Identifier will be a different value from the one used in the Selenium command and therefore. this approach would not work.click(expectedText).contains( "addForm" )) { selenium. click //input[3] Or click //div/p[2]/input[3] If however. may generate HTML dynamically where the identifier varies on different instances of the webpage.Selenium Documentation. // Collect all input IDs on page. Release 1. So. for the checkbox you can simply use click //input Or. will not be found. The click operation will fail with an “element not found” error. To correct this. Given the dynamically generated Identifier. for(String checkboxid:checkboxids) { if(checkboxid. Your application. Its ID and name attributes (both addForm:_ID74:_ID75:0:_ID79:0:checkBox) are dynamically generated values.0 selenium. You can capture this ID from the website before you use it in a Selenium command.click( "adminHomeForm" ). a simple solution would be to just use an XPath locator rather than trying to use an ID locator.getAllFields(). In this case. 7. HTML for a dynamic page element might look like this. if it is not the first input element on the page (which it likely is not) try a more detailed XPath statement. For instance. click addForm:_ID74:_ID75:0:_ID79:0:checkBox Or. you do need to use the ID to locate the element.click("addForm:_ID74:_ID75:0:_ID79:0:checkBox). a different solution is needed.4. } } This approach will work if there is only one check box whose ID has the text ‘expectedText’ appended to it. // Loop initialization. 7.sleep(1000).waitForPageToLoad(waitPeriod). many tests will frequently click on a page element and wait for page to load multiple times within a test. Let’s consider a page which brings a link (link=ajaxLink) on click of a button on page (without refreshing the page) This could be handled by Selenium using a for loop. * * param elementLocator * param waitPeriod */ 106 Chapter 7. In Selenim 2. This is explained in detail in the WebDriver chapters. but it isn’t difficult.5 Wrapping Selenium Calls to Reduce Duplication As with any programming.3 Locating Ajax Elements As was presented in the Test Types subsection above. try { if (selenium. Ajax is a common topic in the user forum and we recommend searching previous discussions to see what others have done. The parameter is a By object which is how WebDriver implements locators.. Instead of duplicting this code you could write a wrapper method that performs both functions. Thread. For example. selenium.isElementPresent( "link=ajaxLink" )) break.0 (Selenium-RC) a bit more coding is involved. One way to prevent this is to wrap frequently used selenium calls with functions or class methods of your own design. } catch (Exception e) // Pause for 1 second.4. Test Design Considerations . if it’s not availble wait for a predefined period and then again recheck it. second++) { // If loop is reached 60 seconds then break the loop. The best way to locate and verify an Ajax element is to use the Selenium 2.Selenium Documentation. } This certainly isn’t the only solution. // Search for element "link=ajaxLink" and if available then break loop. for (int second = 0.0 you use the waitFor() method to wait for a page element to become available. The approach is to check for the element. /** * Clicks and Waits for page to load. Release 1. This is then executed with a loop with a predetermined time-out terminating the loop if the element isn’t found.0 7.click(elementLocator). a page element implemented with Ajax is an element that can be dynamically refreshed without having to refresh the entire page. if (second >= 60) break. To do this with Selenium 1. selenium. It was specifically designed to address testing of Ajax elements where Selenium 1 has some limitations.0 WebDriver API. you will want to use utility functions to handle code that would otherwise be duplicated throughout your tests. Release 1.click(elementLocator). /** * Selenium-WebDriver -. while posting a message to a log about the missing element.Clicks on element only if it is available on page. } } This example uses the Selenium 1 API but Selenium 2 also supports this. * * param elementLocator */ public void safeClick(String elementLocator) { WebElement webElement = getDriver().findElement(By. is not available on page + getDriver(). selenium.log( "Element: " +elementLocator+ ". /** * Selenum-RC -. the following method could be used to implements a safe operation that depends on an expected element being present. Hence. * * param elementLocator */ public void safeClick(String elementLocator) { if(selenium. if(webElement != null) { selenium. essentially. then safe methods could be used. This. This is sometimes called a ‘safe operation’.log( "Element: " +elementLocator+ ".click(elementLocator).6 ‘Safe Operations’ that Depend on Element Presence Another common usage of wrapping selenium methods is to check for presence of an element on page before carrying out some operation.Selenium Documentation. } } In this second example ‘XXXX’ is simply a placeholder for one of the multiple location methods that can be called here. implements a ‘verify’ with a reporting mechanism as opposed to an abortive assert. } 7. ‘Safe Operations’ that Depend on Element Presence 107 . Using safe methods is up to the test developer’s discretion. For instance.isElementPresent(elementLocator)) { selenium. even in the wake of missing elements on the page.Clicks on element only if it is available on page.6. } else { // Using the TestNG API for logging Reporter.click(elementLocator). } else { // Using the TestNG API for logging Reporter. is not available on page +selenium.0 public void clickAndWait(String elementLocator.getUrl()). String waitPeriod) { selenium.waitForPageToLoad(waitPeriod). if test execution is to be continued.getLocation()). But if element must be available on page in order to be 7.XXXX(elementLocator)). e.cancel).click( "addEditEventForm:_IDcancel" ).click(admin. selenium. Release 1. login button on home page of a portal) then this safe method technique should not be used.username. The test script then uses the UI Map for locating the elements to be tested.0 able to carry out further operations (i. When a locator needs to be edited.viewoldevents). selenium. A better script would be: public void testNew() throws Exception { selenium. Test Design Considerations . What makes a UI map heplful? Its primary purpose for making test script management much easier. selenium. "xxxxxxxx" ).com" ).waitForPageToLoad( "30000" ). Also. selenium.Selenium Documentation.type(admin. selenium. selenium. for an application’s UI elements.com" ).click(admin. } This script is incomprehensible to anyone who isn’t very familiar with the AUT’s page source.events.click( "loginForm:btnLogin" ). "xxxxxxxx" ). This makes script maintenance more efficient. selenium. selenium.open( ". or for that matter. Consider the following example (in java) of selenium tests for a website: public void testNew() throws Exception { selenium.test. it allows changing the Identifier in a single place. • Cryptic HTML Identifiers and names can be given more human-readable names improving the readability of test scripts.waitForPageToLoad( "30000" ). selenium.type( "loginForm:tbUsername" .waitForPageToLoad( "30000" ).click(admin. selenium. or in our case. rather than having to make the change in multiple places within a test script.events. To summarize. selenium. 7. selenium. in multiple test scripts.waitForPageToLoad( "30000" ).click(admin. Even regular users of the application would have difficulty understanding what the script does.waitForPageToLoad( "30000" ). selenium.7 UI Mapping A UI map is a mechanism that stores Identifiers.click( "adminHomeForm:_activityold" ). selenium. Basically.waitForPageToLoad( "30000" ).open( ". • Using a centralized location for UI objects instead of having them scattered throughout the script. there is a central location for easily finding that object. locators. } 108 Chapter 7.loginbutton). selenium. a UI map is a repository of test script objects that correspond to UI elements of the application being tested. rather than having to search through test script code.events.createnewevent). a UI map has two significant advantages.click( "adminHomeForm:_activitynew" ). selenium. selenium.8. To achieve this.com" ). where each key and value are strings.test.viewoldevents = adminHomeForm:_activityold The locators will still refer to html objects.cancel). } The idea is to have a centralized location for objects and using comprehensible names for those objects. 7.createnewevent). // Click on View Old Events button.click(admin. (please be aware that UI Map is NOT a replacement for comments! Comments are still important for documenting an automated test.events. selenium.loginbutton).loginbutton = loginForm:btnLogin admin. There is clean separation between automation code which knows about application html and the one which carries out actual tests.waitForPageToLoad( "30000" ).click(admin.events.open( "(admin. selenium. Page Object Design Pattern 109 .waitForPageToLoad( "30000" ).0 There are no comments provided but it is more comprehensible because of the keywords used in scripts. // Click on Create New Event button.8 Page Object Design Pattern Page Object Design Pattern models the page specific behaviour in a corresponding class which represents services (public methods) offered by page object. // Click on Cancel button. Consider a property file prop. selenium.click(admin. 7. selenium. selenium. admin.events.) An even better test script could look like this.properties which assigns as ‘aliases’ easily understood Identifiers for the HTML objects used earlier. but we have introduced a layer of abstraction between the test script and the UI elements.events. Release 1. Page Object Design Pattern brings following advantages 1.cancel = addEditEventForm:_IDcancel admin.waitForPageToLoad( "30000" ).events.Selenium Documentation. properties files can be used in java. A properties file contains key/value pairs. // Click on Login button. For more on Properties files refer to the following link.events. selenium.viewoldevents). Values are read from the properties file and used in the Test Class to implement the UI Map. // Provide admin username. public void testNew() throws Exception { // Open app url. selenium. Selenium tests use page object to interact with application and their own verification/assertion to validate page.username.click(admin. "xxxxxxxx" ).createnewevent = adminHomeForm:_activitynew admin.username = loginForm:tbUsername admin. selenium. Release 1. If user action causes control to be directed to new page then it is represented by new page else same page object could be returned. Application html would be spread in multiple tests. curre +selenium.Selenium Documentation.click( "sign-in" ). Page Object may represent an entirely new page or just part of page. Assert.isElementPresent( "compose button" ).assertTrue(selenium. selenium. Test Design Considerations . } } /** * Login as valid user * 110 Chapter 7.getLocation()).waitForPageToLoad( "PageWaitPeriod" ). "Login was unsuccessful" ). above mentioned example could be rewritten as Page Object for Sign-in page /** * Models sign-in page for user */ public class SignInPage extends SelTestCase { private Selenium selenium. which induces unwarranted redundancy and makes test maintenance difficult. Let us see these problems in more detail by considering a selenium test /*** * Tests login feature */ public class Login extends SelTestCase { public void testLogin() { selenium. 2.0 2.selenium = selenium.type( "inputBox" . While auto suggest window of a search engine could be represented by same page as auto suggest window appears on the same page on which user is types in search term. Applying the page object techniques. Hence improved maintainability and reduction in code duplication. if(!selenium.getTitle(). selenium. There is single repository of services offered by page.type( "password" . selenium. public SignInPage(Selenium selenium) { this. There is no separation between test method and application html as both of them are intertwined in one method. "my supersecret password" ). For example login feature on sign-in page could be represented by HomePage class for user as sign in operation directs user to home page of logged in user. instead of application html scattered through out the tests. "testUser" ).equals( "Sign in page" )) { throw new IllegalStateException( "This is not sign in page. } } There are two primary problems with this approach 1. 0 * @param userName * @param password * @return HomePage object */ public HomePage loginValidUser(String userName.loginValidUser( "userName" .8.). Though there is an exception to it.Selenium Documentation. Release 1. While instantiating a page object it could be checked whether control is really on expected page or not.isElementPresent( "compose button" ). selenium.type( "passwordfield" .click( "sign-in" ). public HomePage(Selenium selenium) { if (!selenium. signInPage. "Login was unsuccessful" ). String password) { selenium.assertTrue(selenium. userName). password).equals( "Home Page of logged in user" )) { throw new IllegalStateException( "This is not Home Page of logged "is: " +selenium.getLocation()). "password" ). Assert. Page Object Design Pattern 111 . selenium. Hence in the examples illustrates 7. return new HomePage(selenium).getTitle(). } } and page object for Home page would look as /** *Models features presented by Home page */ public class HomePage extends SelTestCase { private Selenium selenium. } } /*More methods offering the services represented by Home Page of Logged User.type( "usernamefield" . selenium.waitForPageToLoad( "waitPeriod" ). } } Page objects themselves should never be used to make verification/assertion and it is responsibility of tests to validate application state. This section has not been developed yet.10 Handling Errors Note: This section is not yet developed. Release 1.9 Data Driven Testing Data Driven Testing provides capabilities of testing application under tests using varying data sets. " r " ) values = source.Selenium Documentation. This is a very basic example of what you can do. The Python script above opens a text file. Test Design Considerations . search) sel..2 Recovering From Failure A quick note though–recognize that your programming language’s exception. csv file.10.1 Error Reporting 7. Data driven testing is a favourite of test automation as test data expansion does not require any code change. 7.click( " btnG " ) sel.waitForPageToLoad( " 30000 " ) self.readlines() source. The code then saves this in an array of strings.txt " . generally handle this as it’s a common reason for test automation. but the Idea is to show you things that can easily be done with either a programming or scripting language when they’re difficult or even impossible to do using Selenium-IDE.10. These data sets can be read from external files i.0 above both SignInPage and HomePage constructors check if control is on right page.failUnless(sel. and iterates over the array doing a search and assert on each string. Test automation tools.type( " q " . 7. data base or plane excel sheet etc.e. 112 Chapter 7.open( " / " ) sel. This is called Data Driven Testing and is a very common testing task.close() # Execute For loop for each String in the values array for search in values: sel. Refer to the Selenium RC wiki for examples of reading data from spread sheet or using data provider capabilities of TestNG with java client driver. In Python: # Collection of String values source = open( " input_file. Selenium included. 7.handling support can be used for error handling and recovery. 1. why not use them for some data validations/retrieval on the Application Under Test? Consider the example of a registration process where a registered email address is to be retrieved from the database.executeQuery // method which returns the requested information as rows of data in a // ResultSet object.getConnection(url.forName( "com.DatabaseName=TEST_DB" . public static Statement stmt = con. 7. Class. This is a very simple example of data retrieval from a DB in Java. // Fetch value of "email_address" from "result" object.type( "userID" .10. ResultSet result = stmt.microsoft.Selenium Documentation.jdbc.10. // Send SQL SELECT statements to the database via the Statement. String url = "jdbc:sqlserver://192.0 7.executeQuery ( "select top 1 email_address from user_register_table" ). public static Connection con = DriverManager. Handling Errors 113 . // Create statement object which would be used in writing DDL and DML // SQL statement. emailaddress).180:1433. This wouldn’t take too much work from what you’ve already seen.sqlserver. "username" . assuming you have database support functions. String emailaddress = result. // Use the fetched value to login to application. selenium. Release 1. // Prepare connection url.3 Database Validations Since you can also do database queries from your favorite programming language. // Get connection to DB.getString( "email_address" ).168. A more complex test could be to validate that inactive users are not able to login to the application.SQLServerDriver" ). An example of establishing a DB connection and retrieving data from the DB would be: In Java: // Load Microsoft SQL Server JDBC driver.createStatement(). "password" ). Release 1. Test Design Considerations .Selenium Documentation.0 114 Chapter 7. We would love to have you contribute. If there is a member of the community who is experienced in SeleniumGrid.org/how_it_works.CHAPTER EIGHT SELENIUM-GRID Please refer to the Selenium Grid website This section is not yet developed. please contact the Documentation Team.seleniumhq. and would like to contribute. 115 . Selenium Documentation. Selenium-Grid .0 116 Chapter 8. Release 1. findElement(locator). 9.1 Introduction It can be quite simple to extend Selenium. adding your own actions. which types the text twice into a text box. which will be passed the second and third column values in the test. For each action foo there is also an action fooAndWait registered. assertions and locator-strategies. // Create the text to type var valueToType = text + text.doTypeRepeated = function(locator.2 Actions All methods on the Selenium prototype beginning with “do” are added as actions. text) { // All locator-strategies are automatically handled by "findElement" var element = this. The following examples give an indication of how Selenium can be extended with JavaScript.CHAPTER NINE USER-EXTENSIONS NOTE: This section is close to completion. On startup. 9. that makes sure that the element 117 . but it has not been reviewed and edited. }. You can also define your own assertions literally as simple “assert” methods.prototype. Example: Add a “typeRepeated” action to Selenium. which will be passed the second and third column values in the test. and the PageBot object prototype. Example: Add a valueRepeated assertion. Selenium. // Replace the element text with the new text this. Selenium will automatically look through methods on these prototypes.page(). using name patterns to recognize which ones are actions. 9. valueToType). This is done with JavaScript by adding methods to the Selenium object prototype. assertions and locators. which will also auto-generate “verify” and “waitFor” commands. An action method can take up to two parameters. verifyFooa nd waitForFoo registered.3 Accessors/Assertions All getFoo and isFoo methods on the Selenium prototype are added as accessors (storeFoo).page(). An assert method can take up to 2 parameters.replaceText(element. For each accessor there is an assertFoo. assertTextLength. verifyNotFoo. User-Extensions .assertValueRepeated = function(locator.value. A locator strategy takes 2 parameters. PageBot. // Create the text to verify var expectedValue = text + text. assertNotFoo. and waitForNotTextLength commands. assertNotTextLength.findElement(locator). verifyNotTextLength.matches(expectedValue.prototype. waitForTextLength. 9.getText(locator). 118 Chapter 9. waitForValueRepeated and waitForNotValueRepeated. assertFoo. actualValue). Also note that the assertValueRepeated method described above could have been implemented using isValueRepeated. Release 1. with the added benefit of also automatically getting assertNotValueRepeated.3. and waitForNotFoo commands. if you add a getTextLength() method. // The "inDocument" is a the document you are searching.length. text) { return this. i < allElements. the following commands will automatically be available: storeTextLength. 9. verifyFoo. text) { // All locator-strategies are automatically handled by "findElement" var element = this. Selenium.Selenium Documentation.length. waitForFoo and waitForNotFoo for every getFoo All getFoo and isFoo methods on the Selenium prototype automatically result in the availability of storeFoo. waitForFoo.getTextLength = function(locator. i++) { var testElement = allElements[i]. assertNotFoo.page(). that finds the first element a value attribute equal to the the supplied value repeated. verifyTextLength. looking for ones that have // a value === our expected value var allElements = inDocument. assertFoo. Selenium. The 2 commands that would be available in tests would be assertValueRepeated and verifyValueRepeated.locateElementByValueRepeated = function(text. and the second being the document in which to search.getElementsByTagName( "*" ). for (var i = 0.prototype. }.prototype. // Loop through all elements. Example. // Make sure the actual value matches the expected Assert.0 value consists of the supplied text repeated. // Get the actual element value var actualValue = element. Example: Add a “valuerepeated=” locator.4 Locator Strategies All locateElementByFoo methods on the PageBot prototype are added as locator-strategies. storeValueRepeated. inDocument) { // Create the text to search for var expectedValue = text + text. the first being the locator string (minus the prefix). }.1 Automatic availability of storeFoo. Place your user extension in the same directory as your Selenium Server.5. is the official Selenium suggested approach. While this name isn’t technically necessary. 5. In your empty test. 2. as you would the proc = new HttpCommandProcessor( "localhost" . instantiate that HttpCommandProcessor object DefaultSelenium object. Release 1.value && testElement. If you are using client code generated by the Selenium-IDE you will need to make a couple small edits. 3. 9.0 if (testElement. create a new command. First.Selenium Documentation.ca/" ). Your user-extension will not yet be loaded. js file. Below.value === expectedValue) { return testElement. you must close and restart Selenium-IDE. 9. This can be done in the test setup. 4444.js. your user-extension should now be an options in the Commands dropdown. Using User-Extensions With Selenium-IDE 119 .1 Example C# 1. 9. 1. }.5 Using User-Extensions With Selenium-IDE User-extensions are very easy to use with the selenium IDE. 9. Click on OK.6. Options 4. Next.6 Using User-Extensions With Selenium RC If you Google “Selenium RC user-extension” ten times you will find ten different approaches to using this feature.) HttpCommandProcessor proc. just below private StringBuilder verificationErrors. } } return null. you will need to create an HttpCommandProcessor object with class scope (outside the SetupTest method. ". 1. 6. In Selenium Core Extensions click on Browse and find the user-extensions. it’s good practice to keep things consistent. "*iexplore" . 2. Open Firefox and open Selenium-IDE. Create your user extension and save it as user-extensions. Click on Tools. js using using using using using using System. selenium.Start(). Selenium. private HttpCommandProcessor proc.Selenium Documentation.RegularExpressions. Because JavaScript is case sensitive. 4444. System. System. Remember that user extensions designed for Selenium-IDE will only take two arguments.DoCommand( "alertWrapper" . Start the test server using the -userExtensions argument and pass in your user-extensinos.Framework. java -jar selenium-server. //selenium = new DefaultSelenium("localhost".Text. verificationErrors = new StringBuilder(). In this case there is only one string in the array because there is only one parameter for our user extension. Instantiate the DefaultSelenium object using the HttpCommandProcessor object you created. string[] inputParams = { "Hello World" }. but a longer array will map each index to the corresponding user-extension parameter. System. Within your test code. Release 1. 4444. Notice that the first letter of your function is lower case. private StringBuilder verificationErrors.Threading.js file. "*iexplore" selenium = new DefaultSelenium(proc).0 1. inputParams is the array of arguments you want to pass to the JavaScript user-extension. This method takes two arguments: a string to identify the userextension method you want to use and string array to pass arguments. proc.Text. NUnit. User-Extensions . regardless of the capitalization in your user-extension. 1. namespace SeleniumTests { [TestFixture] public class NewTest { private ISelenium selenium. } 120 Chapter 9.jar -userExtensions user-extensions. execute your user-extension by calling it with the DoCommand() method of HttpCommandProcessor. [SetUp] public void SetupTest() { proc = new HttpCommandProcessor( "localhost" . inputParams). your test will fail if you begin this command with a capital. Selenium automatically does this to keep common JavaScript naming conventions. selenium = new DefaultSelenium(proc). 1. "*iexplore". Stop(). string[] inputParams = { "Hello World" .AreEqual( "" . } } } Appendixes: 9. proc. Using User-Extensions With Selenium RC 121 .DoCommand( "alertWrapper" . inputParams). } catch (Exception) { // Ignore errors if unable to close the browser } Assert.0 [TearDown] public void TeardownTest() { try { selenium. verificationErrors.Open( "/" ). } [Test] public void TheNewTest() { selenium.Selenium Documentation.6.}. Release 1.ToString()). Release 1.0 122 Chapter 9.Selenium Documentation. User-Extensions . • Select Visual C# > Class Library > Name your project > Click on OK button. 123 .CHAPTER TEN .NET CLIENT DRIVER CONFIGURATION . • Launch Visual Studio and navigate to File > New > Project.NET client Driver can be used with Microsoft Visual Studio. To Configure it with Visual Studio do as Following. • Under right hand pane of Solution Explorer right click on References > Add References. Release 1.Selenium Documentation.NET client driver configuration .0 • A Class (. 124 Chapter 10. .cs) is created. Rename it as appropriate. Selenium Documentation.core.dll.framework.ThoughtWorks.0 • Select following dll files . nunit. Selenium. Release 1.Selenium.nmock.Selenium.dll.IntegrationTests.UnitTests. ThoughtWorks.dll. nunit.dll.dll.dll and click on Ok button 125 . ThoughtWorks.Core. NET client driver configuration .0 With This Visual Studio is ready for Selenium Test Cases. Release 1.Selenium Documentation. 126 Chapter 10. . CHAPTER ELEVEN JAVA CLIENT DRIVER CONFIGURATION In General configuration of Selenium-RC with any java IDE would have following steps: • Download Selenium-RC from the SeleniumHQ downloads page • Start any java IDE • Create new project • Add to your project classpath selenium-java-client-driver. It should not be too different for higher versions of Eclipse • Launch Eclipse. Perl. Cobol. • Select File > New > Other.0.. 127 . Python.3. Following lines describes configuration of Selenium-RC with Eclipse .jar • Record your test from Selenium-IDE and translate it to java code (Selenium IDE has automatic translation feature to generate tests in variety of languages) • Run selenium server from console • Run your test in the IDE These points have been delineated below with reference to Eclipse and IntelliJ: 11. in other languages as well as C/C++. by means of the various plug-ins. (Europa Release).Version: 3. Release 1. Java Client Driver Configuration .0 • Java > Java Project > Next 128 Chapter 11.Selenium Documentation. 1. Configuring Selenium-RC With Eclipse 129 .0 • Provide Name to your project. Release 1.5 selected in this example) > click Next 11.Selenium Documentation. Select JDK in ‘Use a project Specific JRE’ option (JDK 1. (This described in detail in later part of document. Java Client Driver Configuration . Project specific libraries can be added here. Release 1.0 • Keep ‘JAVA Settings’ intact in next window.) 130 Chapter 11.Selenium Documentation. Release 1.Selenium Documentation.1.0 • Click Finish > Click on Yes in Open Associated Perspective pop up window. 11. Configuring Selenium-RC With Eclipse 131 . Release 1. Java Client Driver Configuration .0 This would create Project Google in Package Explorer/Navigator pane. 132 Chapter 11.Selenium Documentation. 0 • Right click on src folder and click on New > Folder 11. Release 1. Configuring Selenium-RC With Eclipse 133 .1.Selenium Documentation. 0 Name this folder as com and click on Finish button.Selenium Documentation. Java Client Driver Configuration . Release 1. 134 Chapter 11. • This should get com package insider src folder. Selenium Documentation.1. Configuring Selenium-RC With Eclipse 135 .0 • Following the same steps create core folder inside com 11. Release 1. Please notice this is about the organization of project and it entirely depends on individual’s choice / organization’s standards.Selenium Documentation. Release 1. Test scripts package can further be segregated depending upon the project requirements. Create one more package inside src folder named testscripts.0 SelTestCase class can be kept inside core package. 136 Chapter 11. Java Client Driver Configuration . This is a place holder for test scripts. 0 • Create a folder called lib inside project Google. Release 1. Right click on Project name > New > Folder. This is a place holder for jar files to project (i. Selenium client driver. selenium server etc) 11.1. Configuring Selenium-RC With Eclipse 137 .Selenium Documentation.e. Selenium Documentation. Release 1. Java Client Driver Configuration . 138 Chapter 11.0 This would create lib folder in Project directory. Configuring Selenium-RC With Eclipse 139 .0 • Right click on lib folder > Build Path > Configure build Path 11. Release 1.1.Selenium Documentation. 140 Chapter 11. Java Client Driver Configuration .0 • Under Library tab click on Add External Jars to navigate to directory where jar files are saved. Select the jar files which are to be added and click on Open button.Selenium Documentation. Release 1. 1. 11. Configuring Selenium-RC With Eclipse 141 .Selenium Documentation.0 After having added jar files click on OK button. Release 1. 0 Added libraries would appear in Package Explorer as following: 142 Chapter 11. Release 1.Selenium Documentation. Java Client Driver Configuration . • Open a New Project in IntelliJ IDEA. Subversion. IntelliJ IDEA provides close integration with popular open source development tools such as CVS.0 It should not be very different for higher version of intelliJ. Release 1.Selenium Documentation. Intellij provides a set of integrated refactoring tools that allow programmers to quickly redesign their code.0 11.2 Configuring Selenium-RC With Intellij IntelliJ IDEA is a commercial Java IDE by the company JetBrains. Apache Ant and JUnit. Following lines describes configuration of Selenium-RC with IntelliJ 6.2. Configuring Selenium-RC With Intellij 143 . 11. 144 Chapter 11.Selenium Documentation. Java Client Driver Configuration . Release 1.0 • Provide name and location to Project. • Click Next and provide compiler output path. • Click Next and select Single Module Project.Selenium Documentation.0 • Click Next and select the JDK to be used. Release 1. Configuring Selenium-RC With Intellij 145 . 11.2. 146 Chapter 11. Release 1. • Click Next and provide Module name and Module content root. • Click Next and select Source directory. Java Client Driver Configuration .0 • Click Next and select Java module.Selenium Documentation. Configuring Selenium-RC With Intellij 147 . 11. • Click on Project Structure in Settings pan. This will launch the Project Pan. Adding Libraries to Project: • Click on Settings button in the Project Tool bar.0 • At last click Finish. Release 1.Selenium Documentation.2. 0 • Select Module in Project Structure and browse to Dependencies tab. Java Client Driver Configuration . 148 Chapter 11. Release 1.Selenium Documentation. ).2.0 • Click on Add button followed by click on Module Library. (Multiple Jars can be selected b holding down the control key. • Browse to the Selenium directory and select selenium-java-client-driver. 11. Configuring Selenium-RC With Intellij 149 . Release 1.jar and seleniumserver.Selenium Documentation.jar. 150 Chapter 11.Selenium Documentation.0 • Select both jar files in project pan and click on Apply button. Release 1. Java Client Driver Configuration . Added jars would appear in project Library as following. Configuring Selenium-RC With Intellij 151 .Selenium Documentation. 11.2. Release 1.0 • Now click ok on Project Structure followed by click on Close on Project Settings pan. 152 Chapter 11. Release 1.0 • Create the directory structure in src folder as following. Java Client Driver Configuration .Selenium Documentation. Selenium Documentation.2.0 Note: This is not hard and fast convention and might very from project to project. 11. Hence extended structure would look as following. • Herein core contains the SelTestCase class which is used to create Selenium object and fire up the browser. Configuring Selenium-RC With Intellij 153 . testscripts package contains the test classes which extend the SelTestCase class. Release 1. Java Client Driver Configuration . Release 1.0 154 Chapter 11.Selenium Documentation. Run the installer downloaded (ActivePython-x. • Installing Python Note: This will cover python installation on Windows and Mac only.mhtml 2.x. (even write tests in a text processor and run them from command line!) without any extra work (at least on the Selenium side). Download Active python’s installer from ActiveState’s official site:. • Add to your test’s path the file selenium. After following this.CHAPTER TWELVE PYTHON CLIENT DRIVER CONFIGURATION • Download Selenium-RC from the SeleniumHQ downloads page • Extract the file selenium.x. – Windows 1.com/Products/activepython/index. the user can start using the desired IDE.py • Run Selenium server from the console • Execute your test from a console or your Python IDE The following steps describe the basic installation procedure.x-win32-x86.py • Either write your Selenium test in Python or export a script from Selenium-IDE to a python file. as in most linux distributions python is already pre-installed by default.msi) 155 . 0 • Mac The latest Mac OS X version (Leopard at this time) comes with Python pre-installed. To install an extra Python.5.org/ (packages for Python 2. Python Client Driver Configuration .x). Release 1.pythonmac. 156 Chapter 12. get a universal binary at Documentation. Release 1. it’s located inside seleniumpython-driver-client.pkg file that you can launch. It contains a . Congratulations. you’re done! Now any python script that you create can import selenium and start interacting with the browsers.py) in the folder C:/Python25/Lib (this will allow you to import it directly in any script you write).0 You will get a . You will find the module in the extracted folder. Download the last version of Selenium Remote Control from the downloads page 2. • Installing the Selenium driver client for python 1.Selenium Documentation. Copy the module with the Selenium’s driver for Python (selenium. Extract the content of the downloaded zip file 3.dmg file that you can mount. 157 . Release 1.Selenium Documentation.0 158 Chapter 12. Python Client Driver Configuration . • XPath: //div[contains(@class. For example. however with CSS locators this is much simpler (and faster).3 contains If an element can be located by a value that could be surrounded by other text.CHAPTER THIRTEEN LOCATING TECHNIQUES 13. Useful for forms and tables.1 Useful XPATH patterns 13.1 Locating elements based on class In order to locate an element based on associated class in XPath you must consider that the element could have multiple classes and defined in any order.1 text Not yet written .1. if your dynamic ids have the format <input id="text-12345" /> where 12345 is a dynamic number you could use the following XPath: //input[starts-with(@id.4 siblings Not yet written .locate elements based on the text content of the node.1.1.locate elements based on their siblings.2 starts-with Many sites use dynamic values for element’s id attributes. To demonstrate. the contains function can be used. ’text-’)] 13. ’article-heading’)] 159 . this would be much neater (and probably faster) using the CSS locator strategy css=span..2 Starting to use CSS instead of XPATH 13. One simple solution is to use XPath functions and base the location on what you do know about the element. Incidentally. ’heading’)]. 13. 13.2.1.heading 13. Locating Techniques .0 • CSS: css=div.Selenium Documentation. Release 1.article-heading 160 Chapter 13. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue listening from where you left off, or restart the preview.
https://www.scribd.com/document/55337965/Selenium-Documentation
CC-MAIN-2016-36
refinedweb
34,417
52.15
JavaScript JavaScript Pivot Table can be connected to an OLAP cube, and its result can be visualized in both tabular and graphical formats. Binding the JavaScript JavaScript JavaScript transform the appearance of the actual cell value. The Pivot Table control automatically groups dates and numbers, so the date type can be formatted and displayed based on year, quarter, month, day, and more. The number type can be grouped by range, such as 1-5 or 6-10. You can freeze row and column headers to JavaScript Pivot Table data to Excel, PDF, and CSV formats. You can also customize the exported document by adding header, footer, and cell properties like type, style, and position programmatically. Ships with a set of four stunning, built-in themes: Material, Fabric, Bootstrap, Tailwind CSS, and High Contrast. You can customize the appearance of the control as little or as much as you like be displayed from right to left. You can localize all the control’s strings in the user interface as needed and use the localization (l10n) library to do so. For a great developer experience, flexible built-in APIs are available to define and customize the JavaScript Pivot Table control. Developers can optimize the data bound to the control and customize the user interface completely using code with ease. JavaScript JavaScript Pivot Table (Pivot Grid) using a few simple lines of HTML and TS code, as demonstrated below. Also explore our JavaScript Pivot Table Example that shows you how to render and configure the Pivot Table in JavaScript. <html> <head> <link href="" rel="stylesheet"> </head> <body> <div id="PivotView"> </div> </body> </html> import { PivotView, IDataSet } from '@syncfusion/ej2-pivotview'; let pivotObj: PivotView = new PivotView({ dataSourceSettings: { columns: [{ name: 'Year' }, { name: 'Quarter' }], values: [ { name: 'Sold', caption: 'Units Sold' }, { name: 'Amount', caption: 'Sold Amount' } ], dataSource: getPivotData(), rows: [{ name: 'Country' }, { name: 'Products' }] }, width: '100%', height: 290 }); pivotObj.appendTo('#PivotView'); function getPivotData() : IDataSet[] { let pivotData: IDataSet[] = [ { Sold: 31, Amount: 52824, Country: 'France', Products: 'Mountain Bikes', Year: 'FY 2015', Quarter: 'Q1'}, { Sold: 51, Amount: 86904, Country: 'France', Products: 'Mountain Bikes', Year: 'FY 2015', Quarter: 'Q2'}, { Sold: 21, Amount: 33505.5, Country: 'Germany', Products: 'Touring Bikes', Year: 'FY 2015', Quarter: 'Q1'}, { Sold: 74, Amount: 126096, Country: 'Germany', Products: 'Mountain Bikes', Year: 'FY 2015', Quarter: 'Q1'}, { Sold: 77, Amount: 131208, Country: 'United Kingdom', Products: 'Mountain Bikes', Year: 'FY 2015', Quarter: 'Q1'}, { Sold: 92, Amount: 156768, Country: 'United Kingdom', Products: 'Mountain Bikes', Year: 'FY 2015', Quarter: 'Q2'}, { Sold: 43, Amount: 73272, Country: 'United States', Products: 'Mountain Bikes', Year: 'FY 2015', Quarter: 'Q1'}, { Sold: 43, Amount: 73272, Country: 'United States', Products: 'Mountain Bikes', Year: 'FY 2015', Quarter: 'Q2'} ]; return pivotData; } The Pivot Table component is also available in Blazor, React, Angular, and Vue frameworks. Check out the different Pivot Table platforms from the links below, We do not sell the JavaScript Pivot Table separately. It is only available for purchase as part of the Syncfusion JavaScript suite, which contains over 70 JavaScript components, including the Pivot Table. Pivot Table, are not sold individually, only as a single package. However, we have competitively priced the product so it only costs a little bit more than what some other vendors charge for their Pivot Table.
https://www.syncfusion.com/javascript-ui-controls/js-pivot-table
CC-MAIN-2022-27
refinedweb
531
53.55
SYNOPSIS #(); $class->load(); DESCRIPTIONClass APITo $classT nameThe c<name> method returns the name of the class as original specified in the constructor. VERSIONFind the version for the class. Does not check that the class is loaded ( at this time ). Returns the version on success, "undef" if the class does not defined a $VERSION or the class is not loaded. isa $classChecks to see if the class is a subclass of another class. Does not check that the class is loaded ( at this time ). Returns true/false as for "UNIVERSAL::isa" can $methodChecks to see if a particular method is defined for the class. Returns a "CODE" ref to the function is the method is available, or false if the class does not have that method available. installedChecksChecksReturns the base filename for a class. For example, for the class "Foo::Bar", "loaded" would return "Foo/Bar.pm". The "filename" method is platform neutral, it should always return the filename in the correct format for your platform. resolved_filename @extra_pathsTIf the class is loaded, returns the name of the file that it was originally loaded from. Returns false if the class is not loaded, or did not have its own file. functionsReturnsReturns a list of references to all the functions in the classes immediate namespace. Returns a reference to an array of CODE refs of the functions on success, or "undef" on error or if the class is not loaded. function_exists $functionChecksAttempts. subclassesTThe "super_path" method is a straight pass through to the "Class::ISA::super_path" function. Returns an ordered list of class names, with no duplicates. The list does NOT include the class itself, or the UNIVERSAL class. self_and_super_pathAs above, but includes ourself at the beginning of the path. Directly passes through to Class::ISA. full_super_pathThe No known bugs. Additional feature requests are being taken. SUPPORTBugs should be reported via the CPAN bug tracking system <> For other inquiries,.
https://manpages.org/classhandle/3
CC-MAIN-2022-05
refinedweb
315
66.44
Tuesday, March 25, 2008 #." T!) Monday, February 04, 2008 # (It has links to things such as the C# language specification and a reference guide to the CIL Instruction Set). Thursday, January 24, 2008 # Monday, November 12, 2007 # Many antivirus programs are still susceptible to this evasion technique: Original post: News article: Tuesday, October 30, 2007 # Default get/set accessors: public class Person { public string Name { get; set; } public int Age { get; set; } } Property initialization: Person author = new Person { Name = "Jay Miller", Age = 40 }; From this article: Monday, August 06, 2007 # Here is a pretty good introductory article on crypto in .NET:. Tuesday, July 24, 2007 # I know that I'm going to be looking for this article later so I might as well share it here:. It has some useful PDF utilities as well as others. Wednesday, July 18, 2007 # Here are a few goodies I came across for Office Word 2007... Want help getting started with Word 2007? Add the "Getting Started" ribbon tab inside of Word: Having trouble with the new Word ribbon (menu) system? Use this interactive guide to help with the transition from the previous menu system to the current ribbon system: What to save Office documents in the PDF format? Get the free plug-in: Friday, July 06, 2007 # This! Friday, June 29, 2007 # A few good write-ups on performance: Friday, June 22, 2007 # Tuesday, June 12, 2007 # I just got done with a long afternoon of implementing a Windows Service to self-host my WCF service. It was a bit trickier than I thought it would be so if I can save you the headache I'll be happy. A good place to start is by reading these two MSDN articles: Next, you'll want to understand these support articles: (I needed this to get the wsdl stuff working) (need to do this before TcpNetBinding will work) (an example app hosting WCF) (more on self-hosting) Thursday, June 07, 2007 # Examples of Traditional Software Development Methodologies Waterfall Spiral Rational Unified Process (RUP) CMMI Examples of Agile Software Development Methodologies Extreme Programming Scrum Lean Software Development Feature Driven Development (FDD) Dynamic Systems Development Method (DSDM) A: &) Wednesday, June 06, 2007 # WebDAV & IIS--A remote file access solution to consider:. Tuesday, May 29, 2007 # I) Monday, May 14, 2007 # This article reviews three open-source web service testing tools that might be useful if you don't already have one:. Tuesday, April 17, 2007 # Tuesday, April 10, 2007 # Here is a nice overview of the web server usage statistics from the April 2007 Netcraft survey:. It shows an already widely-used and gaining in popularity web server called lighttpd that is being used for static content serving in some large-scale scenarios like YouTube and Wikipedia. Thursday, April 05, 2007 # Wednesday, April 04, 2007 # Monday, March 19, 2007 #. This article proposes some great ways of making common sequences of operations on lists more reusable in .NET:. It reminds me of some of the built-in set operations that are available in the SmallTalk programming language. Monday, March 05, 2007 # Skin design by Mark Wagner, Adapted by David Vidmar
http://geekswithblogs.net/devdevin/Default.aspx
crawl-002
refinedweb
523
54.05
Hi, When I try to run the practice code from the boost python tutorial in Eclipse's PyDev environment , I get the following error Despite including the path to that file in the environment variable LD_LIBRARY_PATH.Despite including the path to that file in the environment variable LD_LIBRARY_PATH. I also copied the libboost_python.so.1.52.0 file in the same working directory of my python program Also I included the path to the file in Eclipse's Linked resources property field, same error This is the tutorial code I'm using Code:char const* greet() { return "hello, world"; } #include <boost/python.hpp> BOOST_PYTHON_MODULE(libhelloext) { using namespace boost::python; def("greet", greet); } Eclipse code Tried this tooTried this tooCode:import libhelloext print hello.greet() Machine: Unix, boost 1.52, python 2.7Machine: Unix, boost 1.52, python 2.7Code:from libhelloext import * print hello.greet() Any suggestion? please
http://forums.devshed.com/python-programming-11/boost-python-eclipse-pydev-937550.html
CC-MAIN-2015-11
refinedweb
148
59.8
MIDI volume control difficulties Greg Donahue Greenhorn Joined: Oct 07, 2003 Posts: 24 posted Dec 31, 2004 07:26:00 0 Hi there, I'm writing a simple MIDI player to teach myself how to use the javax.sound.midi package. So far, I have a basic program that can play, pause, stop, open a new MIDI sequence, and display file information (name and length in minutes:seconds). I'm having a hard time getting the volume control to work, though. I have googled extensively on this. The conventional wisdom seems to be that you control MIDI volume by instantiating and opening a Sequencer, instantiating and opening a Synthesizer, binding the Synthesizer to the Sequencer via a Transmitter/Receiver pair, setting your Sequence, starting your Sequencer, and collecting the MidiChannels via a call to the Synthesizer, then doing a controlChange of controller #7 (major volume control) on each channel. It's easier to see what's going on by looking at the code; this method should turn all channels on the synthesizer down to zero: public static void main(String[] args) throws Exception {("./foo.mid"))); sequencer.start(); MidiChannel[] channels = synthesizer.getChannels(); for (int i = 0; i < channels.length; i++) channels[i].controlChange(7, 0); } The effect of this code is that the volume of the playing synthesizer is indeed lowered, but not silenced. This is driving me up the wall; I'm not a MIDI guru, so I don't know what I'm missing, and reading the specs isn't helping. Some caveats: 1) Apparently, MIDI controller 39 is another volume controller (the least significant 7 bits of the volume control for the channel) but when you reset controller 7, you also zero out controller 39. 2) I have tried rearranging the instructions in the above code, to see if I was doing something in the wrong order. Nothing helped. 3) I tried setting controller 7 to -1, thinking that maybe MIDI works differently on my machine than everywhere else in the universe. It raised the volume to the maximum value, an earsplitting 127. 4) It's almost as if there are two sound-generating elements here, the Synthesizer I'm using and something else which the Synthesizer can't touch. Calls to setMute() and allNotesOff() don't work, either. 5) Another way to make this work is to go into the Sequence and change the volume of every single MidiMessage individually. I won't do this, it's too slow. I want my volume to change in real time, as the user drags the volume slider up and down. 6) Another caveat: I did the obvious check. I added the following code, which checks each channel's controller #7, to the above: for (int i = 0; i < channels.length; i++) System.out.println(channels[i].getController(7)); ...and each channel is indeed set to zero. Any ideas? Thanks! -Greg [ December 31, 2004: Message edited by: Greg Donahue ] vi veri veniversum vivus vici Greg Donahue Greenhorn Joined: Oct 07, 2003 Posts: 24 posted Dec 31, 2004 08:48:00 0 Okay, I figured it out. I looked at the MidiDevices obtained from calling MidiSystem.getMidiDeviceInfo(), and observed that they were all closed. So I knew right away that something was fishy. I guess that calling MidiSystem.getSequencer() and MidiSystem.getSynthesizer() doesn't give you the default objects for those MIDI devices. To correct the problem, I had to set the sequencer and synthesizer to the default sequencer and synthesizer in the MidiDevice.Info list, rather than using MidiSystem.getSequencer() and MidiSystem.getSynthesizer(). It looks like: ... //--This tells you what your MidiDevices are MidiDevice.Info[] info = MidiSystem.getMidiDeviceInfo(); for (int i = 0; i < info.length; i++) System.out.println(info[i].getName()+"\t\t\t"+mdev.isOpen()); ... //--This sets the Sequencer and Synthesizer //--The indices x and y correspond to the correct entries for the //--default Sequencer and Synthesizer, as determined above Sequencer sequencer = (Sequencer) MidiSystem.getMidiDevice(info[x]); Synthesizer synthesizer = (Synthesizer) MidiSystem.getMidiDevice(info[y]); ...and that did the trick. Now my volume works perfectly. -Greg uvaraj Selvaraj Greenhorn Joined: Sep 16, 2010 Posts: 1 posted Sep 16, 2010 13:49:20 0 Hi, I tried as you have explained.But I am not able to increase/Decrease the MIDI volume. Please let me know where I am going wrong. import java.io.File; import javax.sound.midi.MidiChannel; import javax.sound.midi.MidiDevice; import javax.sound.midi.MidiSystem; import javax.sound.midi.Receiver; import javax.sound.midi.Sequencer; import javax.sound.midi.Synthesizer; import javax.sound.midi.Transmitter; public class Main { public static void main(String[] argv) throws Exception { MidiDevice.Info[] info = MidiSystem.getMidiDeviceInfo(); for (int i = 0; i < info.length; i++) System.out.println(info[i].getName()+"\t\t\t"); // mdev.isOpen() Sequencer sequencer = (Sequencer) MidiSystem.getMidiDevice(info[2]); Synthesizer synthesizer = (Synthesizer) MidiSystem.getMidiDevice(info[3]); //("c:/1.mid"))); sequencer.start(); MidiChannel[] channels = synthesizer.getChannels(); for (int i = 0; i < channels.length; i++) channels[i].controlChange(-1, 0); Howard Amos Greenhorn Joined: Aug 16, 2012 Posts: 1 posted Aug 16, 2012 17:06:07 0 I had the same problems. Upon investigation I concluded that for me (on Mac OS X, java 1.6.0_33-b03-424-10M3720) MidiSystem.getSynthesizer did *NOT* return the same synthesizer that the sequencer was by default connected to. The sequencer is already connected to *A* synthesizer. If you do a getSynthesizer and connect it up then your sequencer will drive *TWO* synthesizers. You can test this by calling sequencer.getTransmitters and looping through the list (of transmitters open and in use). I suggest that this is why setting volume to zero reduces the volume but doesn't shut it off completely! Of course different java environments might behave differently. Possible solutiona: 1 (the one I used) Don't use the synthesizer object because you can't get to it (but see solution 2). Don't use Channels. To control volume use: receiver = seq.getTransmitters ().iterator ().next ().getReceiver (); receiver.send (volumeMessage, -1); This is of course suitable for both software and hardware synth so should simplify the code. 2 (not tested) Use getSynthesizer and connect transmitter and receiver as lots of sample code tells you, BUT do something like: seq.getTransmitters ().iterator ().next ().close () to shut down the default synthesizer started for you. Then with any luck you can get the channels and the sample code might work. I agree. Here's the link: subject: MIDI volume control difficulties Similar Threads JMF and Java Sound at same time? How to measure the Frequency/Pitch/Note of a Midi File? MIDI MIDI Volume Mystery MIDI problems when launching applet through browser All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/272584/java/java/MIDI-volume-control-difficulties
CC-MAIN-2014-41
refinedweb
1,125
50.63
Wildcard Subscribe introduces the ability to add namespaces to channels. Wildcarding is supported up to three levels deep. So you can subscribe to: but you cannot subscribe to ‘*.’, ‘a.b.c.*’ nor just ‘*’. For example, if you need to subscribe to every device in San Francisco or California, you can save yourself from providing a lengthy delimited list of every channel by instead subscribing to ‘california.*’ or ‘california.sanFrancisco.*’. This feature must explicitly be turned on in your PubNub Admin Dashboard. For further learning, please see: We have a Beta version of our new Debug Console available to try, would you like to check it out?
https://www.pubnub.com/developers/tech/key-concepts/stream-controller/wildcard-subscribe/
CC-MAIN-2019-30
refinedweb
106
54.02
C++ <list> - resize() Function The C++ list::resize function is used to resize the container by specified number of elements (n). If n is less than the current list size then the content is reduced to the first n elements of the list. If n is greater than the current list size, then the new elements are inserted at the end of the list. If val is specified, then new elements are initialized with val, else they are value-initialized. Syntax void resize (size_type n, value_type val = value_type()); void resize (size_type n); void resize (size_type n, const value_type& val); Parameters Return Value None. Time Complexity Linear i.e, Θ(n). Example: In the example below, the list::resize function is used to resize the list called MyList. #include <iostream> #include <list> using namespace std; int main (){ list<int> MyList{10, 20, 30, 40, 50}; list<int>::iterator it; //size of the list is reduced to 3 MyList.resize(3); //size of the list is expanded to 5 with val=100 MyList.resize(5, 100); //size of the list is expanded to 8 MyList.resize(8); cout<<"MyList contains: "; for(it = MyList.begin(); it != MyList.end(); it++) cout<<*it<<" "; return 0; } The output of the above code will be: MyList contains: 10 20 30 100 100 0 0 0 ❮ C++ <list> Library
https://www.alphacodingskills.com/cpp/notes/cpp-list-resize.php
CC-MAIN-2021-43
refinedweb
221
71.44
Testing. Note: See New features and storage options in Red Hat Integration Service Registry 1.1 GA for more about Red Hat Integration and the Service Registry component. Overview of Apicurio Registry and the test setup Apicurio Registry manages artifacts such as API definitions or data structure schemas like Apache Avro, which we used for these tests. As a developer, you can use API definitions and data structure schemas across your asynchronous messaging applications to validate the messages they’re producing and consuming. Apicurio Registry helps you decouple the structure of your data from your applications. Figure 1 shows a typical workflow with Apicurio Registry and Kafka. The most common operation within a schema registry is a simple GET request to its API to retrieve a given schema’s latest version. Changing or updating the schema happens less frequently. As a result, the calls we used in our testing are fairly simple: - List all of the artifacts: GET <registry_host>/api/artifacts. (Note that there is no pagination. Use searchif needed.) - Get the latest version of a schema: GET <registry_host>/api/artifacts/<artifact_id>. - Create a new schema with JSON data: POST <registry_host>/api/artifacts. - Add a new version of a schema with JSON data: PUT <registry_host>/api/artifacts/<artifact_id>. - Delete a schema: DELETE <registry_host>/api/artifacts/<artifact_id>. Note: When using Apache Kafka to transfer Avro messages, the default Apicurio Registry client libraries don’t load the Avro schema on every request. They only load schemas on application startup (or, for consumers, when a schema changes), so registry performance does not affect the speed of producing and consuming messages. Performance testing Apicurio Registry Our performance tests were basic, but each step contained multiple variants to catch various Apicurio Registry configurations: - Clean up the registry database for a clean starting point. - Populate the registry with a given number of schemas. - Flood the registry with GETrequests for the latest version using random schema from those created in the previous step. How we tested We used a Python script to generate a load of GETs to the registry, and we used Locust as our load testing tool. This setup might be overkill for our use case, where we’re calling just one endpoint with a random schema ID, but it is a good test setup in general. We use Locust as a library in our custom locust.py tool. Our custom tool has the added benefit of generating JSON files with the results and additional data that you can easily analyze later. Using Locust’s default command-line interface tool would also work here. Our deployment environment was Red Hat OpenShift 4 cluster running on Amazon Web Services Elastic Compute Cloud. We conducted some of our tests using an installation created by an Apicurio Registry Operator; other tests were conducted as custom deployment configurations for more control. Both the PostgreSQL database and load generation scripts could run in a pod in the same cluster. To monitor our pods, we used data from OpenShift’s Prometheus in the openshift-monitoring namespace. Scaling the Locust script horizontally Scaling the Locust script was one of the issues we had to solve during testing. When we raised the registry pod’s CPU resources, we noticed an upper limit of about 925 requests per second. This indicated the application was scaling past two CPUs, which was unexpected. When we monitored the data, it didn’t indicate that the resources were saturated on the registry or on the database, so we scaled the test script horizontally to distribute the load to more pods. When we scaled the script horizontally, we were able to generate many more requests. Figure 2 shows the flow for scaling the Locust script horizontally. Figure 2: Horizontally scaling the Locust script allows for more requests to the system under test. Figure 3 shows the requests per second (RPS) for different CPU resources with one Locust follower node. Figure 3: Requests per second for different CPU resources with one Locust follower node. Figure 4 shows the requests per second after scaling for 10 Locust follower nodes. Figure 4: Requests per second for different CPU resources with 10 Locust follower nodes. Conclusion We found the following results from testing Apicurio Registry’s performance and scalability: - Apicurio Registry works consistently and isn’t affected by the number of artifacts it has in the database. We tested the registry with one million schemas, each with 10 versions and each version with 345 bytes of serialized JSON on average. - Apicurio Registry’s performance grows linearly as we allocate more CPU resources to it. - Apicurio Registry’s performance grows linearly as more registry pods are started. We tested 10 pods, which provided schemas at a rate of 4,201 requests per second. We conclude that Apicurio Registry is capable of handling a wide range of deployments. We can always test more, but the current results show that Apicurio Registry with a PostgreSQL storage backend is a good option for future deployments.
https://developers.redhat.com/blog/2021/04/05/testing-apicurio-registrys-performance-and-scalability/
CC-MAIN-2021-21
refinedweb
828
54.22
proper sorting of pointed Hebrew texts Project description a simple script to sort Hebrew words with vowels and accents according to their lexical order (which differs from the unicode point order or even the locale’s collation string) From the docstring: Module for properly sorting Hebrew words with niqqud – according to consonants first and vowels later. If run from the command line, takes a file with a list of words as input or reads lines from stdin. disclaimer: there is no universal method for the ordering of Hebrew vowels. The order used by this module is:Sheva, Hataf Segol, Hataf Patah, Hataf Qamets, Hiriq, Tsere, Segol, Patah, Qamets, Holem, Holem Vav, Qibbuts, Shureq This order may seem foreign to those accustomed to Latin-based languages, but it was recommended to me by the Academy for the Hebrew Language in Israel, and it is very similar to orders use by Unicode and standard Israeli keyboard layouts. It is also more “scientific” in the sense that it follows a phonological pattern (horizontal to vertical vowels), rather than a traditional, Latin-based pattern (aeiou). This does differ from the one convention common in Israeli works, in that it treats Sin as a separate letter from Shin. This is not especially common in Israel, but it is the convention in all of the widely used Biblical lexicons and other Western Biblical scholarship. I do this both because it would be pedagogical malpractice to give my students glossaries that differ in this regard from the works they will be using later, and because it is more accurate from the perspective of historical linguistics. I would probably revise this approach if this sort engine were targeted at modern Hebrew. Usage At the command line: $ cat wordlist.txt | ivsort ... $ ivsort wordlist.txt So it can read from a file or from STDIN, so as to be useful for text editors that can use shell commands as filters (like all of them that matter). It is basically how sort works. As a Python3 module: from ivsort import ivsort sorted_list = ivsort(unsorted_iterable) You probably aren’t going to want to muck around with the other functions this script provides. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/ivsort/
CC-MAIN-2021-25
refinedweb
389
54.26
Creating a Basic Data Grid Flex provides an <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns: <mx:DataGrid></mx:DataGrid> </mx:Application> The basics of a Flex application are present: the XML DTD, namespace attribute and the <mx:Application> tag. Most importantly for this lesson, you also see the DataGrid tag. If you compile and run this program you will see the following: What you see is a DataGrid with no header and no data items. It is very basic so far. Before we continue on to spruce up this DataGrid, let’s make it expand to the width our browser. By doing this, when we re-size our window, the datagrid will grow to the width and height of the web browser. Here is an updated version of the DataGrid tag with our size attributes added: Try resizing your window to see the effects of our changes. Setting the width and height to "100%" tells Flex that this component should grow as large as it possibly can with reference to its parent container. In this case, the parent is the application, which also takes up as much real estate as possible. {mospagebreak title=Adding Data} Now that our basic DataGrid is showing, let’s add some data. The pure MXML way of doing this is to add a <mx:dataProvider> tag followed by an XML, XMLList, or Array Collection tag. Using a data provider is how Flex connects the UI control with the data being displayed in the UI control. I liken it to having a television in your home. The television serves as the UI component, much like the DataGrid. However, it is useless unless there is a signal telling it what to display. The signal for television is a cable/broadcast signal, while the signal for our DataGrid is the data provider. Having a DataGrid alone does us no good if we can’t add data to it. Flex gives a few different options for how to use a data provider, but in this article I use the XMLList. > The above XMLList describes two people with first and last names and their birth dates. We will tell our DataGrid to display the name and birthday of each person found in XMLList. Listing x.x shows the addition of the XMLList in green, along with two new tags called <mx:DataGridColumn> and <mx:columns> listed in blue. <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns: <mx:DataGrid<mx:columns> <mx:DataGridColumn <mx:DataGridColumn <mx:DataGridColumn </mx:columns><mx:dataProvider> > </mx:dataProvider></mx:DataGrid> </mx:Application> Let’s first take a look at the <mx:columns> tag and its children. <mx:columns> <mx:DataGridColumn <mx:DataGridColumn <mx:DataGridColumn </mx:columns> The DataGridColumn has the job of naming the columns of the DataGrid and telling it where in our XMLList to retrieve the data for its column. In our case, the dataField attribute is assigned ‘firstName’, ‘lastName’, and ‘birthday’ respectively. If the XML in the XMLList is properly built, the DataGrid will have no problem finding the data you wish to place in its column, based on the dataField. Note, the DataGridColumn tags are children of the the <mx:columns> tag. If you compile and run this application, you’ll get the following: Well, that is all we need to produce a basic DataGrid with XML data. For the remainder of this article I’ll mention some variations on the basic DataGrid that will help in your own programming. {mospagebreak title=Customizing the Column Headers} Our current DataGrid uses the "of" dataField to name the columns. This may work in many cases, but you’ll probably want to name your columns something that may be more descriptive or concise. To modify the column headers, you’ll want to use the ‘headerText’ attribute of the DataGridColumn. So, to set our column names to ‘First Name,’ ‘Last Name’ and ‘Date of Birth,’ we’ll modify the DataGridColums to look like this: Customizing Column Widths Actionscript does the work of giving our columns a default size. Unfortunately, it has no idea of how wide the column should be in order to give the user the best view. The DataGridColumn tag once again comes to our rescue. In order to set column widths, use the ‘width’ attribute. {mospagebreak title=Hiding Columns} In certain cases, you may want to hide a DataGrid column. To do this, we use the ‘visible’ attribute of the DataGridColumn tag: Other DataGridColumn Attributes Here is a list and short description of other handle attributes of the DataGridColumn tag: - sortable - By default, clicking on the header of a column will automatically sort the DataGrid’s data provider. You can turn this function on or off by setting this attribute to true or false. - - minWidth - Sets the minimum width of the column. - - resizable - Determines whether or not a user can resize the column.
http://www.devshed.com/c/a/xml/working-with-flex-and-datagrids/1/
CC-MAIN-2014-52
refinedweb
815
61.06
. If you’d like to see a complete guide to mastering the Java language, you can check out “The Definitive Java Interview Handbook”. Today we’ll look at interview questions and answers related to: - The Java ecosystem - Java Classes - Interfaces - Inheritance - Multi-threading - Memory management - Collections - Exception handling - Serialization - Singleton Let’s get started! Q1: What is meant by Java being platform independent? Java works on the principle of write once and run anywhere. Once a Java program is written, it is compiled into what is known as byte code, which can then be run on any Java Virtual Machine or JVM for short. package private. A member marked package private is only visible within its own package. Consider the class below. // class can be accessed by other classes within the same // package but not outside of it. class IamPackagePrivateClass { int IamPackagePrivate; private int IamPrivate; public IamPackagePrivate(int a, int b) { this.IamPackagePrivate = a; this.IamPrivate = b; } } Package private is a slightly wider form of private. One nice thing about package-private is that you can use it to give access to methods you would otherwise consider private to unit test classes. So, if you use helper classes which have no other use but to help your public classes do something clients need, it makes sense to make them package private as you want to keep things as simple as possible for users of the library. inheritance. Need a refresher on multithreading? Check out this article “Java Multithreading and Concurrency: What to know to crack a senior engineering interview”.. There are many more concepts to revisit or explore like object-oriented programming, static variables, and method overloading. If you’d like to take a deep dive into Java and explore hundreds of more questions about the topics mentioned above then “The Definitive Java Interview Handbook” is going to be a great resource to get you refreshed on the core java principles — everything from the basics to more advanced functionality. Happy learning! Discussion Good summary. One small typo: in Q9, you accidentally switched to lower case for the system class (-> System). In Q3, one could argue that upper case variable names are discouraged (even though it‘s valid syntax). A good remark, I think the same goes for the stringclass. Yes. Q14: memory usage A big one in web applications is to prefer streaming over storing everything in RAM. For example: str = readEntireFileIntoString() vs outputStream.write(readAnotherLine()) Huge huge differences in RAM usage (O(N) vs O(1) ). Streaming is by far preferable. In XML for example, SAX parsers are far preferable over DOM parsers because the later store everything in RAM. If your file is huge you'll hog a lot of RAM. Another source of horror is careless use of relations in Hibernate. If you're careless you can end up storing the entire database for each object and hogging the RAM like mad. I mention these.. because sadly, I've seen them in the wild. Q15 is a trick question. The best way to implement it is: not at all. Singleton is the only design pattern which is also an anti-pattern. I often ask this question during interviews: if they know design patterns, know singleton, and what they think of it. If they don't mention it being an anti-pattern. I ask them if they can explain why I think it's an anti-pattern. The answer is rather simple. The whole purpose of a singleton is to introduce global state, and global state is bad. Well, global state appears in the real world. Like configurations files, db connection parameters, etc.. One advantage of using factory methods + singletons is that if for whatever reason you don't want it to be a singleton any more, there's no obligation that it continue to be a singleton. I'm not sure that making sure its a single instance in the VM is the most overriding principle. I haven't had much need for that guarantee. More important is the abstraction of returning an object that represents some configuration. Which over time could become several objects (for example when you make your app multi-tenant) Of course global state appears in the real world. Just like memory leaks, concurrent modifications, and a whole lot of other bad things. Configuration files and DB connection parameters do not have to be global state. You should pass them along as context or local state. Within a context (like Spring's ApplicationContext) you can have a single instance of an object. It is much like a singleton, except that it is possible to have a completely different instance of that object in a different context. Via the context you can get the proper instance of that object. Depending on a global state is also problematic with unit testing. It is simply best to avoid using singletons. However it is not always possible without creating a bigger mess. The prime example would be logging. I see. I guess that's the heart and soul of the IOC / Hollywood principle. Rather than have your methods calling global classes for something, they should have those set for them so its easier to test. Q4: avoiding finalize() Besides the issue of non-determinism of the finalize().. a bigger reason to avoid the finalize() method is that modern garbage collectors are copy collectors. Meaning that if 80% of your objects are garbage, only 20% gets processed by the system. The other 80% simply disappears with no further processing. This is a huge advantage over other schemes. Because with copy collectors processing garbage is almost free. However, if you add finalizers all over the place, then the GC needs to go through all the finalizers() hence you lose all the advantages of copy collection in terms of speed. This ends up being a huge performance hit. Q13: HashSet vs TreeSet You claim HashSet is thread safe. But the Javadocs say otherwise: (...)); " For multi-threading I highly recommend java.util.concurrent rather than synchronizedSet(). But no, its very dangerous to use HashSet in multithreaded situations. In fact, in the past there were cases where HashSet's cousin, HashMap hung even when there were only reads across threads. The main difference is that HashSets use a hash table implementation whereas the TreeSet uses some binary tree implementation. There are many differences such as the ones you mentioned. Other differences include: In practice I've used TreeSet as an alias of "ordered list with no repetitions". HashSet I've used to check what has been processed vs what still needs to be processed. But often I just end up using a Map instead. They're often more useful.
https://practicaldev-herokuapp-com.global.ssl.fastly.net/educative/java-interview-prep-15-java-interview-questions-i64
CC-MAIN-2020-45
refinedweb
1,117
65.93
With. PhpStorm uses PHPUnit as the test runner, a widely used unit testing framework for PHP which provides a lot of features. Let's see how it integrates with PhpStorm. 1. Adding a unit test to a project Adding unit tests to a project can be done in several ways. We can create a new file and select the PHPUnit | PHPUnit test file template. Another way to create a test for some specific class is to invoke use the Go to Test action (with Navigate | Go to Test or Cmd+Shift+T / Ctrl+Shift+T) and choose Create new test. Either method for creating a new test will open Create New PHPUnit Test dialog, in which we can specify the name of the class to test, the name and namespace of the test class, and where the PHP file should be saved. After clicking OK, a boilerplate unit test class will be generated. 2. Enabling PHPUnit for our project As we can see from the generated class above, there is no autocompletion support yet and PhpStorm does not know about the PHPUnit_Framework_TestCase class PHPUnit provides. Why is that? Because we haven't enabled PHPUnit yet for our project. Let's do that. We can reference PHPUnit in several ways, depending on preferences or project standards. - One approach is installing PHPUnit via Composer in PhpStorm. - Another approach is downloading PHPUnit as a PHAR file and loading the PHAR file in our unit test code. - And another approach is to install PHPUnit using PEAR but this is an obsolete option for PhpUnit < 5. For this tutorial, let's go with PHPUnit support via PHAR file. From the Settings (Preferences on Mac) | Languages & Frameworks | PHP | PHPUnit, we can specify how we want to load PHPUnit. The options presented are the same options as described above (include path, Composer or PHAR). We don't have to grab the phpunit.phar file from ourselves: we can let PhpStorm download it for us. Let's go ahead and download PHPUnit PHAR file into a root folder of our project. Optionally, we can also specify the path to a phpunit.xml configuration file, or the path to a bootstrap file (to run arbitrary PHP code before unit tests run). After closing the settings and giving IDE some time to index a new archive in a project, we now get full autocompletion support on all PHPUnit's classes and functions: 3. Running unit tests The easiest way to run PHPUnit test in PhpStorm is to right click a test file in a Project Tool window > Run 'test name'. Once run, PHPUnit run configuration will be automatically created: you can view it in Run menu > Edit configurations... . It should appear under PHPUnit node and named after a test file we've run. We can also manually create a test run configuration but that it is often too cumbersome and should be reserved for the advanced PHPUnit test configurations. Once we create a new PHPUnit run configuration (or edit existing one) we can provide details such as run configuration name, which tests should be run (all tests in a directory, a specific test class or one specific test). Adding test runner arguments or PHP interpreter options is also supported. 4. Reviewing test results We are now ready to run (or debug) our unit tests! Let's do this: just right click a PHPUnit test and select "Run 'test name' ...". This will bring up a new tool window in which test results will be displayed. The test results tool window is divided in 3 main areas: the left side allows us to filter tests or export results. The middle area shows us the raw PHPUnit output. In the right part, we can drill down through all unit tests and see which ones succeeded and which ones failed. From the test results we can also use the context menu to perform several actions, such as running one specific test or navigating to the test source code. Keep in mind that you can also debug unit tests, as well as use the techniques outlined in Profiling the Performance of PHP Applications to analyze the test run performance. Finally, you can Rerun the tests (rerunning only failed tests is also supported).
https://confluence.jetbrains.com/pages/viewpage.action?pageId=87460146
CC-MAIN-2022-40
refinedweb
707
70.43
User Name: Published: 11 Jun 2010 By: Medusa M In this article, you will learn how to bind to a method of a CLR object in WPF. For any kind of data handling tasks, you first need to have data stored somewhere so it can be retrieved. In .NET applications, a data source holds the data that can be used within your application. WPF is typically known as a technology used to create visually rich applications. WPF, however, is much more than just a rich user interface generator. Developers across the world are now employing WPF to create powerful business applications. These applications deal extensively with data in some form or the other. WPF provides strong support and powerful features for data access. WPF 4, together with the Visual Studio 2010 IDE, helps you develop data-bound applications efficiently. WPF enables you to work with various kinds of data source types such as: The Visual Studio IDE now enables you to create any of the above four data source types using a Data Source Configuration Wizard. Note that the above four types are supported only in 2010, earlier versions of the IDE supported fewer data source types. The ADO.NET Database data source type enables you to create data objects by using any one of two data models: A Dataset or an Entity Data Model. A Dataset is one of the most common data models and is used to store and retrieve data from a data source such as an SQL Server database.Depending on your requirements, you can also change the data source to an MS Access database, ODBC data source, SQL Server 3.5 Compact database, and so forth. Entity Data Model creates data classes based on the ADO.NET Entity Data Framework. You can also use data from objects in your assembly as a data source. Typically, this is a object of type user-defined class. The class defines the data that can be used by a WPF application. For example, you could have a class defining a List collection populated with strings and then using the Object option in the Choose Your Data Source Type screen of the Data Source Configuration Wizard, you can add the class as a data source. Then you can create a static resource for it using the ObjectDataProvider class in XAML and make use of this resource for data binding. Alternatively, you could directly reference the class object in code and use DataContext to bind to it, without any mention of it in XAML. ObjectDataProvider DataContext Let's see the first approach in action. We will take an example of a WPF application that will bind to a list of car manufacturers. The data source will be list and the data will be the names of the car manufacturers. Launch Visual Studio 2010 and select WPF application in the New Project dialog box. Name the project as ObjectDataSource. Drag and drop a ListBoxc control from the Toolbox. ObjectDataSource The resulting XAML code for this would be as shown: Next, we will create the class which will define the data for the data source. Select Project->Add Class and name the class file as Cars.cs. Add the following code in it. Here, we have declared a method CreateList() inside the class Cars. This method returns a generic collection of strings. Within the method, we create an instance of a List of strings named manufacturers. Then, we use a series of Add() methods to populate the List with data. The newly populated list will be returned from the method. CreateList() Cars List manufacturers Add() Now we will see how create a static resource for the class using ObjectDataProvider in XAML. The ObjectDataProvider class enables you to create your object in XAML and make it available as a binding source. It is defined in the System.Windows.Data namespace. This class provides the following properties: ConstructorParameters MethodName MethodParameters Using one or more of the above properties, you can then bind to the results of the method. Let's make use of ObjectDataProvider in our code. As you can see, we have used the MethodName property to indicate that we want to bind to the results of this method. We will now use databinding to bind to this resource and also customize the look of the ListBox using ItemTemplate and DataTemplate. We use the ItemsSource property of the ListBox to bind to the static resource. ListBox ItemTemplate DataTemplate ItemsSource If required, in addition to the above steps, you can also set the DataContext of the ListBox in code to bind to the object. Here, in the current scenario, this is optional. So far, so good. A simple example for a simple scenario. But what if your class was a bit more complex and you had to pass parameters to process the data? Let's see how we can deal with this. First, we add more spice to the class. Then we specify the MethodParameters property in XAML. The complete XAML listing is as follows: Notice that in the namespace declaration section, we have included the System namespace. System This has been done because we have used a parameter of string type. This type is not recognized by default in XAML. Hence you need to reference the assembly for it. Also, note that though we have used a single parameter in this example, you can specify any number of parameters you want. Each of the parameters must match in type to the parameters declared in the class method definition. Also, you can pass parameters of several different types together. One other property of ObjectDataProvider class that can be useful is the IsAsynchronous property. This property is used to indicate whether the object creation is to take place in a worker thread or in the active context. IsAsynchronous Though this article primarily discussed binding to methods of objects, you can also bind to constructors of objects through the ObjectDataProvider class. You can try that out yourself, the procedure for it is almost similar to that described above. In this article, you learnt how to bind to a CLR object in WPF.
http://dotnetslackers.com/articles/wpf/Data-binding-to-CLR-objects-in-WPF.aspx
crawl-003
refinedweb
1,025
64.1
Ok, thanks for the extra info, I think the main problem here is actually agreeing on exactly whats required rather than the script - hopefully we'll get there in the end! 🙂 In terms of the order number being dynamic (extracted from the Soap request), I thought that was understood - in the script sample I only hard coded it as an example i.e. def fileName = "1234.txt" //Extract this value from the request (ask if you need help) Of course this is no use in practical terms, as there will obviously be many different 'order number' values extracted from the various requests that are made to the mock. Now, just to check are you happy to extract the order number tag value from the SOAP request using Groovy script? Otherwise I can offers help on this. If you are happy to extract the order number tag, then the script will effectively match the 'order number' tag value against the file names, since the statement: File testDataFile = new File("/Users/test/$fileName") //Load file containing test data response Will not find any files if $fileName doesn't match and you'll get a blank response. So in your case, if your 'order number' tag value is ordnb you'd put something like: File testDataFile = new File("c:\Users\path\$fileName.txt") If you'd like to check whether the file exists first (matches), then you could instead do something like: ... File testDataFile = new File("/Users/test/$fileName") if (testDataFile.exists()){ //Matches, read response data from file testDataFile.eachLine {content, lineNumber -> responseFileContent.append(content) } }else{ responseFileContent="File not found!" //Or perhaps return a SOAP fault? } ... Is any of this getting closer to what you are looking for? Might have helped if I'd provided a SOAP example, rathet than this REST based one - let me know if you need that and perhaps even supply your WSDL so that I can build a Mock matching your exact case. Cheers, Rup Hi Rup, Rest does not work for me. Please provide Soap groovy script. I have attached sample WSDL here. in that salesOrderNumber is the dynamic value which corresponding mock response need to be loaded. sample request is also attached.> /* If you already have all the directory structure of the project * defined(in cvs, svn etc) and can't change as mentioned in the above script * you may use below one which uses the location of respones as project property, * say define a project custom property MOCK_RESPONSES_LOCATION and set the path * in unix style ('/' as path separator) even on windows. Of course, you may use at test suite, or * testcase level property too if you wish. * soapFault.xml is need here too in case of failure. */ def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context) def holder = groovyUtils.getXmlHolder(mockRequest.requestContent) def soNumber = holder.getNodeValue("//*:BillingOrderLoadRequest/*:salesOrderNumber") def project = mockResponse.mockOperation.mockService.project def responseLocation = project.getPropertyValue('MOCK_RESPONSES_LOCATION') def file = new File("${responseLocation}/${soNumber}.xml") def fileToLoad = 'soapFault' if (file.exists()) { fileToLoad = soNumber } context.content = new File("${responseLocation}/${fileToLoad}.xml").text Hi Rao, Thanks a lot for script. Can you please modify the script bit to include the external path instead of Soap project path ? Because I need to fetch the mock response files from external path. Also I am not using any external property.xml to include the predifined properties. So the second script you provided, I cannot use. I am creating an external path C:Users\mockResponse path to store mockresponse and Fault.xml Hi Rao, can you give similar example for rest mocking(.json) too please , similar to soap which you had suggested above
https://community.smartbear.com/t5/SoapUI-Open-Source/How-to-get-soap-mock-response-from-external-file/td-p/110795/page/2
CC-MAIN-2021-21
refinedweb
603
58.28
JScript .NET, Part X: Displaying Information: Using System.Windows.Forms.MessageBox - Doc JavaScript JScript .NET, Part X: Displaying Information Using System.Windows.Forms.MessageBox You probably know well the alert() method you use so often in client-side JavaScript code. The alert() method is great for debugging scripts the good old-fashioned way--tracing variables by displaying their values along the flow. JScript .NET provides similar capabilities via the System.Window.Forms.MessageBox.Show() method. You pass this method a single argument, a string, and it pops up a window displaying this string and an OK button. The message box is called modal. A window or a form is modal if it retains the focus until you explicitly close it. It's a common practice to make dialog boxes and messages modal, since you want to make sure the user reads the message before he or she continues working with the application. The show() method belongs to the class MessageBox, of the System.Windows.Forms namespace. Import this namespace before you work with the MessageBox class, so you don't have to specify the fully-qualified name. As System.Console are available only from JScript .NET code that is compiled and run from the command line, so is the System.Windows.Forms namespace. It is not available from ASP.NET pages or from Code Behind JScript .NET code. The following code greets the user and asks him or her to press the OK button on two consecutive message boxes: import System.Windows.Forms; System.Windows.Forms.MessageBox.Show ("Hello! Press the OK button"); MessageBox.Show("Doing fine! Now press the button again."); The following command-line window shows the code listing, the compilation command of this code ( col116ex4.js), the execution command, and the first message box that pops up. The second command-line window below shows the second message box that pops up after the user clicks the OK button on the first message box. Next: How to use <%= %> Produced by Yehuda Shiran and Tomer Shiran Created: August 12, 2002 Revised: August 12, 2002 URL:
http://www.webreference.com/js/column116/4.html
CC-MAIN-2015-27
refinedweb
346
66.13
I. Anyhow, I needed to display an error message to the user as popup window, or at least this is the requirement of the project that I'm working on. To display the above error message you just need to add <nw:ErrorPopUp</nw:ErrorPopUp> This control leverages the Modal Popup control which is part of the AJAX Controls Toolkit. The ErrorPopup control is highly configurable in which you can change the look and feel, behavior and a lot's of things. For example when you want to show the error message all you need to do is to set the property Show to 'true' or invoke the ShowControl() method to display the error window. In the attachment you will find the control source-code, and demo web app. The control is written in separate DLL, all related JS, CSS styles and images are embedded in that dll so you can easily add it to your web project. Hope this helps Sorry but where's the attachment? Sorry,I find it! thanks. Hi Webdiyer, It's there mate. look under the statement "Hope this helps" can not you see it!! Good luck Nice! I was just preparing to "roll my own" for something similar, and this should save me some time. Thanks for sharing. Hi Joshua Stengel, I'm very glad you find it useful :) Last time I blogged about how to display a nice error message to the user using only one line of declarative Pingback from ?????????? ?????? ???? AJAX « ???????? web.config Add this assembly code <pages> <controls> <add tagPrefix="nw" namespace="ErrorPopup" assembly="ErrorPopup"/> </controls> </pages> Thank you for sharing! Nice, easy to use control. It is great that folks like you take the time to help the rest of us! Bill
http://weblogs.asp.net/nawaf/archive/2008/10/02/display-a-nice-error-popup-window.aspx
crawl-002
refinedweb
292
71.75
In addition to releasing the Resource Menu Component, we've also created an ActionScript object which loads the Macromedia XML Resource feed, making it available as a XML object and a DataProviderClass. Since the Resource Menu Component can use a Data Provider Class to get data, this object can be used in conjunction with the Resource Menu Component to easily add the Macromedia XML Resource feed to your own site. Note: Once the Resource Menu Component is installed, a help file for the component is available in Macromedia Flash MX (Window > Resource Menu Help). To use the ActionScript object, place a copy of the FResourceFeed.as file in the same directory as the FLA file that the object will be used in. Then include the AS file in the code for the FLA as shown below. FResourceFeed.as Here is an example of the ActionScript code necessary to load the Macromedia XML Resource feed and then display it in the Resource Menu Component: #include "FResourceFeed.as" var rf = new FResourceFeed(); rf.onXML = function() { rMenu.setDataProvider(this.getDataProvider()); } rf.load(""); rMenu is an instance of the component in the movie, and FResourceFeed is the ActionScript object (which you can download above) to load the XML Feed. rMenu FResourceFeed Since a Macromedia Flash movie running in a web browser cannot load data from a domain outside its own, some middleware is required to pass the XML to the SWF. The SWF file could then load the XML from the middleware and not from the Macromedia domain. The middleware retrieves the XML from Macromedia website and returns it to the SWF. Here is an example of the code: #include "FResourceFeed.as" var rf = new FResourceFeed(); rf.onXML = function() { rMenu.setDataProvider(this.getDataProvider()); } rf.load("xml_feed_proxy.cfm"); xml_feed_proxy.cfm is a very simple ColdFusion page which is included in the download and has the following code: xml_feed_proxy.cfm <cflocation url=""/> Pretty simple. Of course, the same technique could be used with Java, JSP, ASP, PHP, or just about any other middleware language. To see live examples of the Macromedia XML Resource feed in action, check out this week's Logged In article. For more information about the XML feed itself, see Macromedia Developer Center XML Resource feed. Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy (updated 07-08-2008). Search powered by Google™
http://www.adobe.com/devnet/flash/articles/resource_component.html
crawl-002
refinedweb
397
63.39
3. Money Types¶ Until django-SHOP version 0.2, amounts relating to money were kept inside a Decimal type and stored in the database model using a DecimalField. In shop installations with only one available currency, this wasn’t a major issue, because the currency symbol could be hard-coded anywhere on the site. However, for sites offering pricing information in more than one currency, this caused major problems. When we needed to perform calculations with amounts that have an associated currency, it is very common to make mistakes by mixing different currencies. It also is common to perform incorrect conversions that generate wrong results. Python doesn’t allow developers to associate a specific decimal value with a unit. Starting with version 0.9, django-SHOP now is shipped with a special factory class: 3.1. MoneyMaker¶ This class can not be instantiated, but is a factory for building a money type with an associated currency. Internally it uses the well established Decimal type to keep track of the amount. Additionally, it restricts operations on the current Money type. For instance, we can’t sum up Dollars with Euros. We also can’t multiply two currencies with each other. 3.1.1. Not a Number¶ In special occurrences we’d rather want to specify “no amount” rather than an amount of 0.00 (zero). This can be useful for free samples, or when an item is currently not available. The Decimal type denotes a kind of special value a NaN – for “Not a Number”. Our Money type also knows about this special value, and when rendered, € – or $ –`` is printed out. Declaring a Money object without a value, say m = Money() creates such a special value. The big difference as for the Decimal type is that when adding or subtracting a NaN to a valid value, it is considered zero, rather than changing the result of this operation to NaN as well. It also allows us to multiply a Money amount with None. The result of this operation is NaN. 3.1.2. Create a Money type¶ >>> from shop.money import MoneyMaker >>> Money = MoneyMaker() >>> print(Money('1.99')) € 1.99 >>> print(Money('1.55') + Money('8')) € 9.55 >>> print Money <class 'shop.money.money_maker.MoneyInEUR'> >>> Yen = MoneyMaker('JPY') >>> print(Yen('1234.5678')) ¥ 1235 >>> print(Money('100') + Yen('1000')) ValueError: Can not add/substract money in different currencies. How does this work? By calling MoneyMaker() a type accepting amounts in the default currency is created. The default currency can be changed in settings.py with SHOP_DEFAULT_CURRENCY = 'USD', using one of the official ISO-4217 currency codes. Alternatively, we can create our own Money type, for instance Yen. 3.1.3. Formating Money¶ When the amount of a money type is printed or forced to text using str(price), it is prefixed by the currency symbol. This is fine, when working with only a few currencies. However, some symbols are ambiguous, for instance Canadian, Australian and US Dollars, which all use the “$” symbol. With the setting SHOP_MONEY_FORMAT we can style how money is going to be printed out. This setting defaults to {symbol} {amount}. The following format strings are allowed: - {symbol}: The short symbol for a currency, for instance $, £, €, ¥, etc. - {code}: The international currency code, for instance USD, GBP, EUR, JPY, etc. - {currency}: The spoken currency description, for instance “US Dollar”, “Pound Sterling”, etc. - {amount}: The amount, unlocalized. Thus, if we prefer to print 9.98 US Dollar, then we should set {amount} {currency} as the formatting string. 3.2. Localizing Money¶ Since the Money class doesn’t know anything about our current locale setting, amounts always are printed unlocalized. To localize a Money type, use django.utils.numberformat.format(someamount). This function will return the amount, localized according to the current HTTP request. 3.3. Money Database Fields¶ Money can be stored in the database, keeping the currency information together with the field type. Internally, the database uses the Decimal type, but such a field knows its currency and will return an amount as MoneyIn... type. This prevents implicit, but accidental currency conversions. In our database model, declare a field as: class Product(models.Model): ... unit_price = MoneyField(currency='GBP') This field stores its amounts as British Pounds and returns them typed as MoneyInGBP. If the currency argument is omitted, then the default currency is used. 3.4. Money Representation in JSON¶ An additional REST SerializerField has been added to convert amounts into JSON strings. When writing REST serializers, use: from rest_framework import serializers from shop.money.rest import MoneyField class SomeSerializer(serializers.ModelSerializer): price = MoneyField() The default REST behavior serializes Decimal types as floats. This is fine if we want to do some computations in the browser using JavaScript. However, then the currency information is lost and must be re-added somehow to the output strings. It also is a bad idea to do commercial calculations using floats, yet JavaScript does not offer any Decimal-like type. It therefore is recommended to always do the finance arithmetic on the server and transfer amount information using JSON strings.
http://django-shop.readthedocs.io/en/latest/reference/money-types.html
CC-MAIN-2017-47
refinedweb
845
58.38
Using a custom pu/pyui view in another one using ui editor Hi I've defined a custom view object with its pyui file so I have: a.py a.pyui A(ui.View) Is it possible to use it from the editor in another ui? It looks like there is no way to specify the .pyui file for the custom views... Cheers, Eric T. Yes, but you will need to import a.py first before you load the view (perhaps as from a import Aif you want to just refer to the name by A in the editor). Be sure that a.py has a if __name__=='__main__'type guard to ensure when you import it, only the class definitions are executed. IIRC, A should load_view inside init. Hi thx for the reply. I already did the import for the class but I can't figure out to call the load_view in the init.. Do you mean in the init(self) of the A class? as load_view will return an instance of A... It has been a while, but IIRC there are two ways to create custom views: - you give the pyui a Custom View name -- and when you load_view('a') it will return an A object. - You instantiate A directly, and inside A you can call load_view() or load_view('a') (no arguments loads the pyui associated with the current py). One neat thing about this method is that load_view operates in the current scope, so you can reference self.some_methodwhen you create the pyui to assign actions. The first approach IIRC does not let you do that, since self has not yet been created. With the second method, in b.pyui you can add a custom View A -- which will instantiate an A(). For this to work A must have already been imported. My sense is that the second creates two separate object. You can try creating and printing a self.create_timevariable in the __init__()method. Hi, I don't get the way to load the pyui file in the __ init__() method. there is no load_view() method in View class So I really don't get it... do you have sample code that load view content in __ init__() ? Do ui.load_view(), not my_view.load_view().. @JonB , this is almost exactly what I am looking for. I want a class inherited from ui.View but with the pyui file loaded. This is almost perfect but for the fact that I need to somehow provide the pyui file at runtime. Did you ever figure out a way to do it? I have been going down the black magic path , without success 😭 Changing the mro attr example. I know it's stupid. I was looking for inspiration 😁 I have a feeling I tried to do this a long time ago. I couldn't find anything on the forum. But I found this post. It's encouraging but also not 😱 But any ideas appreciated. Oh, my goal is to have just to have a class that works as its a ui.View but it loads the view from a pyui file. Maybe multiple inheritance could help? @JonB k sorry don't worry about it. It appears the new method is past the params. Even if n9t in the init. I didn't expect that. But this is fantastic. All I did is The below. Works perfectly class LoadedPanel(ui.View): def __init__(self): pass def __new__(self, pyui_file): return ui.load_view(pyui_file) l = LoadedPanel(pyui_file = 'Countries') l.present('sheet') Oh, there was one gotcha, but not a big deal. The class init is not called. But I think you can reach it with super or by calling self.init. But is not a big deal. I just changed the class a little and do my init stuff inside the new class LoadedPanel(ui.View): def __init__(self): pass def __new__(self, pyui_file): # hmmm initialse here as init is not called.. # maybe can do super, but this works just fine... cls = ui.load_view(pyui_file) cls['tb_countries'].data_source.items = _country_list return cls Keep in mind, this approach gives you a ui.View, not a LoadedPanel class. So you cannot use touch, etc, unless you monkey patch it. ui.View.__init__does get called, not LoadedPanel.__init__. Let me explain the point of this a little clearer, because rereading the thread got me confused again, others might be too. A "recommended way" to have a custom view defined both in code and pyui, is to set the Custom View of the pyui to point to a class name. Then, to instantiate the custom view, you would use ui.load_view -- NOT MyView(). If you want to be able to personalize a pyui, wrap load_view inside another function that takes parameters. But, if you use that approach, you can not use the editor to insert your custom view into another pyui edited view. Because the ui editor doesnt know you wanted to use load_view instead of MyView() to instantiate your class. The solution is to use the wrapper approach. Here is a long winded example of what I was just saying. pyuistr represents a pyui which has a button, but is also a MyView CustomView. pyuistr2 adds a MyView as a subview to another view, which does not load the pyui properly. The last method uses the wrapper, and all is hunky dory. Actually, it seems Custom View in the editor can be anything that can get eval'd to return an object which is a subclass of ui.View, so could just be a wrapper function. # coding: utf-8 import ui pyuistr=''' [ { "class" : "View", "attributes" : { "custom_class" : "", " : [ ] } ] }] ''' pyuistr2=''' [ { "class" : "View", "attributes" : {}, "frame" : "{{0, 0}, {240, 240}}", "selected" : false, "nodes" : [ { "class" : "View", "attributes" : { "class" : "View", "name" : "view1", "uuid" : "C9AF78B9-C0EB-4951-A282-D06468F22F3E", "frame" : "{{70, 70}, {100, 100}}", "custom_class" : "MyView" }, "frame" : "{{70, 70}, {100, 100}}", "selected" : true, "nodes" : [ ] } ] }] ''' class MyView(ui.View): def hi(self): print 'hi' class MyViewWrapper(ui.View): def __new__(self): v= ui.load_view_str(pyuistr) return v def check_load(v): if v['button1']: return True else: return False v = ui.load_view_str(pyuistr) print 'loadviewstr loaded pyui :', check_load(v) v2= MyView() print 'MyView() loaded pyui:', check_load(v2) v3=MyViewWrapper() #i.e use this in editor print 'MyViewWrapper() loaded pyui:', check_load(v3) #v.present('sheet') v4=ui.load_view_str(pyuistr2) print 'Custom View subview inside pyui using MyView() loaded pyui', check_load(v4['view1']) v5=ui.load_view_str(pyuistr2.replace('MyView','MyViewWrapper')) print 'Custom View subview inside pyui using MyViewWrapper() loaded pyui', check_load(v5['view1']) Ack, I forgot the whole poont of this... if your custom class has both a new and an init, you don't need the wrapper class: class MyView(ui.View): def __init__(self): print 'initted' def __new__(self): v= ui.load_view_str(pyuistr) return v @JonB, shhhhhh! I see what you mean about being returned a ui.View class in my other example. Its so obvious now! I thought I was so close! I will look at the custom class way. Thanks again! Eureka! Looking at load_view, which now has a bindings parameter, it is possible to pass "self" to the view getting loaded. This means you can load a view inside init, and have the pyui update appropriate subviews and attributes of the currently initting View. The code is looking for a class, that is a subview of View, so you have to create such a class inside init, but the new method can return self. Hopefully this explains it better: # coding: utf-8 import ui pyuistr=''' [ { "class" : "View", "attributes" : { "custom_class" : "self", }, " : [ ] } ] }] ''' class MyView(ui.View): def __init__(self): class selfy(ui.View): def __new__(cls): return self ui.load_view_str(pyuistr,bindings={'self':selfy}) v=MyView() v.present() @JonB, wow. You cracked it... It's perfect. I had a problem getting your expample to run. There was just some problem with the pyui_str in could not spot. I was too excited to spend too long on it. ** but thank you ** I know some of these side tracks I go on seem a bit crazy, but I think this is great news for the community for anyone doing ui work. I can't say I exactly get what's happening with the bindings, but I get the gist of it. I have seen the bindings before, but no understanding of there function. So, I would never have figured this out. I think this is too important to leave in this thread. What about in Pythonista-tools repo there was a folder for code snippets, a folder for each subject? An online knowledge base app would be better in my opinion, but repo's appear to be the way here. Anyway, just seems to important to leave in here. For others reading this. The only thing that is done special here you can't see is that in the pyui file, the custom class is set to self. I just did this in the ui Editor I put a pic at the bottom class MyView(ui.View): def __init__(self, *args, **kwargs): class selfy(ui.View): def __new__(cls): return self if kwargs.get('pyui_file'): ui.load_view( kwargs.get('pyui_file') ,bindings={'self':selfy}) else: self.make_view() def make_view(self): self.frame = (0,0,500,500) self.background_color = 'purple' def test(self): print 'in test' #v=MyView(pyui_file = 'Countries') v=MyView() # isinstance is not good in this case as ui.View class returns true # check the type instead ... assert isinstance(v, MyView) , 'The class is wrong type' assert type(v) == MyView, 'The class is wrong type' v.test() # just make sure the methods are callable v.present('sheet') @Phuket2 In retrospect it might be better to pass in a dict which includes both the wrapper class, and the actual self instance. That way, you can have actions refer to instance methods. class MyView(ui.View): def __init__(self, *args, **kwargs): class selfwrapper(ui.View): def __new__(cls): return self if kwargs.get('pyui_file'): ui.load_view( kwargs.get('pyui_file') ,bindings={'selfwrapper':selfwrapper, 'self':self}) else: self.make_view() @JonB , given I will use the class like in the code below, do you still think it's an issue? I will listen to you, I would like to get it right. But I wanted to show you how I thought I would use it. Essentially a loader. In this case the child just decides if it calls the super or not. I guess it wouldn't hurt to call super regardless. But in my view subclassing the "loader" so to speak is nice. I could see @omz just providing this in future releases, or something close any way. But it would be nice to here your thoughts, as I say, I would like to get it right. class ViewBase(ui.View): def __init__(self, pyui_file = None): self.loaded_from_pyui = False class selfy(ui.View): def __new__(cls): return self if pyui_file: ui.load_view( pyui_file ,bindings={'self':selfy}) self.loaded_from_pyui = True class CountriesPanel(ViewBase): def __init__(self, pyui_file = None): if pyui_file: super(CountriesPanel, self).__init__(pyui_file) self.background_color = 'purple' @JonB, I don't really understand you changes in the binding. I think name conflicts. Not really sure. But to get the ui.load_view_str() working correctly I had to change it. Well at least I think I had to... Been getting a little complicated as working on different things. But here is a gist that I am using this idea with. It's not finished, but it's working @JonB or anyone else that can comment, I appreciate your feedback if you have time. What I have outlined below, seems to work. But I have long past my level of competence to really know if it's ok. I put a working version of the code at this gist Based on the discussion in this thread I have had to extend the model to use multiple inheritance for it really to be very useful. Well I think I have to use multiple inheritance. The idea of the MyPanel class is its reusable to create any type of panel (basically just another uiView, that is displayed as a subview) Without adding the PanelHelper there will be a lot of duplicate code as well as uncertainty to attributes the class will contain. Meaning anyone that wants to write a MyPanelClass will have to know to much about the callbacks etc required as well as have to implement std code and define a std set of attrs that will be required. I have read a few times about avoiding Multiple inheritance, but in this case I don't see how to do it nicely or even if I need to avoid it at all. As I say it seems to work. But maybe I have stepped in a land mine, next step might not be nice 😱 So I have : class PyiuLoader(ui.View) class PanelHelper(object) class MyPanel( PyuiLoader , PanelHelper): PyuiLoader.init(self, params) PanelHelper.init(self , params)
https://forum.omz-software.com/topic/2154/using-a-custom-pu-pyui-view-in-another-one-using-ui-editor
CC-MAIN-2018-05
refinedweb
2,151
76.32
Just add this to your normal runserver command: python manage.py runserver 0.0.0.0:8000 Then others on your local network can access it through: You can take a look at $_SERVER['REMOTE_ADDR'], which is the address of the client connecting to a php script. if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') { // connection from localhost, proceed } else { // connection from the outside, deny header('403 Forbidden'); echo "You are not allowed to be here."; die(); } Take into account that if you have a reverse proxy in the same machine, then all connections to your script will come from the proxy, and you will have no way to know if they are really from localhost or from another host. Comment from @x4rf41 is also good, managing that from the webserver layer (although it has the same problem with reverse proxies). Another option would be a command line script instead of a web page, where you would pass the data as parameters to Put following code in your async task in doInbackground() public boolean getData() { try { SoapObject soReturn ; String [] ParameterName = new String[2]; String [] ParameterValue = new String[2]; ParameterName[0] = "MANUFACTURERID"; ParameterValue[0] = manmasid; ParameterName[1] = "MANUFACTURERDESC"; ParameterValue[1] = manmas; try { objWSConfig.SetURL(URL, WebService); objWSConfig.SetSOAPAction(SoapAction, MethodName); objWSConfig.SetWebService(WebService); objWSConfig.SetMethod(MethodName); ws_Method = objWSConfig.getMethod(); This code will do the trick $data_array = array ( array ('1','2'), array ('2','2'), array ('3','6'), array ('4','2'), array ('6','5') ); $csv = "col1,col2 ";//Column headers foreach ($data_array as $record){ $csv.= $record[0].','.$record[1]." "; //Append data to csv } $csv_handler = fopen ('csvfile.csv','w'); fwrite ($csv_handler,$csv); fclose ($csv_handler); echo 'Data saved to csvfile.csv'; put be sure about permession of csvfile so your script can create or write on it. You can alsouse tools which generate diff scripts, like this one for schema or see here The problem is that the Python compiler can't determine basedir's proper scope. Scoping in Python is determined statically. But basedir="empty" assignment statement makes basedir variable as a local variable for newf function. And as a result you cannot access a local variable before its first assignment. And as for your "fix" just you removed assignment of basedir="empty" and basedir isn't more local for newf but it uses from deco function.> First purchase an SSL certificate from a provider such as GoDaddy or RapidSSL. When purchasing you specify the domain name that the certificate will represent. Obviously you can point the domain name to any IP address you wish by configuring the DNS entries for your domain. I've never configured a certificate to point to an actual IP address but I guess it's possible. Given you want to have your server accept requests from the internet, I would use a domain name so that you can change the IP address if required. When purchasing your SSL certificate, you will need to provide a Certificate Signing Request (CSR) which you generate on your server computer, specifying the domain name you want to use the SSL certificate for. You can use a utility such as the DigiCert util ( we found that we were cleaning mongo databases every night with : db.adminCommand("listDatabases").databases.forEach( function (d) { if (d.name != "admin" && d.name != "config") db.getSiblingDB(d.name).dropDatabase(); }) But we were dropping db.local which is not a good idea : it holds replicaset config !"))) Note to anyone who runs into this. It took me about a day to figure it out. First off Blender was right about the POST requests, I changed them to GET requests. Secondly the issue, as I found out lied not within my code, but with IIS 7.5. It does not come with json as a predefined MIME type. Here are the steps in order to solve this. 1)Make sure you are running IIS 7.5. 2)Open the IIS Services Manager. 3)Open up MIME Types 4)Add a new MIME type 5) There are two fields to fill out. File Name Extension: JSON MIME Type: application/json After that it should work. What worked for me was not editing the handler.py file, but rather creating my own subclass (myFTPHandler) and then redefining the onconnect method to write my html file then. Thanks for the help though! Try following: import BaseHTTPServer", 'application/octet-stream') You can use select. plus the select documentation. Or some third party module such as twisted. Feedburner does not support CORS (yet). These are the headers I receive from feedburner when executing your code from jsfiddle: HTTP/1.1 200 OK Content-Type: text/xml; charset=UTF-8 ETag: ckkcnAejDTcF+4d0Kj6kftZuq+0 Last-Modified: Tue, 30 Jul 2013 19:56:16 GMT Content-Encoding: gzip Transfer-Encoding: chunked Date: Tue, 30 Jul 2013 19:58:11 GMT Expires: Tue, 30 Jul 2013 19:58:11 GMT Cache-Control: private, max-age=0 X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Server: GSE If it supported CORS you should see an Access-Control-Allow-Origin header in there That generally means (used to work for MSFT many moons ago) that any problem or issue that you may call Microsoft about when the service runs under the Local Service account will not be answered or handled by their support staff. Long story short, you're on your own when it comes to errors or other challenges. You're best off running the services under a domain account.). This is not a generally accepted way of doing customization in openerp. Ususally, you should make a custom module that implements your customization when installed on the OpenERP server installation. Are you using Windows or Linux? The concept here is to move all of the server addons files to the upsite server, including a dump of the database which can be restored on the upsite server. Here's how. First click the Manage databases at the login screen, Do a backup database and save the generated dump file. Install openerp o nthe upsite server (*major versions must match). Copy the server addons folder, and upload to the upsite server's addon directory. Restart openerp service. Then restore the dump file from your backup location. This is basically how you can mirror a "customized" open When you deploy your file to production it compile and collect all your assets in one folder called assets, so specified paths doesn't work, because there is no galleria/themes/classic/ path on Heroku server or other server, which you're using. So, you need to specify path in HTML file like this href="assets/galleria.classic.css" if it is necessary. But in fact your *= require galleria/themes/classic/galleria.classic and //= require galleria/galleria-1.2.9.min //= require galleria/themes/classic/galleria.classic has already done it, and all the necessary code must be in your compiled .css and .js files. So, you can just remove <link rel...> part from your code. P.S. I'm trying to avoid subfolders in css, javascripts and images folders, because it can often cause such proble You have display_errors turned off on one server and on on the other. The issues still occur on both servers, you just don't get told about them on one. The issue is that you are accessing variables or parts of arrays that are not defined before you try to use them. As your code stands now, only one row will get inserted into mysql. The second while loop is looping on the select statement's result set. So when it gets there it is just going to exhaust the result set outputting the second, third and so on results. If that while block is not being executed then you might only have one row that matches the select statement. Error states that BrakeShoe is not accessible, make BrakeShoe public rebuild and deploy may help. You can revere engineer your existing dll to find if BrakeShoe has proper access specifier. John, When updating your data using ko.mapping be sure you don't create a new item. Your UI is already bound to the existing items, so you just want to update the values of the existing item properties; not create new ones. For the example you posted, you'll want to adjust your "update" method of your map to insert the new values into the correct ko.observable property, rather than creating a new object in it's place. The ko.mapping "update" method has a few different parameter lists depending on usage, with the third parameter being the target object of the map. You would want to update that object's properties. obj.target[label].items[0].text(obj.data[label][0].text); But, that's a bit of a mess. You'll probably want to create a second level of mappings (create / update) to hand I'm not sure if you are aware of the fact that Inserted or Deleted in the above mentioned queries are not alias but special tables used by the SQL server to track insertion, update or deletion of data within triggers. Here is more information: This looks to be a misfeature of the setup.py script always including /usr/local in the search path when make builds the target sharedmods. You'll have to manually frob the setup.py, so do the... ./configure --enable-shared --prefix=/app/vendor/python-dev ...first, then edit setup.py, find lines 442, 443, and 444 which should look like this... if not cross_compiling: add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') ...and comment them out so they look like this... # if not cross_compiling # add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') # add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') ...then the make should work. Instead of npm install from a local directory, try npm link, which creates a globally-installed symlink to the directory. As stated in the docs, this is a two-step process: In package directory: $ npm link This creates a symlink to the current folder in npm's global installation directory. Somewhere else, where you want to use the module: $ npm link <pkgname> This will create a symlink in your project's node_modules/ folder to the global installation. Version Control Systems work with revisions, yes, that counts for either SVN and git. In case of new program versions it naturally makes sense to put them into revisions, as they are usually only a snapshot of XYZ in a certain point in time. XYZ being whatever want it to be, binary programs, images, files, etc. But to make it really part of a revision you would also need to commit the newly fetched changes. That in the end makes a new revision of your (let's say) games tree. Those revisions then can be fetched from the client computers. That can happen either by scripts that automatically check the server every couple of minutes (cronjobs?) for changes or manually. The benefit of that workflow is quite obvious, in case your new versions are not what you want (e.g. later you notice they I think the logshipping solution fits your needs. After a one-time setup proces, the logs would be continually shipped from the local db to the remote db. Keeping the remote perfectly in sync with the local one, providing you with the readonly copy. Logshipping is available in all editions, besides Express. There would be no need for a continuous restore process. You can find more information here. You unnecessarily making a Complex Query UPDATE X SET X.column1 = Y.column1 FROM tableX X INNER JOIN tableY Y ON X.primary_key_col = Y.primary_key_col WHERE X.column1 != Y.column1 git status On branch anotherbranch Your branch is ahead of 'origin/anotherbranch' by 2 commits. (use "git push" to publish your local commits) It means that you have 2 commits that are not pushed. As a best practice is good to run git fetch once in a while to get all the server metadata (updated deleted branches, new commits etc) what is the results of this command: git log --oneline it will show you all the log with the commits so yu can see what is the problem The best way to answer this question is to do an experiment. Perhaps you should have asked the question, then conducted your own experiment and answered it yourself. I suspect it is possible to do it as you describe, without calling a rollback as one of the comments suggested, but I would recommend against it. Often times we are tempted to take the most expedite way of doing something, but often time that leads to hard to find faults. Take the time and do it right, construct the array list as you suggest. you tend to use this in development along with a database parameter -d. This means that openerp will connect to the database and then update this module. Note that it is update only, it won't install. If other modules depend on the module being upgraded they will also be upgraded. You can also pass in a comma separated list of modules. EDIT: I think I did not understand the question completely. Thanks Xman, for pointing it out. What I would have done in this case is - save the last loaded JSON file to my bundle and use it for displaying information while querying the server and loading updates in the background. The flow should be like this: Parse and display data using local JSON file. (Assuming there is local copy of JSON file) Query the server for latest data. Upon receiving response, update the bundle with the latest JSON file. Then, do step 1. In case there is no JSON file, just start from step 2. If there is a Network error display the appropriate information. This SO question answers how to handle Network connections in iOS: How to check for an active Internet Connection on iPhone SDK? Saving file locally: I'm not sure what the other columns in the product table are, but here's a basic approach that should work for you based on the 3 columns in your example, assuming the products_model column is unique in the products table: insert into products (products_price,products_quantity,products_model) select price, stock, model from mid on duplicate key update products_price = values(products_price), products_quantity = values(products_quantity). If the graph schema is not too complex and the data in a single file, the easiest way is to simply use a Gremlin script. Check out this simple recipe to load an edge list: If you have a large amount of data, consider using the BatchGraph wrapper for easier programming, auto-commit and better performance: Once you have your script, you could run it in the Gremlin REPL or execute it from shell script with gremlin.sh: Note that your question is about Titan, but I've responded generically with Blueprints in mind (so you will see TinkerGraph examples in many of these links), bu
http://www.w3hello.com/questions/How-do-I-create-a-local-update-server-for-Anaconda-Python-
CC-MAIN-2018-17
refinedweb
2,505
64
Thank you for giving me the opportunity to assist you. I will give the best answer that I can with the information provided. I can only tell you what SHOULD be deducted from your pay, as I have seen many New York employers make errors in tax withholding and W2 preparation. Since you work physically in NY State, your employer should withhold NY State tax. You are not subject to NYC tax since you are not a resident of NYC UNLESS you work for the city, such as a public school teacher or transit worker. You also may be subject to NY disability tax if your employer participates with the state disability plan. (This is only generally pennies to a couple dollars on each paycheck) When you file a tax return, in addition to filing your federal return, you must file a NY State Non-resident return (IT-203) and file a NJ resident return. You will use Schedule A on the NJ return to calculate a credit for taxes paid to another jurisdiction (new york state). This effectively will alleviate double taxation on that income. Please let me know if I can assist you further. Hello Wendy. Sorry if I was not so clear, but I am coming to the US next month (from Brazil) and wanted to know from my total paycheck (let's say US$1.000 per month), how is the percentage that will be deducted (as city and state) taxes? Thanks in advance, Tiago Papa Well in order to help you better, I need to know how much your gross pay is and what the pay period is...Is it $1,000 per month and you are paid once a month? Also, will you be working for the city or for a private company? How will you fill out your W4 form? (Married or Single, # XXXXX exemptions) Generally if you are single you would fill it out as single 0 or single 1. The more exemptions you pick, the less tax is taken out. Ok, I got it. My gross payment is $12,500 total per month (and I am paid twice a month), I'll be working for a private company, and I'll fill the W4 as married with no kids (and my wife will be my dependent, if posible). How much will be taken of my gross payment? Married, 0, on $6250 semi-monthly will look something like this: (401k, medical insurance, or other non-taxable deductions are not considered) Semi-monthly Gross Pay Federal Withholding Social Security Medicare New York NY SDI Net Pay
http://www.justanswer.com/tax/39vu4-live-new-jersey-work-nyc-taxes.html
CC-MAIN-2015-27
refinedweb
433
69.01
In the ubuntu environment, I made a soft link between python and python3.6 (ln -s python python3.6), and I made a soft link with pip, so after installing virtualenvwrapper with pip, start virtualenvwrapper at source. When sh and workon virtual environment always report an error: 1 ./virtualenvwrapper.sh: line 230: : command not found 2 virtualenvwrapper.sh: There was a problem running the initialization hooks. 3 4 If Python could not import the module virtualenvwrapper.hook_loader, 5 check that virtualenvwrapper has been installed for 6 VIRTUALENVWRAPPER_PYTHON= and that PATH is 7 set properly. This is the statement on line 230 according to the hint: 1 "$VIRTUALENVWRAPPER_PYTHON" -m 'virtualenvwrapper.hook_loader' \ Combined with the error message and the sentence found in the prompt, it is guessed that there should be a problem with VIRTUALENVWRAPPER_PYTHON, and then look for VIRTUALENVWRAPPER_PYTHON in the virtualenvwrapper.sh file, and find the key points: 1 # Locate the global Python where virtualenvwrapper is installed. 2 if [ " ${VIRTUALENVWRAPPER_PYTHON:-} " = "" ] 3 then 4 VIRTUALENVWRAPPER_PYTHON = " $(command \which python3) " # It was originally written \which python, here The one posted is after I modified it to python3. 5 fi VIRTUALENVWRAPPER_PYTHON is used (Locate the global Python where virtualenvwrapper is installed.) to locate which python has virtualenvwrapper installed. The location originally specified is python, which is version 2.7. Since I installed it using python3.6 before, I need to change it to python3 here. Then the error disappeared. The advantage of using virtualenvwrapper is that you don’t need to use source /xxx/virtual environment/bin/activate every time to start the virtual environment. Configure it in ~/.bashrc. You can directly use the workon command to open the virtual environment in the future. The specific steps and premise You have installed python-virtualenv: # Setup: # 1. Create a directory to hold the virtual environments. # (mkdir $HOME/.virtualenvs). # 2. Add a line like "export WORKON_HOME=$HOME/.virtualenvs" # to your .bashrc. # 3. Add a line like "source /path/to/this/file/virtualenvwrapper.sh" # to your .bashrc. # 4. Run: source ~/.bashrc # 5. Run: workon # 6. A list of environments, empty, is printed. # 7. Run: mkvirtualenv temp # 8. Run: workon # 9. This time, the "temp" environment is included. # 10. Run: workon temp # 11. The virtual environment is activated. Read More: - [MAC] How to Solve zsh Error: command not found: umi - g++: internal compiler error: Killed (program cc1plus) Please submit a full bug report, with preprocess - Error: a JNI error has occurred, please check your installation and try again - Maven configuration error: JAVA_HOME not found in your environment - ImportError: No module named google.protobuf.internal - PIP Fatal error in launcher: Unable to create process using - [Solved] ‘pyopenssl’ is a dependency of conda and cannot be removed from requests’ is a dependency of conda - Yarn add package loading error: operation not permitted, unlink … - How to Solve ModuleNotFoundError: No module named ‘_bz2‘ - ImportError: /lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.23‘ not found - Error. Onload failed when ‘rjava’ was calculated in loadnamespace() - NVM ERROR open \settings.txt: The system cannot find the file specified - How to Fix “Microsoft Visual C ++ 14.0 is required” Error - The solution of no module named ‘jinja2. Asyncsupport’ - How to Solve mount error(6): No such device or address - [Solved] At least one of these environment variable is needed to run this program - Sublime text 3 does not support Chinese/[decode error – output not UTF-8] solution - [Solved] cnpm: Cannot load the file C:\Users\Raytine\AppData\Roaming\npm\cnpm.ps1 because running scripts is prohibited on this system - [Solved] Module ‘scipy.misc‘ has no attribute ‘imread‘ - [Samtools] Run error: error while loading shared libraries: libcrypto.so.1.0.0 or libncurses.so.5 or libtinfow.so.5
https://programmerah.com/solved-virtualenvwrapper-sh-error-there-was-a-problem-running-the-initialization-hooks-28751/
CC-MAIN-2021-25
refinedweb
614
59.09
We are pleased to announce that Spring AMQP for Java 1.0 RC2 is now available. For details about the changes since RC1, please review the Release Notes here In addition to a few bug fixes, this release provides the following: - Support for Exchange-to-Exchange bindings as well as custom Exchange types - Improved re-connection support - Added ChannelListenercallback - Clarified Binding builder API semantics - Added a MessageProperties conversion strategy interface - Improved namespace coverage (e.g. <rabbit:template>) - Upgraded to RabbitMQ client version 2.5.0 Since this is intended to be our final pre-GA release, please take some time to try it out. In fact if you have a chance, really try to push the limits so that we know we're ready for prime time. Thanks! The Spring AMQP Team Back
http://spring.io/blog/2011/06/27/spring-amqp-for-java-1-0-rc2
CC-MAIN-2013-48
refinedweb
133
62.07
Today, the world's e-commerce industry alone shoots close 30 billion images a day in studios across the world. Shooting involves human intervention to place object and move them through multiple angles before each image is shot. Multiple shots give customers a better idea of how their products look through imagery since e commerce is intangible over the internet. My aim is to simplify this process and ensure that varied types of products get shot in minimal time without human intervention with exact angles as specified by the photographer. This is an ongoing project since I am trying to improvise the functionality of this system at every stage. The system needs to be robust, versatile and at the same time easy to use for the end user. Parts Required Bread Board - 1 No. Arduino Mega 2560 or the Intel Edison with the Arduino breakout Board - 1 No.( use the one youre comfy with) Base Shield by (Seeed Studio) - 1 No. Jumper wires - 40 No. L293D IC - 1 No. DC Motor with reduction system to 10 RPM - 1 No. RGB Led with 12C interface and 4 cable input GROVE (Seed Studio)- 1 No. Songle 2 output Relay - 1 No. Shoebox - 1 No. Yongnuo Wireless SLR Camera Trigger and Receiver - 1 No. Arduino IDE Installed on your computer. 12 V 4.0Amp Regulated AC to DC Adaptor 1 USB cable to connect the arduino mega and transfer Code 1 USB Battery Pack Teacher Notes Teachers! Did you use this instructable in your classroom? Add a Teacher Note to share how you incorporated it into your lesson. Step 1: Preparing the Intel Edison/Arduino and the IC in H Bridge Mode The connections are easy, see the image above with the breadboard circuit schematic. Tip: You can connect an external power source to L293D pin 8, up to 36V! Ensur eyou use the right voltage and make sure you do not "burn" your motors! Since we would be using just one motor for this setup you can ignore the second motor for all practical purposes. You can also refer to this link to get more information on the working on the L293D IC. He has some good references there.... Step 2: Connecting the Relay For the connection os the relay, I used the steps mentioned in this link.... COM - Common connection--> it is the center. im using NO connection,but here in this type of relay "HIGH" state in code turns off the relay(opens the circuit). "LOW" state in code turns on the relay. The basic code for this would be as follows digitalWrite(RELAY1,LOW); // Turns ON Relays 1 Serial.println("Light ON"); delay(2000); // Wait 2 seconds digitalWrite(RELAY1,HIGH); // Turns Relay Off Serial.println("Light OFF"); delay(2000); Step 3: Controlling the DSLR Camera Wirelessly For this step I've used a simple Yongnuou Wireless Trigger system which is available commercially. I have clicked a picture of it for your reference. However we need to hack it a little bit. The trigger transmitter needs to be opened up and the power leads and the trigger leads need to be pulled out to be connected to our arduino.There is one common line which comes in contact with another one to focus and both these when in touch, contact another lead to click. Howeverm ,we will assume that the camera will be in focus all the time since the distances between the camera and the product being shot are constant and hence we would not need any focus system to be a part of this process. The trigger leads would connect to the two points on the relay which get actuated. The other two leads are the power leads which will be connected to the 12 V power rails on the mini breadboard. This will need 12 volts and will not work on the 5V logic voltage. You can either use the Vcc pin if the 2560 is being powered by an external 2.0 Amps adaptor. Step 4: Putting All These Three Components Together and to Create the Complete System In this step you connect all three systems together. - The Motor Driving system - The Relay System - The wireless Triggering system for the Camera #include #include "rgb_lcd.h" rgb_lcd lcd; const int colorR = 255; const int colorG = 0; const int colorB = 0; const int rotdurA = 5100; const int rotdurB = 10200; const int relay = 10; #define RELAY1 7 void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); lcd.setRGB(colorR, colorG, colorB); // Print a message to the LCD. lcd.print("__Initializing__"); delay(2000); lcd.setCursor(0, 0); lcd.setRGB(0 , 255, 0); lcd.print("__System Ready__"); delay(2000); pinMode(RELAY1, OUTPUT); pinMode(E1, OUTPUT); pinMode(E2, OUTPUT); pinMode(I1, OUTPUT); pinMode(I2, OUTPUT); pinMode(I3, OUTPUT); pinMode(I4, OUTPUT); } void loop() { lcd.setCursor(0, 0); lcd.print("Place Prodct Now"); delay(500); lcd.setCursor(0, 0); lcd.print("___Front_Shot___"); delay(1000); digitalWrite(RELAY1,0); delay(150); // Wait 2 seconds digitalWrite(RELAY1,1); // Turns Relay Off Temporarily // Pauses for 2 second digitalWrite(E1, LOW); digitalWrite(E2, LOW); delay(2000); // Rotates the Disc from 0 - 90(1000); lcd.setCursor(0, 0); lcd.print("___Side__Shot___"); delay(1000); digitalWrite(RELAY1,0); delay(150); // Wait 2 seconds digitalWrite(RELAY1,1); // Turns Relay Off // Rotates the Disc by 90 - 180(2000); lcd.setCursor(0, 0); lcd.print("___Back__Shot___"); delay(1000); digitalWrite(RELAY1,0); delay(150); // Wait 2 seconds digitalWrite(RELAY1,1); // Turns Relay Off // Rotates the Disc from 180 - 9 360 again Degrees CW lcd.setCursor(0, 0); lcd.print("_Shoot_Complete_"); delay(1000); digitalWrite(E1, HIGH); digitalWrite(E2, HIGH); digitalWrite(I1, HIGH); digitalWrite(I2, LOW); digitalWrite(I3, HIGH); digitalWrite(I4, LOW); delay(rotdurB); // Pauses for 2 second digitalWrite(E1, LOW); digitalWrite(E2, LOW); delay(100); } Step 5: Step 5 - Gist of the Code The objective of this project is to automate the entire shoot process and to ensure that product are shot automatically at specific angles and these images need to be transferred directly to the computer where they can be edited later. The first bit of the code initializes the system and asks the user to place the product with the face front. The rig starts shooting the front angle shot of the product. The base moves by 45 degrees and comes to a halt for a few seconds. The rig gets a 45 degree shot. Moves another 45 degrees and comes to halt. The gets a 90 degree (Side Shot) of the product. Moves another 90 degrees and comes to halt. The gets a 180 degree (Back Shot) of the product. Reports that the "Shoot Completed" and comes back to "Home Position" which is 0 or 360 degrees. We are using a simple DC motor which has a speed of 10 rpm and is controlled by an IC in H bridge mode (IC-L293D) The pin configurations have been shared earlier along with the references. Since the Speed of the motor is around 10RPM or 10 revolutions in 60 seconds or 1 revolution (360 deg) in 6 seconds, we can arrive at the conclusion that it moves at "60 Degree per second" 45 Degrees in 0.75 Second or 750 milli sec as used by arduino (Front shot to 45 degree shot) Optional 45 Degrees in 0.75 Second or 750 milli sec as used by arduino (45 degree shot to 90 degree side shot) Optional 90 Degrees in 1.5 second or 1500 milli sec as used by arduino (90 Degree Side shot to 180 degree back shot) 180 Degree in 3 seconds of 3000 milli sec as used by arduino (180 degree back shot to the 360 degree Home Position) However, the DC motor speed is usually controlled by the voltage that is applied, the load and the small play of the motor shaft.. I had to take both of these into consideration and arrive at values mid way and those are the numbers you will see in program. Please feel free to use your numbers as required. At each of the positions that the camera comes to a standstill we use the code to trigger the relay to complete the circuit of the cameras wireless trigger system. Since this is wireless, the photographs are shot automatically without any hard wired connection between the rig and the computer/camera. However the camera and the computer will have to be connected through a USB cable or in newer cases the wifi connection inbuilt in the camera. Thats it !! Your ready to shoot your products without much manual intervention and the angles will be very uniform since its a machine that is handling your shoot. Step 6: Step 6 - the Actual Working Video of the Rig Here you go. I've used all my photography, videography skills into making this video which shows how the product works. Participated in the First Time Author Contest 2016 6 Discussions 3 years ago Ok ArvindShenoy. Thanks very much for explaining it. Very good idea. I also find that when taking photos where you don't want a shadow is to place the item on a piece of glass raised above the surface which would show the shadow. 3 years ago What does it do? and which Base Shield. Seeed Studio have 5 listed. Reply 3 years ago Hi Stuart.Good Point.I missed describing the project there, one of the most basic steps in any instructable.I will add the detailed description in a bit.To give you a gist of it, I am a photographer and when we shoot thousands of prodycts amd their varied angles we have to manually move the product through various angles making it a time consuming task.Consistency between the product shots can also be achieved when the angles are controlled by a precise motor.The shield is a SeeedStudio Base shield which costs around 8-9 dollars and gives you good expandability and convenient connectivity. 3 years ago Thanks geekrex and wold630. I'm really glad I worked on this project. Its been in mind for over 3 years and i brought it to life finally. Will be uploading a video of the actual product, the final one. Just making the video now.Wroking on additional functionalities. Ill have that ready in the version 2 of this project. 3 years ago nice project 3 years ago Thanks for sharing this project!
https://www.instructables.com/id/Automated-Product-Photography-Rig/
CC-MAIN-2019-43
refinedweb
1,738
64.41
Hi Tom, fellow DECstation hackers On 15-Oct-98 Thomas Riemer wrote: > Ok - after playing with the dz serial device - > > I'm getting effectively nowhere - > I have enabled the UART scan > I have enabled the transmit. > > I can force one character across - but as far > as I can tell the interrupt that is supposed to be generated > when the dz11 is ready to process another character never happens. > > I'm guessing that somehow we are not catching it. > > What's the best way to approach this? How do I find out what's > going on under the hood? Your problem might be another one. The R3000 Family processors (including the R2000) have a four word writeback buffer which usually is transparent to memory accesses, but may have side effects when dealing with hardware registers. Example: Let's assume data and status to be two hardware registers and writing something to data has an influence on the content of the status register. A code snippet like: data = whatever; if (status == OK) do_something(); might fail because it cannot be guaranteed that the write access to data happens before the read access from status. The solution to this problem is to wait until the writeback buffer is empty i.e., all write accesses are done. Unfortunately the mechanism for this is hardware implementation specific and the DECstation engineers chose four different ways to do this. You might want to look at arch/mips/dec/wbflush.c. To make a long story short, the above code snippet should look like: #include <asm/dec/wbflush.h> data = whatever; wbflush(); if (status == OK) do_something(); If you have to write to several hardware registers in a certain sequence, you have to wait for the writeback buffer to be empty too. For example: reg_1 = a_value; wbflush(); reg_2 = another_value; when the access to reg_1 should be done before the access to reg_2. Hope this helps. --- Regards, Harald
http://www.linux-mips.org/archives/linux-mips-fnet/1998-10/msg00065.html
CC-MAIN-2015-40
refinedweb
318
61.87
Fit. Contents - Documentation - Infrastructure - Differentiating Java from .NET - Include .NET-Equivalent References - Include .NET-Equivalent Using Statements - Let FitNesse Dynamically Index Your Sub-Pages - Allow Concurrent Test Access - Avoid Duplicating Setup or Teardown Code - Avoid Duplicating Any Other Code, Too - Moving, Renaming, or Deleting Tests - More to Come FitNesse is a wiki-based framework for writing acceptance tests for software systems. If you are not familiar with FitNesse, then you’ll find Part 1 of this series, 'Acceptance Testing With FitNesse, The Overview', useful because it walks through a complete .NET example from writing the test in your browser to writing the C# code-behind. Although FitNesse provides a rather nifty and user-friendly way to write acceptance tests in general there are, in practice, plenty of quirks and glitches to watch out for. This article, and the subsequent parts of this series, provides “tips from the trenches”, by which I mean an accumulation of tips collected from intensive daily use of FitNesse to alleviate or avoid many of those pain-points. This article covers various issues with the documentation and infrastructure; subsequent parts will cover tips about such things as naming, debugging, control flow, layout, variables, comparisons, tracing and database. Documentation FitNesse was originally designed for testing Java code, but it has since evolved to handle .NET code with the separate fitSharp component and does so pretty well. Database support came later with the DbFit component. Those two components, together with the base FitNesse component, all provide their own documentation with different styles, organization and comprehensiveness. As so often with software documentation, it can be a challenge to find the information you are looking for. Here then, is a collection of the most useful links within the documentation of FitNesse, fitSharp, and DbFit: - FitNesse User Guide (The starting point for all things FitNesse.) - FitNesse Quick Reference to formatting and executing FitNesse tests. (On your local installation, this will be located at.) - FitNesse Fixture Gallery and FitNesse Fit Table Styles (e.g. Column Fixture, Row Fixture, Comment Fixture, etc.) - FitNesse Special Pages (e.g. SetUp, TearDown, PageHeader, PageFooter, etc.) - FitSharp Fixture/Feature Gallery (e.g. Debug Fixture, Calculate Fixture, Cell Operators, etc.) - DbFit Fixture Gallery (e.g. Query Fixture, Insert Fixture, Execute Fixture, etc.) - DbFit Reference (This covers DbFit but it is not quite complete: for a variety of actual examples, download the complete FitNesse and DbFit package from the DbFit website, run it, then select .NET Acceptance Test and choose SqlServerTests. The direct URL on your own installation is .... - Test Driven .NET Development with FitNesse (This book is the next stepping stone, covering all things FitNesse-plus-.NET) The first part of this series was just intended to help get you up to speed if you had never been exposed to FitNesse, so it is more tutorial than reference. This and subsequent parts, however, lean more towards reference than tutorial. The main FitNesse site provides some additional tutorial material—notably their One-Minute Description and Two-Minute Example, among other good learning material. Use the User Guide link above to see those. Infrastructure Differentiating Java from .NET By default, FitNesse works for the Java environment. To work in a .NET environment you must download the fitSharp DLL and tell FitNesse to use that instead. Typically you do this on your root page—accessible from a link at the bottom of every FitNesse page (the address is). Use the !define directive as follows: References: Defining Common Actions, Customizing Test Execution, Using FitNesse Include .NET-Equivalent References You must include references in FitNessse with the !path directive to access the namespaces and classes in a DLL.This is In much the same way as a Visual Studio project. You do not need to include either FitNesse, as this is handled by the JAR file you launched, or fitSharp, handled by the TEST_RUNNER definition described in the previous section. You would, however, include DbFit if you are using database fixtures as well as your custom DLLs: Just as with the COMMAND_PATTERN and TEST_RUNNER in the previous section, you typically specify these on your root page, which is accessible from a link at the bottom of every FitNesse page (the address is). You may optionally specify these from a suite configuration file instead. If you do, you do not need the %p in the COMMAND_PATTERN. Reference: Defining Common Actions, Using FitNesse, Suite Configuration File Include .NET-Equivalent Using Statements In much the same way that you optionally import namespaces with using statements in C# to obviate the need to use fully-qualified paths when referring to classes, you may do the same in FitNessse with the !import directive. Typically these go in a SuiteSetUp or SetUp page so they are inherited as needed, but you may use them directly on individual test pages as well. A FitNesse import is analogous to a .NET using statement: you can then write unqualified class names in your code, making it more readable. At the left side of the table below, you see the use of an !import directive allowing the Echo fixture to be referenced without a fully-qualified namespace. At right, the namespace is required when the !import directive is not used. Reference: Import Fixture Let FitNesse Dynamically Index Your Sub-Pages You can explicitly list a set of links to subpages, as is done on the FitNesse top-level page: That is fine if your list of links is hand-picked, but in most cases you will be setting up suites of suites of suites. You want each suite page to contain links to all of its children and, should you add or delete children, you want the page to update automatically. To do this, rather than enumerate your pages or suites explicitly, just use the !contents directive. The –R flag indicates to recursively show all child pages, as shown in the example. Omit the –R flag to show only immediate children. Limit the recursion to a set depth by adding a numeric argument, e.g. –R2. By default, creating a new page gives you that flag and more: !contents -R2 -g -p -f –h See the reference for details on all the other flags. References: MarkupContents Allow Concurrent Test Access Where a test may access a common resource such as a database, you can allow several people to run the same test simultaneously by generating unique values per session. This assumes that each user runs their own FitNesse server, so each will thereby have a unique session. First, setup a command file to launch FitNesse (e.g. LaunchFitNesse.cmd) defining an environment variable containing a random seed just before you launch the FitNesse server: set SEED=%RANDOM% java -jar fitnesse.jar -p port Windows environment variables such as SEED are accessible within FitNesse tests just like variables you explicitly define. You can thus use this session-specific seed when creating one or more values to insert in your database table: From the variable definition, it does not look like the value of SEED has been substituted within TestClient, but when it is used in the Echo table you can see it has. Avoid Duplicating Setup or Teardown Code Use appropriate setup and teardown pages. These will function exactly as do setup and cleanup pages in unit test frameworks. The table shows the corresponding elements between the two major .NET test frameworks and FitNesse: Pages that you name SetUp or TearDown are executed automatically at the start and end of every test. Pages that you name SuiteSetUp or SuiteTearDown are executed automatically at the start and end of a suite. Note that a suite may be explicit—a page containing one or more child tests—but it may also be implicit: executing just a single test constitutes a suite, too. These special pages are inherited in child pages, so often you just need to define these once at the top-level. However, you can override inheritance by redefining one further down your tree. This is because FitNesse pages are always arranged hierarchically in a standard tree structure. The root may typically contains suites, which may contain suites of their own, etc. Eventually, you will have leaf nodes—individual tests. You can also inherit and override at the same time. Assume you have created a SetUp page at your root. Somewhere lower in your tree you also create a SetUp page. Its presence cancels inheritance. But if your goal is to add to the parent SetUp rather than replace it, simply start your lower SetUp page with an !include directive. My root page is CleanCode (in a browser, this is) so referencing my root SetUp page is done like this: Reference: Special Pages, Defining Common Actions Avoid Duplicating Any Other Code, Too You are not restricted from using the !include directive from the last section just in SetUp or TearDown pages. Bring in other needed code fragments with the !include directive whenever you need: !include path A path may be relative or absolute. A path address is formed just like a file system path but you must use a period between component names instead of virgules or backslashes. A leading period makes a path absolute. If your path is incorrect, FitNesse will tell you immediately upon saving the page; you do not have to wait until you execute the test. By default, the included block of text is expanded—you see the contents of the included file inline. Compare that to the example in the previous section; the –setup option collapsed the block so you only saw the file name. The !include directive provides several options: - Collapse it with the –c flag. - Expand it and make it look just as if it was part of the page with the –seamless flag. - Delegate control over whether it is expanded or collapsed to the global variable COLLAPSE_SETUP or COLLAPSE_TEARDOWN with the –setup or –teardown flags, respectively. Reference: Includes & Informational, Global Variables Moving, Renaming, or Deleting Tests For your conventional code—e.g. C# code that you work with in Visual Studio—there are source control plugins available (notably AnkhSVN or VisualSVN) so that, when you move or rename a file in Visual Studio, it actually mirrors the operation correctly in source control, maintaining the history of the item in question. In FitNesse, you can similarly move or rename test pages, but there is no plugin to mirror this in your source control back-end! Thus, a moved item will appear as unversioned and its former named item will appear as missing when you review your changes to commit. Because of this, it is easier to do file reorganizations outside of FitNesse, just using Windows Explorer or equivalent. Assuming you have followed the guideline above to automatically generate your suite pages with the !contents directive, the only thing you need do is restart your FitNesse server. If you don’t restart, you will pick up the items in the new locations or new names, but you will also still see the old locations/names. Of course, the above applies to files that you have already committed to source control. If you are developing new test pages that are not yet committed, you can freely move, rename, or delete as needed within the confines of FitNesse.
https://www.simple-talk.com/dotnet/.net-tools/acceptance-testing-with-fitnesse-documentation-and-infrastructure/
CC-MAIN-2015-18
refinedweb
1,877
54.12
How do I create an empty array/matrix in NumPy? assign data to it row-by-row: import numpy a = numpy.zeros(shape=(5,2)) aarray([[ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.], [ 0., 0.]]) a[0] = [1,2] a[1] = [2,3] aarray([[! To create an empty multidimensional array in NumPy (e.g.]). This way you can use for example (here m = 5 which we assume we didn't know when creating the empty matrix, and n = 2): import numpy as npn = 2X = np.empty(shape=[0, n])for i in range(5): for j in range(2): X = np.append(X, [[i, j]], axis=0)print X which will give you: [[ 0. 0.] [ 0. 1.] [ 1. 0.] [ 1. 1.] [ 2. 0.] [ 2. 1.] [ 3. 0.] [ 3. 1.] [ 4. 0.] [ 4. 1.]]
https://codehunter.cc/a/python/how-do-i-create-an-empty-array-matrix-in-numpy
CC-MAIN-2022-21
refinedweb
134
82.75
import "github.com/mholt/certmagic" Package certmagic automates the obtaining and renewal of TLS certificates, including TLS & HTTPS best practices such as robust OCSP stapling, caching, HTTP->HTTPS redirects, and more. Its high-level API serves your HTTP handlers over HTTPS if you simply give the domain name(s) and the http.Handler; CertMagic will create and run the HTTPS server for you, fully managing certificates during the lifetime of the server. Similarly, it can be used to start TLS listeners or return a ready-to-use tls.Config -- whatever layer you need TLS for, CertMagic makes it easy. See the HTTPS, Listen, and TLS functions for that. If you need more control, create a Cache using NewCache() and then make a Config using New(). You can then call Manage() on the config. But if you use this lower-level API, you'll have to be sure to solve the HTTP and TLS-ALPN challenges yourself (unless you disabled them or use the DNS challenge) by using the provided Config.GetCertificate function in your tls.Config and/or Config.HTTPChallangeHandler in your HTTP handler. See the package's README for more instruction. acmeclient.go acmemanager.go async.go cache.go certificates.go certmagic.go config.go crypto.go filestorage.go handshake.go httphandler.go maintain.go ocsp.go ratelimiter.go solvers.go storage.go user.go const ( LetsEncryptStagingCA = "" LetsEncryptProductionCA = "" ) Some well-known CA endpoints available to use. const ( // HTTPChallengePort is the officially-designated port for // the HTTP challenge according to the ACME spec. HTTPChallengePort = 80 // TLSALPNChallengePort is the officially-designated port for // the TLS-ALPN challenge according to the ACME spec. TLSALPNChallengePort = 443 ) const ( the CA's actual rate limits. Let's Encrypt's rate limits can be found here: Currently (as of December 2019), Let's Encrypt's most relevant rate limit for large deployments is 300 new orders per account per 3 hours (on average, or best case, that's about 1 every 36 seconds, or 2 every 72 seconds, etc.); but it's not reasonable to try to assume that our internal state is the same as the CA's (due to process restarts, config changes, failed validations, etc.) and ultimately, only the CA's actual rate limiter is the authority. Thus, our own rate limiters do not attempt to enforce external rate limits. Doing so causes problems when the domains are not in our control (i.e. serving customer sites) and/or lots of domains fail validation: they clog our internal rate limiter and nearly starve out (or at least slow down) the other domains that need certificates. Failed transactions are already retried with exponential backoff, so adding in rate limiting can slow things down even more. Instead, the point of our internal rate limiter is to avoid hammering the CA's endpoint when there are thousands or even millions of certificates under management. Our goal is to allow small bursts in a relatively short timeframe so as to not block any one domain for too long, without unleashing thousands of requests to the CA at once. Some default values passed down to the underlying lego client. var ( // HTTPPort is the port on which to serve HTTP // and, by extension, the HTTP challenge (unless // Default.AltHTTPPort is set). HTTPPort = 80 // HTTPSPort is the port on which to serve HTTPS // and, by extension, the TLS-ALPN challenge // (unless Default.AltTLSALPNPort is set). HTTPSPort = 443 ) Port variables must remain their defaults unless you forward packets from the defaults to whatever these are set to; otherwise ACME challenges will fail., } Default contains the package defaults for the various Config fields. This is used as a template when creating your own Configs with New(), and it is also used as the Config by all the high-level functions in this package. The fields of this value will be used for Config fields which are unset. Feel free to modify these defaults, but do not use this Config by itself: it is only a template. Valid configurations can be obtained by calling New() (if you have your own certificate cache) or NewDefault() (if you only need a single config and want to use the default cache). This is the only Config which can access the default certificate cache.(storage Storage, opts CleanStorageOptions) CleanStorage removes assets which are no longer useful, according to opts. CleanUpOwnLocks immediately cleans up all current locks obtained by this process. Since this does not cancel the operations that the locks are synchronizing, this should be called only immediately before process exit. HTTPS serves mux for all domainNames using the HTTP and HTTPS ports, redirecting all HTTP requests to HTTPS. It uses the Default config. This high-level convenience function is opinionated and applies sane defaults for production use, including timeouts for HTTP requests and responses. To allow very long-lived connections, you should make your own http.Server values and use this package's Listen(), TLS(), or Config.TLSConfig() functions to customize to your needs. For example, servers which need to support large uploads or downloads with slow clients may need to use longer timeouts, thus this function is not suitable. Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service. This is the simplest way for HTTP servers to use this package. Call HTTPS() with your domain names and your handler (or nil for the http.DefaultMux), and CertMagic will do the rest. Code: http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Hello, HTTPS visitor!") }) err := HTTPS([]string{"example.com", ""}, nil) if err != nil { log.Fatal(err) } Listen manages certificates for domainName and returns a TLS listener. It uses the Default config. Because this convenience function returns only a TLS-enabled listener and does not presume HTTP is also being served, the HTTP challenge will be disabled. The package variable Default is modified so that the HTTP challenge is disabled. Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service. LooksLikeHTTPChallenge returns true if r looks like an ACME HTTP challenge request from an ACME server. ManageAsync is the same as ManageSync, except that certificates are managed asynchronously. This means that the function will return before certificates are ready, and errors that occur during certificate obtain or renew operations are only logged. It is vital that you monitor the logs if using this method, which is only recommended for automated/non-interactive environments. ManageSync obtains certificates for domainNames and keeps them renewed using the Default config. This is a slightly lower-level function; you will need to wire up support for the ACME challenges yourself. You can obtain a Config to help you do that by calling NewDefault(). You will need to ensure that you use a TLS config that gets certificates from this Config and that the HTTP and TLS-ALPN challenges can be solved. The easiest way to do this is to use NewDefault().TLSConfig() as your TLS config and to wrap your HTTP handler with NewDefault().HTTPChallengeHandler(). If you don't have an HTTP server, you will need to disable the HTTP challenge. If you already have a TLS config you want to use, you can simply set its GetCertificate field to NewDefault().GetCertificate. Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service. NormalizedName returns a cleaned form of serverName that is used for consistency when referring to a SNI value.). TLS enables management of certificates for domainNames and returns a valid tls.Config. It uses the Default config. Because this is a convenience function that returns only a tls.Config, it does not assume HTTP is being served on the HTTP port, so the HTTP challenge is disabled (no HTTPChallengeHandler is necessary). The package variable Default is modified so that the HTTP challenge is disabled. Calling this function signifies your acceptance to the CA's Subscriber Agreement and/or Terms of Service. // Disable all HTTP challenges DisableHTTPChallenge bool // Disable all TLS-ALPN challenges DisableTLSALPNChallenge bool // The host (ONLY the host, not port) to listen // on if necessary to start a listener to solve // an ACME challenge ListenHost string // The alternate port to use for the ACME HTTP // challenge; if non-empty, this port will be // used instead of HTTPChallengePort to spin up // a listener for the HTTP challenge AltHTTPPort int // The alternate port to use for the ACME // TLS-ALPN challenge; the system must forward // TLSALPNChallengePort to this port for // challenge to succeed AltTLSALPNPort int // The DNS provider to use when solving the // ACME DNS challenge DNSProvider challenge.Provider // The ChallengeOption struct to provide // custom precheck or name resolution options // for DNS challenge validation and execution DNSChallengeOption dns01.ChallengeOption // TrustedRoots specifies a pool of root CA // certificates to trust when communicating // over a network to a peer. TrustedRoots *x509.CertPool // The maximum amount of time to allow for // obtaining a certificate. If empty, the // default from the underlying lego lib is // used. If set, it must not be too low so // as to cancel orders too early, running // the risk of rate limiting. CertObtainTimeout time.Duration //. HTTPChallengeHandler wraps h in a handler that can solve the ACME HTTP challenge. cfg is required, and it must have a certificate cache backed by a functional storage facility, since that is where the challenge state is stored between initiation and solution. If a request is not an ACME HTTP challenge, h will be invoked. (am *ACMEManager) Issue(ctx context.Context, csr *x509.CertificateRequest) (*IssuedCertificate, error) Issue implements the Issuer interface. It obtains a certificate for the given csr using the ACME configuration am. func (am *ACMEManager) IssuerKey() string IssuerKey returns the unique issuer key for the confgured CA endpoint. (am *ACMEManager) Revoke(ctx context.Context, cert CertificateResource) error Revoke implements the Revoker interface. It revokes the given certificate. Cache is a structure that stores certificates in memory. A Cache indexes certificates by name for quick access during TLS handshakes, and avoids duplicating certificates in memory. Generally, there should only be one per process. However, that is not a strict requirement; but using more than one is a code smell, and may indicate an over-engineered design. An empty cache is INVALID and must not be used. Be sure to call NewCache to get a valid value. These should be very long-lived values and must not be copied. Before all references leave scope to be garbage collected, ensure you call Stop() to stop maintenance on the certificates stored in this cache and release locks. Caches are not usually manipulated directly; create a Config value with a pointer to a Cache, and then use the Config to interact with the cache. Caches are agnostic of any particular storage or ACME config, since each certificate may be managed and stored differently. func NewCache(opts CacheOptions) *Cache NewCache returns a new, valid Cache for efficiently accessing certificates in memory. It also begins a maintenance goroutine to tend to the certificates in the cache. Call Stop() when you are done with the cache so it can clean up locks and stuff. Most users of this package will not need to call this because a default certificate cache is created for you. Only advanced use cases require creating a new cache. This function panics if opts.GetConfigForCert is not set. The reason is that a cache absolutely needs to be able to get a Config with which to manage TLS assets, and it is not safe to assume that the Default config is always the correct one, since you have created the cache yourself. See the godoc for Cache to use it properly. When no longer needed, caches should be stopped with Stop() to clean up resources even if the process is being terminated, so that it can clean up any locks for other processes to unblock! func (certCache *Cache) AllMatchingCertificates(name string) []Certificate AllMatchingCertificates returns a list of all certificates that could be used to serve the given SNI name, including exact SAN matches and wildcard matches. RenewManagedCertificates renews managed certificates, including ones loaded on-demand. Note that this is done automatically on a regular basis; normally you will not need to call this. This method assumes non-interactive mode (i.e. operating in the background). Stop stops the maintenance goroutine for certificates in certCache. It blocks until stopping is complete. Once a cache is stopped, it cannot be reused. type CacheOptions struct { // REQUIRED. A function that returns a configuration // used for managing a certificate, or for accessing // that certificate's asset storage (e.g. for // OCSP staples, etc). The returned Config MUST // be associated with the same Cache as the caller. // // The reason this is a callback function, dynamically // returning a Config (instead of attaching a static // pointer to a Config on each certificate) is because // the config for how to manage a domain's certificate // might change from maintenance to maintenance. The // cache is so long-lived, we cannot assume that the // host's situation will always be the same; e.g. the // certificate might switch DNS providers, so the DNS // challenge (if used) would need to be adjusted from // the last time it was run ~8 weeks ago. GetConfigForCert ConfigGetter // How often to check certificates for renewal; // if unset, DefaultOCSPCheckInterval will be used. OCSPCheckInterval time.Duration // How often to check certificates for renewal; // if unset, DefaultRenewCheckInterval will be used. RenewCheckInterval time.Duration } CacheOptions is used to configure certificate caches. Once a cache has been created with certain options, those settings cannot be changed. type CertMetadata struct { Tags []string // user-provided and arbitrary Subject pkix.Name SerialNumber *big.Int PublicKeyAlgorithm x509.PublicKeyAlgorithm } CertMetadata is data extracted from a parsed x509 certificate which is purely optional but can be useful when selecting which certificate to use if multiple match a ClientHello's ServerName. The more fields we add to this struct, the more memory use will increase at scale with large numbers of certificates in the cache. func (cm CertMetadata) HasTag(tag string) bool HasTag returns true if cm.Tags has tag. type Certificate struct { tls.Certificate // Names is the list of names this certificate is written for. // The first is the CommonName (if any), the rest are SAN. Names []string // The certificate's validity period. NotBefore, NotAfter time.Time // These fields are extracted to here mainly for custom // selection logic, which is optional; callers may wish // to use this information to choose a certificate when // more than one match the ClientHello CertMetadata // contains filtered or unexported fields } Certificate is a tls.Certificate with associated metadata tacked on. Even if the metadata can be obtained by parsing the certificate, we are more efficient by extracting the metadata onto this struct, but at the cost of slightly higher memory use. func (cert Certificate) NeedsRenewal(cfg *Config) bool NeedsRenewal returns true if the certificate is expiring soon (according to cfg) or has expired. (cr *CertificateResource) NamesKey() string NamesKey returns the list of SANs as a single string, truncated to some ridiculously long size limit. It can act as a key for the set of names on the resource. type CertificateSelector interface { SelectCertificate(*tls.ClientHelloInfo, []Certificate) (Certificate, error) } CertificateSelector is a type which can select a certificate to use given multiple choices. type CleanStorageOptions struct { OCSPStaples bool ExpiredCerts bool ExpiredCertGracePeriod time.Duration } CleanStorageOptions specifies how to clean up a storage unit. type Config struct { // How much of a certificate's lifetime becomes the // renewal window, which is the span of time at the // end of the certificate's validity period in which // it should be renewed; for most certificates, the // global default is good, but for exremely{}) // DefaultServerName specifies a server name // to use when choosing a certificate if the // ClientHello's ServerName field is empty DefaultServerName string // The state needed to operate on-demand TLS; // if non-nil, on-demand TLS is enabled and // certificate operations are deferred to // TLS handshakes (or as-needed), the first matching certificate // will be selected CertSelection CertificateSelector // The storage to access when storing or // loading TLS assets Storage Storage // contains filtered or unexported fields } Config configures a certificate manager instance. An empty Config is not valid: use New() to obtain a valid Config. New makes a new, valid config based on cfg and uses the provided certificate cache. certCache MUST NOT be nil or this function will panic. Use this method when you have an advanced use case that requires a custom certificate cache and config that may differ from the Default. For example, if not all certificates are managed/renewed the same way, you need to make your own Cache value with a GetConfigForCert callback that returns the correct configuration for each certificate. However, for the vast majority of cases, there will be only a single Config, thus the default cache (which always uses the default Config) and default config will suffice, and you should use New() instead. NewDefault makes a valid config based on the package Default config. Most users will call this function instead of New() since most use cases require only a single config for any and all certificates. If your requirements are more advanced (for example, multiple configs depending on the certificate), then use New() instead. (You will need to make your own Cache first.) If you only need a single Config to manage your certs (even if that config changes, as long as it is the only one), customize the Default package variable before calling NewDefault(). All calls to NewDefault() will return configs that use the same, default certificate cache. All configs returned by NewDefault() are based on the values of the fields of Default at the time it is called. func (cfg *Config) CacheManagedCertificate(domain string) (Certificate, error) CacheManagedCertificate loads the certificate for domain into the cache, from the TLS storage for managed certificates. It returns a copy of the Certificate that was put into the cache. This is a lower-level method; normally you'll call Manage() instead. This method is safe for concurrent use. func (cfg *Config) CacheUnmanagedCertificatePEMBytes(certBytes, keyBytes []byte, tags []string) error CacheUnmanagedCertificatePEMBytes makes a certificate out of the PEM bytes of the certificate and key, then caches it in memory. This method is safe for concurrent use. CacheUnmanagedCertificatePEMFile loads a certificate for host using certFile and keyFile, which must be in PEM format. It stores the certificate in the in-memory cache. This method is safe for concurrent use. CacheUnmanagedTLSCertificate adds tlsCert to the certificate cache. It staples OCSP if possible. This method is safe for concurrent use. func (cfg *Config) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) GetCertificate gets a certificate to satisfy clientHello. In getting the certificate, it abides the rules and settings defined in the Config that matches clientHello.ServerName. It first checks the in- memory cache, then, if the config enables "OnDemand", it accesses disk, then accesses the network if it must obtain a new certificate via ACME. This method is safe for use as a tls.Config.GetCertificate callback. ManageAsync is the same as ManageSync, except that ACME operations are performed asynchronously (in the background). This method returns before certificates are ready. It is crucial that the administrator monitors the logs and is notified of any errors so that corrective action can be taken as soon as possible. Any errors returned from this method occurred before ACME transactions started. As long as logs are monitored, this method is typically recommended for non-interactive environments. If there are failures loading, obtaining, or renewing a certificate, it will be retried with exponential backoff for up to about 30 days, with a maximum interval of about 24 hours. Cancelling ctx will cancel retries and shut down any goroutines spawned by ManageAsync. ManageSync causes the certificates for domainNames to be managed according to cfg. If cfg.OnDemand is not nil, then this simply whitelists the domain names and defers the certificate operations to when they are needed. Otherwise, the certificates for each name are loaded from storage or obtained from the CA. If loaded from storage, they are renewed if they are expiring or expired. It then caches the certificate in memory and is prepared to serve them up during TLS handshakes. Note that name whitelisting for on-demand management only takes effect if cfg.OnDemand.DecisionFunc is not set (is nil); it will not overwrite an existing DecisionFunc, nor will it overwrite its decision; i.e. the implicit whitelist is only used if no DecisionFunc is set. This method is synchronous, meaning that certificates for all domainNames must be successfully obtained (or renewed) before it returns. It returns immediately on the first error for any of the given domainNames. This behavior is recommended for interactive use (i.e. when an administrator is present) so that errors can be reported and fixed immediately. ObtainCert obtains a certificate for name using cfg, as long as a certificate does not already exist in storage for that name. The name must qualify and cfg must be flagged as Managed. This function is a no-op if storage already has a certificate for name. It only obtains and stores certificates (and their keys), it does not load them into memory. If interactive is true, the user may be shown a prompt. RenewCert renews the certificate for name using cfg. It stows the renewed certificate and its assets in storage if successful. It DOES NOT update the in-memory cache with the new certificate. RevokeCert revokes the certificate for domain via ACME protocol. It requires that cfg.Issuer is properly configured with the same issuer that issued the certificate being revoked. TLSConfig is an opinionated method that returns a recommended, modern TLS configuration that can be used to configure TLS listeners, which also supports the TLS-ALPN challenge and serves up certificates managed by cfg. Unlike the package TLS() function, this method does not, by itself, enable certificate management for any domain names. Feel free to further customize the returned tls.Config, but do not mess with the GetCertificate or NextProtos fields unless you know what you're doing, as they're necessary to solve the TLS-ALPN challenge. type ConfigGetter func(Certificate) (*Config, error) ConfigGetter is a function that returns a prepared, valid config that should be used when managing the given certificate or its assets. ErrNoRetry is an error type which signals to stop retries early. func (e ErrNoRetry) Error() string func (e ErrNoRetry) Unwrap() error Unwrap makes it so that e wraps e.Err. ErrNotExist is returned by Storage implementations when a resource is not found. It is similar to os.IsNotExist except this is a type, not a variable. FileStorage facilitates forming file paths derived from a root directory. It is used to get file paths in a consistent, cross-platform way or persisting ACME assets on the file system. func (fs *FileStorage) Delete(key string) error Delete deletes the value at key. func (fs *FileStorage) Exists(key string) bool Exists returns true if key exists in fs. func (fs *FileStorage) Filename(key string) string Filename returns the key as a path on the file system prefixed by fs.Path. List returns all keys that match prefix. func (fs *FileStorage) Load(key string) ([]byte, error) Load retrieves the value at key. func (fs *FileStorage) Lock(key string) error Lock obtains a lock named by the given key. It blocks until the lock can be obtained or an error is returned. func (fs *FileStorage) Stat(key string) (KeyInfo, error) Stat returns information about key. func (fs *FileStorage) Store(key string, value []byte) error Store saves value at key. func (fs *FileStorage) String() string func (fs *FileStorage) Unlock(key string) error Unlock releases the lock for name. type IssuedCertificate struct { // The PEM-encoding of DER-encoded ASN.1 data. Certificate []byte // Any extra information to serialize alongside the // certificate in storage. Metadata interface{} } IssuedCertificate represents a certificate that was just issued.. KeyBuilder provides a namespace for methods that build keys and key prefixes, for addressing items in a Storage implementation. var StorageKeys KeyBuilder StorageKeys provides methods for accessing keys and key prefixes for items in a Storage. Typically, you will not need to use this because accessing storage is abstracted away for most cases. Only use this if you need to directly access TLS assets in your application. func (keys KeyBuilder) CertsPrefix(issuerKey string) string CertsPrefix returns the storage key prefix for the given certificate issuer. func (keys KeyBuilder) CertsSitePrefix(issuerKey, domain string) string CertsSitePrefix returns a key prefix for items associated with the site given by domain using the given issuer key. func (keys KeyBuilder) OCSPStaple(cert *Certificate, pemBundle []byte) string OCSPStaple returns a key for the OCSP staple associated with the given certificate. If you have the PEM bundle handy, pass that in to save an extra encoding step. func (keys KeyBuilder) Safe(str string) string Safe standardizes and sanitizes str for use as a single component of a storage key. This method is idempotent. func (keys KeyBuilder) SiteCert(issuerKey, domain string) string SiteCert returns the path to the certificate file for domain that is associated with the issuer with the given issuerKey. func (keys KeyBuilder) SiteMeta(issuerKey, domain string) string SiteMeta returns the path to the metadata file for domain that is associated with the certificate from the given issuer with the given issuerKey. func (keys KeyBuilder) SitePrivateKey(issuerKey, domain string) string SitePrivateKey returns the path to the private key file for domain that is associated with the certificate from the given issuer with the given issuerKey. type KeyGenerator interface { // GenerateKey generates a private key. The returned // PrivateKey must be able to expose its associated // public key. GenerateKey() (crypto.PrivateKey, error) } KeyGenerator can generate a private key.. KeyType enumerates the known/supported key types. type Locker interface { // Lock acquires the lock for key, blocking until the lock // can be obtained or an error is returned. Note that, even // after acquiring a lock, an idempotent operation may have // already been performed by another process that acquired // the lock before - so always check to make sure idempotent // operations still need to be performed after acquiring the // lock. // // The actual implementation of obtaining of a lock must be // an atomic operation so that multiple Lock calls at the // same time always results in only one caller receiving the // lock at any given time. // // To prevent deadlocks, all implementations (where this concern // is relevant) should put a reasonable expiration on the lock in // case Unlock is unable to be called due to some sort of network // failure or system crash. Lock(key string) error // Unlock releases the lock for key. This method must ONLY be // called after a successful call to Lock, and only after the // critical section is finished, even if it errored or timed // out. Unlock cleans up any resources allocated during Lock. Unlock(key string) error } Locker facilitates synchronization of certificate tasks across machines and networks. type OnDemandConfig struct { // If set, this function will be called to determine // whether a certificate can be obtained or renewed // for the given name. If an error is returned, the // request will be denied. DecisionFunc func(name string) error // contains filtered or unexported fields } OnDemandConfig configures on-demand TLS (certificate operations as-needed, like during TLS handshakes, rather than immediately). When this package's high-level convenience functions are used (HTTPS, Manage, etc., where the Default config is used as a template), this struct regulates certificate operations using an implicit whitelist containing the names passed into those functions if no DecisionFunc is set. This ensures some degree of control by default to avoid certificate operations for aribtrary domain names. To override this whitelist, manually specify a DecisionFunc. To impose rate limits, specify your own DecisionFunc. PreChecker is an interface that can be optionally implemented by Issuers. Pre-checks are performed before each call (or batch of identical calls) to Issue(), giving the issuer the option to ensure it has all the necessary information/state. type Revoker interface { Revoke(ctx context.Context, cert CertificateResource) error } Revoker can revoke certificates. RingBufferRateLimiter uses a ring to enforce rate limits consisting of a maximum number of events within a single sliding window of a given duration. An empty value is not valid; use NewRateLimiter to get one. func NewRateLimiter(maxEvents int, window time.Duration) *RingBufferRateLimiter NewRateLimiter returns a rate limiter that allows up to maxEvents in a sliding window of size window. If maxEvents and window are both 0, or if maxEvents is non-zero and window is 0, rate limiting is disabled. This function panics if maxEvents is less than 0 or if maxEvents is 0 and window is non-zero, which is considered to be an invalid configuration, as it would never allow events. func (r *RingBufferRateLimiter) Allow() bool Allow returns true if the event is allowed to happen right now. It does not wait. If the event is allowed, a ticket is claimed. func (r *RingBufferRateLimiter) MaxEvents() int MaxEvents returns the maximum number of events that are allowed within the sliding window. func (r *RingBufferRateLimiter) SetMaxEvents(maxEvents int) SetMaxEvents changes the maximum number of events that are allowed in the sliding window. If the new limit is lower, the oldest events will be forgotten. If the new limit is higher, the window will suddenly have capacity for new reservations. It panics if maxEvents is 0 and window size is not zero. func (r *RingBufferRateLimiter) SetWindow(window time.Duration) SetWindow changes r's sliding window duration to window. Goroutines that are already blocked on a call to Wait() will not be affected. It panics if window is non-zero but the max event limit is 0. func (r *RingBufferRateLimiter) Stop() Stop cleans up r's scheduling goroutine. func (r *RingBufferRateLimiter) Wait(ctx context.Context) error Wait blocks until the event is allowed to occur. It returns an error if the context is cancelled. func (r *RingBufferRateLimiter) Window() time.Duration Window returns the size of the sliding window. StandardKeyGenerator is the standard, in-memory key source that uses crypto/rand. func (kg StandardKeyGenerator) GenerateKey() (crypto.PrivateKey, error) GenerateKey generates a new private key according to kg.KeyType. type Storage interface { // Locker provides atomic synchronization // operations, making Storage safe to share. Locker // Store puts value at key. Store(key string, value []byte) error // Load retrieves the value at key. Load(key string) ([]byte, error) // Delete deletes key. Delete(key string) error // Exists returns true if the key exists // and there was no error checking. Exists(key string) bool // List returns all keys that match prefix. // If recursive is true, non-terminal keys // will be enumerated (i.e. "directories" // should be walked); otherwise, only keys // prefixed exactly by prefix will be listed. List(prefix string, recursive bool) ([]string, error) // Stat returns information about key. Stat(key string) (KeyInfo, error) } Storage is a type that implements a key-value store. Keys are prefix-based, with forward slash '/' as separators and without a leading slash. Processes running in a cluster will wish to use the same Storage value (its implementation and configuration) in order to share certificates and other TLS resources with the cluster. The Load, Delete, List, and Stat methods should return ErrNotExist if the key does not exist. Implementations of Storage must be safe for concurrent use. Package certmagic imports 48 packages (graph) and is imported by 62 packages. Updated 2020-03-22. Refresh now. Tools for package owners.
https://godoc.org/github.com/mholt/certmagic
CC-MAIN-2020-16
refinedweb
5,214
55.95
I am trying to use std::move boost::move std::move std::move (and boost::move) is just a cast from T& to T&&. It does not actually move anything. This means that the specific type of pointer T&& must be supported by the compiler. GCC supports r-value references since version 4.3, so the boost version should be fine. However, is there a reason you can't use std::move from #include <utility>? You just need to make sure to specify -std=c++0x as a compiler option in order to enable the limited c++11 support that gcc 4.4 has.
https://codedump.io/share/N5IWO8pb6m5v/1/the-counterpart-of-stdmove-in-boost-library
CC-MAIN-2017-13
refinedweb
104
66.74
hi I'm new to C# and I didn't have any programming skills. I'm on my third week now and it seems it's quite complex I would like to design a code, where it can determine the word type in the sentence. So, first one must type a sentence and then on the second box, just type a word and check if its present in the first box (from the sentence you typed) the result should show, true or false. I started a code but I don't know how to continue: Any idea or suggestion is greatly appreciated: namespace DisplayWordJaNein public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string yourSentence; string yourWord; yourSentence = textBox1.Text; yourWord = textBox2.Text; if from here I'm not sure what to do. From what I've learned I have to use the type bool here. But don't know how to implement. thanks & regards
https://www.daniweb.com/programming/software-development/threads/178273/how-to-find-a-word-in-c
CC-MAIN-2018-13
refinedweb
161
77.77
hey all, been a while (damn jobs) so im familiar with the rand() function, and how to get a random number within a certain range, but as i was flipping through one of my books i noticed its telling me that i need to include <cstdlib> in order to call the rand() function.. however I ran the following code without it and got the same (random) results... im just curious about how this is happening. Is it simply good practice to include <cstdlib> or was there some kind of C++ update that allows the rand() function to be called without it? not of uttermost importance, just curious this code runs fine for me and still generates random numbers from 1 - 6...this code runs fine for me and still generates random numbers from 1 - 6...Code: #include<iostream> #include <ctime> using namespace std; int main() { srand(time(0)); for (int i = 0; i < 15; i++) { int randomNumber= (rand() % 6) + 1; cout<< randomNumber << endl; } system("pause"); }
https://cboard.cprogramming.com/cplusplus-programming/150142-i-dont-need-include-cstdlib-call-rand-function-printable-thread.html
CC-MAIN-2018-05
refinedweb
165
65.35
I have an optimisation I would like to run when the user presses a button on a Django page. For small cases, it is fine to run it synchronously. However, when it takes more than a second or so, it is not great to have the web server held back by a process of unknown length. The solution I have settled on is Celery, with Redis as the message broker. I am using Redis over the alternatives, since it seems to have much lower memory requirements (I find it uses under 2 Mb, vs. 10-30 Mb per Celery process). And the equivalent commands if you want to use redis-queue (which uses about 10 Mb per worker) instead of Celery are given in this post. There is a bit of a learning curve to get started with this, so I am making a guide for the next person by listing all the steps I have taken to get set up on both my development platform (running MacOS X) and a unix server (hosted by Webfaction). Along the way I hope to answer questions about security and what the right settings are to put in the redis.conf file, the celery config file, and the usual Django settings.py file. Install Redis Redis is the message broker. You will need to have this running at all times for Celery’s tasks to be executed. Installing Redis on Mac OS X is described in this blog. Basically, just download the latest version from redis.io, and in the resulting untarred directory: make test make sudo mv src/redis-server /usr/bin sudo mv src/redis-cli /usr/bin mkdir ~/.redis touch ~/.redis/redis.conf Installing Redis on your server is similar, though you may need to know how to download the code from the command line first (e.g. see this post): wget tar xzf redis-2.6.14.tar.gz cd redis-2.6.14 make test make On the production server we don’t need to relocate the redis-server or redis-cli executables, as we’ll see in the next section. Run Redis To run Redis on your Mac, just type one of: redis-server # if no config required, or: redis-server ~/Python/redis-2.6.14/redis.conf To run it on your Webfaction server, first add a custom app listening on a port, and note the port number you are assigned. Now we need to daemonize it (see this post from the Webfaction community). In summary, in your redis directory, edit the redis.conf file like so (feel free to change the location of the pid file): daemonize yes ... pidfile /home/username/webapps/mywebapp/redis.pid ... port xxxxx # set to the port of the custom app you created To test this works, type the commands below. If all is well, the pid file will now contain a process id which you can check by providing it to the ps command. src/redis-server redis.conf cat /home/username/webapps/mywebapp/redis.pid ps xxxxx # use the number in the pid file Note – when I did this without assigning the port number of the custom app, I got the following error: # Warning: no config file specified, using the default config. In order to specify a config file use src/redis-server /path/to/redis.conf # Unable to set the max number of files limit to 10032 (Operation not permitted), setting the max clients configuration to 4064. # Opening port 6379: bind: Address already in use It turns out someone else was already using port 6379, the default Redis port. Now in practice you will want Redis to be managed with cron, so that it restarts if there is a problem. Webfaction has some docs on how to do this here; I used: crontab -e # and add this line to the file, changing the path as necessary: 0,10,20,30,40,50 * * * * ~/webapps/redis/redis-2.6.14/src/redis-server ~/webapps/redis/redis-2.6.14/redis.conf FYI, for me the running Redis process uses 1.7 Mb (i.e. nothing compared to each celery process, as we’ll see). Install Celery The Celery docs cover this. Installation is simple, on both development and production machines (except that I install it in the web app’s environment with Webfaction, as explained here): pip install django-celery-with-redis I have added the following to settings.py, replacing the port number for production: BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' import djcelery djcelery.setup_loader() INSTALLED_APPS = ( ... 'djcelery', ... ) And added the suggested lines to the top of wsgi.py: import djcelery djcelery.setup_loader() I found lots more detail here, but I haven’t yet established how much of this is required. Run a Celery worker Now you need to start a Celery worker. On your development server, you can enter your Django project directory and type: python manage.py celery worker --loglevel=info On your production server, I started by trying the same command above, to test out whether Celery could find the Redis process and run jobs – and it worked fine. But in practice, the Celery docs say: “you will want to run the worker in the background as a daemon“. (Note this link also talks about Celery beat, which “is a scheduler. It kicks off tasks at regular intervals, which are then executed by the worker nodes available in the cluster.” In my case, I do not need this.) To do this, I copied the CentOS celeryd shell script file from the link at the end of the daemonization doc (since the server I am using runs CentOS), and placed it in a new celerydaemon directory in my Django project directory, along with the Django celeryd config file (I renamed the config file from celeryd, which was confusing as it is the same name as the shell script, to celery.sysconfig). I also created a new directory in my home directory called celery to hold the pid and log output files. One more change is required, at least if you are using Webfaction to host your site: the call to celery_multi does not have a preceding python command by default. While this works in an ssh shell, it does not work with cron - I believe because the $PATH is not set up the same way in cron. So I explicitly add the python command in the front, including the path to python. The config file looks like this: # Names of nodes to start (space-separated) CELERYD_NODES="myapp-node_1" # Where to chdir at start. This could be the root of a virtualenv. CELERYD_CHDIR="/home/username/webapps/webappname/projectname" # How to call celeryd-multi (for Django) # note python (incl path) added to front CELERYD_MULTI="/home/user/bin/python $CELERYD_CHDIR/manage.py celeryd_multi" # Extra arguments #CELERYD_OPTS="--app=my_application.path.to.worker --time-limit=300 --concurrency=8 --loglevel=DEBUG" CELERYD_OPTS="--time-limit=180 --concurrency=2 --loglevel=DEBUG" # If you want to restart the worker after every 3 tasks, can use eg: # (I mention it here because I couldn't work out how to use # CELERYD_MAX_TASKS_PER_CHILD) #CELERYD_OPTS="--time-limit=180 --concurrency=2 --loglevel=DEBUG --maxtasksperchild=3" # Create log/pid dirs, if they don't already exist CELERY_CREATE_DIRS=1 # %n will be replaced with the nodename CELERYD_LOG_FILE="/home/username/celery/%n.log" CELERYD_PID_FILE="/home/username/celery/%n.pid" # Workers run as an unprivileged user CELERYD_USER=celery CELERYD_GROUP=celery # Name of the projects settings module. export DJANGO_SETTINGS_MODULE="myproject.settings" In the shell script, I changed the two references to /var ( DEFAULT_PID_FILE and DEFAULT_LOG_FILE) and the reference to /etc ( CELERY_DEFAULTS) in the shell script to directories I can write to, e.g.: DEFAULT_PID_FILE="/home/username/celery/%n.pid" DEFAULT_LOG_FILE="/home/username/celery/%n.log" ... CELERY_DEFAULTS=${CELERY_DEFAULTS:-"/home/username/webapps/webappname/projectname/celerydaemon/celeryd.sysconfig"} I found a problem in the CentOS script – it calls /etc/init.d/functions, which resets the $PATH variable globally, so that the rest of the script cannot find python any more. I have raised this as an issue, where you can also see my workaround. To test things out on the production server, you can type (use sh rather than source here because the script ends with an exit, and you don’t want to be logged out of your ssh session each time): sh celerydaemon/celeryd start and you should see a new .pid file in ~/celery showing the process id of the new worker(s). Type the following line to stop all the celery processes: sh celerydaemon/celeryd stop Restart celery with cron if needed As with Redis, you can ensure the celery workers are restarted by cron if they fail. Unlike with Redis, there are a lot of tricks here for the unwary (i.e. me). - Write a script to check if a celery process is running. Webfaction provides an example here, which I have changed the last line of to read: sh /home/username/webapps/webappname/projectname/celerydaemon/celeryd restart - This is the script we will ask cronto run. Note that I use restarthere, not start; I am doing this because I have found in a real case that if the server dies suddenly, celery continues to think it is still running even when it isn’t, and so startdoes nothing. So add to your crontab (assuming the above script is called celery_check.sh): crontab -e 1,11,21,31,41,51 * * * * ~/webapps/webappname/projectname/celerydaemon/celery_check.sh - One last thing, pointed out to me in correspondence with Webfaction: the celerydscript file implements restartwith: stop && start So if stopfails for any reason, the script will not restart celery. For our purposes, we want startto occur regardless, so change this line to: stop; start; Your celery workers should now restart if there is a problem. Controlling the number of processes If you’re like me you are now confused about the difference between a node, a worker, a process and a thread. When I run the celeryd start command, it kicks off three processes, one of which has the pid in the node’s pid file. This despite my request for one node, and “ --concurrency=2” in the config file. When I change the concurrency setting to 1, then I get two processes. When I also add another node, I get four processes. So what I assume is happening is: workers are the same things as nodes, and each worker needs one process for overhead and “ concurrency” additional processes. For me, at first I found each celery process required about 30-35Mb (regardless of the number of nodes or concurrency). So three use about 100Mb. When I looked again a week later, the processes were using only 10 Mb each, even when solving tasks. I’m not sure what explains the discrepancy. Use it With this much, you can adapt the Celery demo (adding two numbers) to your own site, and it should work. On my site I use ajax and javascript to regularly poll whether the optimisation is finished. The following files hopefully give the basic idea. urls.py # urls.py from myapp.views import OptView, status_view ... url(r'^opt/', OptView.as_view(), name="opt"), url(r'^status/', status_view, name="status"), # for ajax ... views.py # views.py import json from django.views.generic import TemplateView from django.core.exceptions import SuspiciousOperation from celery.result import AsyncResult from . import tasks class OptView(TemplateView): template_name = 'opt.html' def get_context_data(self, **kwargs): """ Kick off the optimization. """ # replace the next line with a call to your task result = tasks.solve.delay(params) # save the task id so we can query its status via ajax self.request.session['task_id'] = result.task_id # if you need to cancel the task, use: # revoke(self.request.session['task_id'], terminate=True) context = super(OptView, self).get_context_data(**kwargs) return context def status_view(request): """ Called by the opt page via ajax to check if the optimisation is finished. If it is, return the results in JSON format. """ if not request.is_ajax(): raise SuspiciousOperation("No access.") try: result = AsyncResult(request.session['task_id']) except KeyError: ret = {'error':'No optimisation (or you may have disabled cookies).'} return HttpResponse(json.dumps(ret)) try: if result.ready(): # to do - check if it is really solved, or if it timed out or failed ret = {'status':'solved'} # replace this with the relevant part of the result ret.update({'result':result}) else: ret = {'status':'waiting'} except AttributeError: ret = {'error':'Cannot find an optimisation task.'} return HttpResponse(json.dumps(ret)) return HttpResponse(json.dumps(ret)) javascript // include this javascript in your template (needs jQuery) // also include the {% csrf_token %} tag, not nec. in a form $(function() { function handle_error(xhr, textStatus, errorThrown) { clearInterval(interval_id); alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText); } function show_status(data) { var obj = JSON.parse(data); if (obj.error) { clearInterval(interval_id); alert(obj.error); } if (obj.status == "waiting"){ // do nothing } else if (obj.status == "solved"){ clearInterval(interval_id); // show the solution } else { clearInterval(interval_id); alert(data); } } function check_status() { $.ajax({ type: "POST", url: "/status/", data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value}, success: show_status, error: handle_error }); } setTimeout(check_status, 0.05); // check every second var interval_id = setInterval(check_status, 1000); }); As mentioned in the comments to the code above, if you need to cancel an optimisation, you can use: revoke(task_id, terminate=True) Monitoring You can monitor what’s happening in celery with celery flower, at least on dev: pip install flower celery flower --broker=redis://localhost:PORTNUM/0 And then go to localhost:5555 in your web browser. When you use djcelery, you will also find a djcelery app in the admin panel, where you can view workers and tasks. There is a little bit of set up required to populate these tables. More info about this is provided in the celery docs. Security Some links on this topic: - - I’ll add to this section as I learn more about it. I hope that’s helpful – please let me know what you think. One thought on “Asynchronous calls from Django”
http://racingtadpole.com/blog/django-with-celery-and-redis/
CC-MAIN-2019-43
refinedweb
2,325
55.34
by Zoran Horvat Feb 17, 2014 An array of integer numbers is given, such that each number appears exactly twice with exception of two numbers which appear once each. Write a function which finds two numbers that appear once. Example: Suppose that array is 1, 2, 1, 3, 4, 3, 5, 4. All numbers except 2 and 5 appear exactly twice. So the function should return numbers 2 and 5 as the result. This exercise is similar to Finding a Number That Appears Once in Array of Duplicated Numbers. There is also a variation, with a very interesting solution Finding a Number which Appears Once in Array where All Other Numbers Appear Three Times. In exercise Finding a Number That Appears Once in Array of Duplicated Numbers we have discussed a simple method to isolate one number which appears once when all other elements appear exactly twice. The solution was to XOR all the array elements. Since K XOR K is zero for any integer K, we are sure that all duplicated numbers will zero themselves out. The only number which does not cancel itself is the one which appears once. So the result of the operation is that one number. However, this solution cannot be applied directly to finding two numbers that appear once each. Suppose that these numbers that appear once are J and K, and all other numbers appear twice. If we decide to XOR all the array's elements, the overall result would actually be J XOR K. Unfortunately, there is no way to extract J and K out of their XOR. But there is one thing that we can do. Since J and K are different, we are sure that J XOR K is different than zero. This information is valuable in sense that we know pieces of information that differ. If we pick up any bit that is 1 in J XOR K, we can use it as a mask to test each element of the array. Obviously, that mask will be the discriminator between J and K - only one of them will have value 1 at that particular position. Now that we have the mask with exactly one bit set to 1, we can walk through the array once again. But this time we are going to maintain two XORed results. One for numbers that have bit 1 at the mask's position and another for numbers that have bit 0 at that position. In this way, we are sure that all duplicates will go into the same pile. But likewise, we are sure that J and K will go into separate piles. The overall result is that the first XORed result will be equal to J and the second XORed result will be equal to K (or the other way around, but it really doesn't matter). Below is the pseudocode which solves the problem. function GetUniqueNumbers(a, n, out j, out k) -- a - array of integers -- n - number of elements in a -- j - on output first unique number -- k - on output second unique number begin mask = FindMask(a) j = k = 0 for i = 1 to n begin if a[i] AND mask = 0 then j = j XOR a[i] else k = k XOR a[i] end end function FindMask(a, n) -- a - array of integer numbers -- n - number of elements in a begin combined = 0 for i = 1 to n combined = combined XOR a[i] mask = 1 while combined AND mask = 0 mask = 2 * mask return mask end This implementation relies on a helper function FindMask which, as its name implies, calculates appropriate mask which can be used to discriminate J from K. Below is the C# console application which lets the user enter elements of the array and then prints out the two unique numbers. using System; namespace TwoNumbersAppearingOnce { public class Program { static void GetUniqueNumbers(int[] a, out int j, out int k) { int mask = FindMask(a); j = k = 0; for (int i = 0; i < a.Length; i++) if ((a[i] & mask) == 0) j ^= a[i]; else k ^= a[i]; } static int FindMask(int[] a) { int combined = 0; for (int i = 0; i < a.Length; i++) combined ^= a[i]; int mask = 1; while ((combined & mask) == 0) mask <<= 1; return mask; } static void Main(string[] args) { while (true) { int[] array = ReadArray(); if (array.Length == 0) break; int j; int k; GetUniqueNumbers(array, out j, out k); Console.WriteLine("Numbers that appear once are {0} and {1}.", j, k); Console.WriteLine(); } } static int[] ReadArray() { Console.Write("Enter array elements (ENTER to quit): "); string line = Console.ReadLine(); string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); int[] array = new int[parts.Length]; for (int i = 0; i < array.Length; i++) array[i] = int.Parse(parts[i]); return array; } } } When application is run, it produces the following output: Enter array elements (ENTER to quit): 1 2 1 3 4 3 5 4 Numbers that appear once are 2 and 5. Enter array elements (ENTER to quit): 1 2 1 3 5 3 5 4 Numbers that appear once are 4 and 2. Enter array elements .
http://codinghelmet.com/exercises/two-numbers-appearing-once-in-array
CC-MAIN-2019-04
refinedweb
850
70.43
This is a small self-contained header file implementation of a static counter for use at compile-time. The features of this implementation are: __COUNTER__ Boost::Preprocessor Currently this implementation is only capable of use on a small scale, within 50-100 lines for each counter instance. It was designed to be embedded within another MACRO, where each time the outer MACRO is called, the counter increments. This utility would be useful for creating unique registration ids, or automated index entries. Recently I have been developing a network communication library, Alchemy[^]. Alchemy automatically manages byte-order conversion of data for network transfer. It is capable of programmatically inspecting message definitions and performing the proper conversions. This task is performed by iterating over an array of types that define the message. I iterate over the type list starting with a zero-based index. I saw an example in Advanced C++ Metaprogramming by, Davide Di Gennaro, of a template meta-program that used the __LINE__ preprocessor MACRO to define unique identifiers. His example showed a template that used indexing starting from zero and counting up to return the line-number the template was defined on as a unique ID. I thought if I could build the reverse template, that would be one less field for users to defined. I first turned to the Internet, and I could not find a solution to this problem. So I set out to find a solution, and that is what I present to you here. __LINE__ It is a set of MACROs that must be unique to a particular scope. They can be used in a class definition or namespace. Unfortunately, it's not possible to instantiate this version of the counter inside of a function. Even from inside of a nested class. Sorry, Demz da rulz. Here is a quick demonstration of what using the counter looks like. // Basic use declaration. DECLARE_COUNTER // Line: Base INC_COUNTER // Line: Base + 1 INC_COUNTER // Line: Base + 2 INC_COUNTER // Line: Base + 4 INC_COUNTER // Line: Base + 8 INC_COUNTER // Line: Base + 10 The previous block creates a set of templates that will return the counted index declared on a line, when passed the line number - base number. The block of code below demonstrates how the values are extracted from their declarations. cout << "line(1) value: " << auto_index<1>::value << "\n" << "line(2) value: " << auto_index<2>::value << "\n" << "line(4) value: " << auto_index<4>::value << "\n" << "line(8) value: " << auto_index<8>::value << "\n" << "line(10) value: " << auto_index<10>::value << "\n"; // The output is: // // line(1) value: 0 // line(2) value: 1 // line(4) value: 2 // line(8) value: 3 // line(10) value: 4 // This contrived example is intended to demonstrate the separate components of the utility. First there is the counter definition, second the auto_index template that is used to query the index. The previous block would be difficult to use correctly in any non-trivial program. That is why this counter is intended to be embedded within a user-defined MACRO. This will allow the increment call, and the index access to occur on the same line. auto_index The block below demonstrates an example closer to how the static counter was intended to be used: // Sample Usage MACRO #define REGISTER_OBJECT(CLASS) \ INC_COUNTER \ static const size_t CLASS::k_uid = auto_index<__LINE__ - k_base>::value; // Each type of class to be registered needs a unique ID, // There is an internal constant named k_uid that holds this id. DECLARE_COUNTER REGISTER_OBJECT(ObjectTypeA); REGISTER_OBJECT(ObjectTypeB); REGISTER_OBJECT(ObjectTypeC); REGISTER_OBJECT(ObjectTypeD); After the preprocessor runs, the use of the __LINE__ compiler MACRO will appear on the same line as the declaration of INC_COUNTER. When the base enumeration line number is subtracted from this instantiation line number, a new value will be defined with the next index value, starting from zero. The first thing that I would like to mention, is that I was originally attempting to create a set of template only definitions for the implementation. However, there is one thing that I was just not able to find a solution around, template specialization. Template specialization has a restriction, that it must be performed within the namespace or a parent namespace, where the template definition resides. When I reached the solution that was mostly working, I tried to apply the counter towards the purpose for which I created the counter to begin with. I quickly realized it was not going to work because my use required the counters to occur in a class scope. I then spent a few days away from this project. When I returned, I realized that if I converted these templates to a MACRO, I could redefine a set of these templates within whatever scope that I wanted to use the counter. This actually is a better solution, because multiple counters can be used in a single compilation unit. They simply need to be placed in their own scope. In principle, the concept is very simple. For each instance of the auto_index template that is defined: Unfortunately, this turned out to be one of those problems where the devil is in the details. It is important to remember that once a declaration is started for a single counter instance, the entire definition with the instantiation must be completed with the declaration of a single statement. Because the goal of this solution is to have a single MACRO, which is called the exact same way every time it is instantiated. Yet it must still increment a value. Here are the other challenges that I had to consider or overcome to reach a solution: What the hell is a Quantum Template? This one had me tied in knots attempting to work through a solution. Fairly early I had arrived at the counting backwards solution design. I also decided that I would mark the valid lines with the enum_entry template, defined with the true_type. That would leave lines that did not have a definition to return false_type when enum_entry was queried to see if the current line defines an index. enum_entry true_type false_type This is when I saw Schrodinger's Cat in template form. I am trying to discover if a template definition was valid or not. However, the moment that I query for that template, I have just defined it. If I had just left it alone, it wouldn't have existed. This is where template specialization became necessary. I was shooting for a solution where I simply defined a template for lines that were to increment the counter. However, there is simply no way to generically define a valid line as well as the invalid line. In order to break this maddening cycle, I had to turn to specialization. Here is the default template definition. This declaration marks the entry as not a valid enumeration by default. template<int N, bool IsValidT = false> struct enum_entry : std::integral_constant<bool, IsValidT> { }; This is the specialized template that is defined for each line that increments the counter. template < > struct enum_entry< (ID) > : std::true_type { }; After the enumeration entry specialization has been created, the auto_index < int L < must be called in order for the counter value to be assigned in increasing order just as the lines are defined. This sets the recursive template processing in motion. auto_index < int L < template <int L> struct auto_index : std::integral_constant< int, index_before<L>::value + 1 > { }; The template is defined to create a simple static constant, where the current value of the counter will be set to the last value plus one. std::integral_constant< int, index_before<L>::value + 1 > index_before is a convenience template to simplify the first request for the previous index. This sets the search in motion to start at the previous line, and count back by one, until the last valid enum_entry template has been found. index_before template <int L> struct decrement_until_match : std::integral_constant< int, value_if< enum_entry<L>::value, int, auto_index<L>::value, decrement_until_match<L - 1>::value >::value > { }; Let's zoom in and take a close look at the decision point. value_if< enum_entry<L>::value, // Predicate int, auto_index<L>::value, // Previous Index Found decrement_until_match<L - 1>::value // This is not a valid line, >::value // search the previous line. value_if is a conditional template that I wrote to simplify the syntax required when making a Boolean decision, then assigning a value based on the result TRUE | FALSE . Its behavior is the moral equivalent of the ternary operator ?: for meta-programming. The implementation is straight-forward. There are two definitions of the template; one for the true case and one for the false case. value_if TRUE | FALSE ?: true false // *************************************************************************** /// This construct provides the compile-time equivalent of /// the ternary operator ?: for value selection. /// template <bool predicate, typename T, T trueValue, T falseValue> struct value_if : std::integral_constant<T, trueValue> { }; // *************************************************************************** /// Specialization for the false condition of the value selector. /// template <typename T, T trueValue, T falseValue> struct value_if<false, T, trueValue, falseValue> : std::integral_constant<T, falseValue> { }; Finally, there is a terminating enum_entry specialization, and a template to act as the seed value for the first index. // Terminating enum_entry. Do not search before line 0. template<> struct enum_entry<0, true> : std::true_type { }; // Initial auto_index specialization to // start the first index at 0. template <> struct auto_index<0> : std::integral_constant< int, -1> { }; Because the INC_COUNTER MACRO depends on the __LINE__ compiler MACRO, each increment definition must be defined on a different line. This also means that INC_COUNTER cannot appear in the same multi-line MACRO more than once. The INC_COUNTER call does not need to appear sequentially. This is because of the search for the last index that was declared, rather than a simple offset from base calculation. INC_COUNTER Since the implementation relies on recursive template instantiation to calculate the next index, there is a limitation dependent on the nesting depth of your compiler. The declarations for a set of counting MACROs must be relatively close together as well. Therefore, I recommend that you embed these MACROs inside of other MACROs and create a declaration block with your definitions. It would probably be possible to modify the counting loop to add conditional statements to take one path for odd numbers, and another for evens. This would effectively double the depth. I did not explore any of these options because what I have presented currently suits my needs. Also, I did not want to over complicate something that I think is already complex. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Quote:It was designed to work embedded in a MACRO. Where, each time that MACRO is called, this counter increments. Quote:My library required an index starting from zero, and counting up from there. General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/776770/Automatic-Static-Cplusplus-Counter-with-Scope
CC-MAIN-2016-44
refinedweb
1,800
53
Automatic transformation of XML namespaces/Extracting information from RDF From Wikiversity Every time an RDF file is loaded, the following algorithm takes place: - If the file is invalid and user specified the option to completely reject invalid RDF, then the following is skipped. - Store all triples with predicates rdfs:subClassOf and :higherThan and :lowerThan. - process rdfs:seeAlso as described below. - For every of the below defined RDF classes (:Namespace, :Transformer, :CommandLine, :NamedScript, :WebService) find start nodes that is RDF nodes which have rdf:type predicate with the given class as object. - For every start node and its corresponding grammar tree verify that it conforms to the tree and do all other validation checks. - Reject information from start nodes which violates any validation rules. Extract namespaces, transformations, and precedences as get from the rest (that is valid) start nodes and their grammar trees. Note that the information is extracted in the order of triples in the RDF file. When processing scripts (for validation of a namespace or for a transformer), just ignore scripts of unknown rdf:type.
https://en.wikiversity.org/wiki/Automatic_transformation_of_XML_namespaces/Extracting_information_from_RDF
CC-MAIN-2017-17
refinedweb
176
52.19
These are chat archives for opal/opal object.foo(), or someything like that (and perhaps something better than .js) def has_attribute?(name) `!!self.attr(name)` end but it can potentially break appsbut it can potentially break apps def has_attribute?(name) `self.attr(name) !== undefined` end As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. def [](name) %x{ var value = self.attr(name); if(value === undefined) return nil; return value; } end - Element#[]and Element#attrnow return nilfor empty attributes, instead of returning an empty string. TypeError: wrong argument type Method (expected Proc/Method) rendermethod returns a scalar, a virtual DOM node, or an array of any combination of those, that's all that's needed.
https://gitter.im/opal/opal/archives/2015/05/18
CC-MAIN-2019-18
refinedweb
122
51.14
Dear friends of Backend service, welcome back to our tutorial series You’ve successfully gone through the tutorial blog 1 easy API creation, haven’t you? Yes, but ohhh… You are somehow not fully satisfied ? ehmmm I guess I know why: you’re missing the explanations of what you were doing bingo! Please read on, here comes an attempt to make you more happy What is it, the CDS model? CDS stands for Core Data and Services How do I know that? I’ve looked it up in the documentation thanks, but that doesn’t help me The CDS definition language allows to define models Going further, CDS allows to define models in 3 aspects: – Define data model – Service definition – Attach user interface information We will completely ignore the third aspect here Both other aspects, data model and service definition, were used in the tutorial sample Let’s have a closer look What about the data model? Data model means we want to store data in a structured way. In Backend service, a database is used, but you don’t really need to care about it. I just think it is helpful to have a concrete idea of what we are doing. In the data-model-part of our CDS file we say how we want to persist data in a database. In our sample, we say that we want a “Products” – entity with properties “Name” and “Category” and “ProductId” entity Products { key ProductId : Integer; Name : String; Category : String; } With other words, we say that we want a database table (“Products”) with several columns (“Name”, Category, etc) With other words, we say that we want to execute an SQL statement like CREATE TABLE Products (ProductId int, Name varchar(255), …); OK, I understand, I need to learn CDS language, such that I will be able to describe the data model which I need for my application. The Backend service takes care of generating the database tables and filling the data into it. Correct? Yes, I see you’re seriously following. BTW, the Backend service does much more for you, in terms of maintaining the data and operating the database for you. But that’s a larger topic than what we’re discussing here. Sounds promising. What about the service definition? CDS not only allows to describe a data model. It also allows to define services. And it really means “services”, in the sense of REST services. More concrete: In your CDS file you define a “service” element and as a result you get an OData service which you can use to read and create the data in the database. In the service-definition-part of our CDS file, we say that we want data to be exposed as a service In our sample, we say that we want a service to be generated with name “MyFirstService”, and moreover, we define which data should be exposed service MyFirstService{ . . . The data to be exposed can refer to an existing data model. Or, alternatively, it can be defined directly in the body of the service, that’s what we did in our sample in our tutorial. With other words, while defining a “service” in CDS, we say that we want an OData service. This OData service itself declares metadata containing “Products” Entity Type with Properties and “Products” Entity Set and “MyFirstService”-namespace and other OData elements. The metadata document of the OData service which we created in our tutorial [1] looks like this: huh… it looks very similar to the CDS Thank you for this comment, yes, indeed, CDS and HANA and SQL and OData are like brothers and sisters of the same family… What about the third aspect? We wanted ignore this one… Just short summary: CDS allows to attach UI annotations to every model element. The annotations can then be interpreted to generate user interfaces. For example, a property can be declared (with annotation) to be used as phone number, such that in the user interface it can be represented with a phone icon and dialer But we wanted to ignore this feature. OK Why these 3 aspects? The goal is to have one common and generic definition file which is fully protocol and database agnostic. Like that, you can describe your application irrelevant of how the persistence would be realized. Concrete: In a subsequent step, the CDS file is translated into the target formats. In our case, roughly speaking, the database and the OData metadata (edmx) Example: In your CDS, you define a service, but as you can see at the end, there’s no distinction between the version of OData (OData V2 or V4) What else is happening under the hood? Oh, let’s leave this for a future discussion For the moment, I think it is enough to know that under the hood, the CDS model is parsed and transformed into artifacts which are then served to the infrastructure which is even more under the hood (like database, OData service runtime) I’m confused, can you please summarize? We need to create a CDS file which defines a data model and a service. Then we pass it to the Backend service The Backend service reads this input and: – based on the data model, it generates database tables, to store the data in a database – based on the service definition, it generates an OData service, allowing standardized access to the data via internet The Backend service provides you with access to the generated API (which is the OData service) Why CDS at all? The Backend service wants to make life easy for you, so you don’t need to handle database and scaling and service implementation and all that stuff. The intention is to allow the user to model the data in a human readable way. As such, the input for Backend service is a model definition file. Currently, 3 formats are supported – OpenAPI is a widely adopted standard, so it is good that it can be used. – EDMX is anyways used to define OData metadata – CDS, yeah, CDS is the best, because it is the most powerful. You can attach meta-information to the data model definition and it will be automatically supported Please refer to the overview page to see more CDS Tutorials with detailed examples How to learn more about CDS? Of course, following my blogs… Hihi More serous answer: the official SAP documentation Do you still have questions? I know you won’t hesitate to send me messages with questions and I will try to add answers to this blog posting Great stuff Carlos Roggan , much needed for everyone working with CDS. I must admit when i started with CDS i was super confused and have to struggle a lot to have the better understanding. You blog series will help every CDS enthusiast in understanding the concepts in details. Hi Nabheet Madan good to know that I wasn’t the only one, to be confused in the beginning… 😉 Thanks so much for your awesome comment 😉 Great Blog Carlos Roggan ! It really was an enjoyable and interesting read for me, really liked the way you commented yourself during the Blog. Keep it up! Thanks so much Marco Beier for your feedback! Such comment is what encourages to continue writing ! 😉 Hi Carlos, Reading your blogs i realised here you calling API which you created in backend-service in SAP cloud cockpit. Please tell me is there any way where i Can write a node.js application which will call my data from backend which i exposed via a communication arrangement in my S4 system? Please reply if any more clarification needed. Thanks in advance I Posted in community also Hello Swastik Mukherjee , Thanks very much for reading my Blogs, and for reaching the end and for writing a comment 😉 Your Question isn’t related to the blog Topic at all, so I’d like to ask you to send me a personal message, Maybe I can help a bit. Nevertheless, I’m Pretty sure that the SDK Folks are going to answer your Question very soon. Cheers, Carlos Great Blog Carlos Roggan ! I’m very interested to know more about the third aspect where we attach user interface information. Can you please suggest another supports wish explain this part? Hello Mariam Id-Manssour Thanks very much for the feedback! I will give an example for the Fiori-annotations once they will be supported by Backendservice. In the meantime, you can go ahead with CAP application and use them. The annotations themselves: There are no specific CDS annotations for UI. Here we’re talking about Fiori Elements, UI is described by annotations. For instance, you have a property and you declare that whenever it is displayed in a UI, the label for it will be “First Name”. Such a “label” annotation is part of Fiori Elements, not CDzS. As such, in CDS you can just use the FE annotation. As such, there’s no specific CDS documentation to be expected. You have to google for Fiori Elements docu and Blogs, you’ll find them here in the Community Kind Regards, Carlos Hi Carlos , Thank you for your response . I followed the course from openSAp “Building Applications with SAP Cloud Application Programming Model” to build the back-end OData service using SAP Cloud Business Application Studio . Now I want to use the Fiori elements templates to Speed up development and build the front end of my app and bind it to my Odata back-end service that I already created and deployed to SCP CF environment. I’m wondering how can I create my Fiori app project within my previous SAP Cloud Platform Business Application Project (srv db folder etc ..) and establish the data connection between my Odata service back-end and the Fiori app front-end . I tried to set destination in SCP using the URL of my OData service like is mentioned in those tutorials below using Northwind or ES5 OData service but it’s not working is no such service “destination” in the drop down list. -using SAP WEB IDE ( step 4) -Using SAP Business Application Studio ( step 3 point number 8 ): So How can I create Fiori elements app from template wizard and point to the “Srv” folder with in workspace for services while using the Fiori create from template wizard ? Should I use SAP WEB IDE or SAP Business Application Studio to develop my front end ? Note: I checked the official documentation on serving UIs: it was mentioned that for adding fiori apps to CAP model project i have to copy the the fiori apps folder from sap/samples project on github as a template and modify the content as appropriate. But it doesn’t work properly . I will greatly appreciate your help . Any pointers/ suggestions/ links would be helpful. Thank you . Hello Mariam Id-Manssour , BTW, you can contact me via personal message and I can send you example CDS from project with all 3 flavors Cheers, Carlos
https://blogs.sap.com/2019/02/11/sap-cloud-platform-backend-service-tutorial-1.1-about-cds-model/
CC-MAIN-2020-50
refinedweb
1,834
58.01
Unity 4.6.2 The Unity 4.6.2 release brings you some improvements and - Support for iOS 64-bit builds using il2cpp. Changes - The Flash build target is no longer supported from this release onwards. Improvements - Audio: Added. Allows AudioClips obtained via WWW class to be loaded into memory compressed, similar to "Compressed in Memory" import option. - Graphics: Added MaterialPropertyBlock.Set*() methods to overwrite existing values in a MaterialPropertyBlock instead of adding duplicates. - iOS: Add basic launch screen support. - iOS: Expose “set pause” as ObjC API. - Linux: Added more font fallbacks for Latin and CJK. - Oculus GearVR: Enabled low latency audio support. - Oculus Plugin: Future Oculus Plugin releases will no longer require Direct_To_Rift.exe - Oculus: Added VR friendly splash screen for Unity Free. - Scene View: DrawGizmo attribute now reports errors when used incorrectly, and has better documentation. - Standalone: Screen.dpi implemented for OSX and Windows standalone platforms. - UI: Change Text.m_Text to protected and Text.text to virtual. In this way users can have control over the text contents when extending Text. - UI: Expose EventSystem.firstSelected to API. - WebPlayer UnityObject: It is now possible to identify the webplayer runtime version before loading content. This makes it possible to load different content based on the runtime version already installed. Fixes - 2D: Custom sprites are now forced to have unique name when created through Sprite Editor. - 2D: Fixed PolygonCollider2D mesh generation on Android. - 2D: Hotkey for sprite Trim 'T' doesn't intervene with sprite naming anymore. - 2D: Single sprite pivot will be now properly saved in Sprite Editor. - 2D: Sprite importer multi-editing now works for packing tag, pixels per unit and extrude fields. - 2D: Sprite Packer page list is now refreshed after packing. - Android: Android TV - do not strictly require accelerometer and microphone. - Android: Fix for NullReferenceException causing a crash. - Android: Fixed a file-loading problem which occasionally caused 'Inflate Error' messages & freezes or crashes when loading resources on Android. - Android: Fixed broken texture upload from OnApplicationPause(false). - Android: Fixed build failure on x86 Java on Windows. - Android: Fixed CJK fonts on Android Lollipop. - Android: Fixed possible crash in hardware stats code. - Android: Fixed deadlock when calling UnityPlayer.pause() too early. - Android: Fixed freeze during startup on some Amazon Kindle devices. - Android: Fixed freeze on focus change when app is not paused (e.g. keyboard input). - Android: Fixed Japanese Kana fonts on Android Lollipop. - Android: Fixed lights-out mode on Android Lollipop. - Android: Fixed possible lost wakeup in UnityPlayer when rapidly calling pause/resume. - Android: Fixed theme attribute in default manifest to hide title bar during startup. - Android: Increase maximum memory available to Java when building for Android. - Animation: Animation window no longer shows 'Function not supported' for events on secondary MonoBehaviours. - Animation: Don't expose multiple entries for a source clip in AnimatorOverrideController. - Animation: Optimize and DeoptimizeTransformHierarchy are available in runtime as well as editor. - Asset Import: Imported assets now update the project label database correctly. - Asset Import: Restored previous behaviour of AssetModificationProcessor.OnWillSaveAssets to ignore null or void return values. - Asset Import: Reserialize imported .unitypackage assets to comply with project's Force Binary / Force Text serialization setting. - Core: Fixed incorrect error message when RectTransform.GetWorldCorners is called with incorrect parameters. - Core: PPtr animations now properly trigger the OnDidApplyAnimationProperties callback. - Editor: Allow viewing of all ModelImporter tabs when the model is not open for edit. - Editor: Fixed importing of .DDS textures with XRGB color formats. - Editor: Fixed a bug where driven RectTransform would incorrectly mark the scene dirty if it had a Vector2 where one coord was driven and the other not. Such a setup is common with the ContentSizeFitter UI component. - Editor: Fixed a small memory leak related to FormerlySerializedAs attribute. - Editor: Fixed bugs that caused UnityEvent object references to change by themselves with no user action when selecting multiple objects. - Editor: Fixed lagginess in editor when destroying multiple elements. - Editor: Fixed navigation to next / previous animation keyframes when there are subframe keyframes. - Graphics: Worked around some GPU driver bugs that were causing crashes when using OpenGL ES 3.0. - Graphics: Fixed possible memory corruption when using dynamic batching on platforms that support NEON. - Graphics: Fixed D3D9 handling of unsupported BGRA32 texture format to fall back properly to ARGB32. - Graphics: Texture2D.PackTextures will produce an ARGB4444-format atlas if all input textures are ARGB4444/RGBA4444. - iOS: Do not rotate splash view on non 6+ iPhones. - iOS: Ensure that Input.touches is not changed during the frame. - iOS: Fixed 2nd stage splash orientation on iOS 8.0+ landscape. - iOS: Fixed crash when text field contents are modified via script and undo is used. - iOS: Fixed OpenGL ES backbuffer size determination (fixes iPhone6+ zoomed mode). - iOS: Fixed local notifications for iOS 8.0. You should call NotificationServices.RegisterForLocalNotificationTypes before scheduling first notification. - iOS: Fixed messed up terminal settings if building for iOS from console. - iOS: Fixed skewed image on secondary display (AirPlay). - iOS: Fixed splash screen check on Xcode 5 when iPhone 6 splashes are present. - iOS: Fixed Xcode 6.2 support. - iOS: Increased stack allocator size on iOS. - iOS: On iOS set no backup flag on __info cache file. - iOS: Register SubstanceArchive when procedural materials are used. - iOS/IL2CPP: Correctly emit method, property, field, and event counts for array types - iOS/IL2CPP: Dramatically reduce the amount of warnings the generated code produces. - iOS/IL2CPP: Fixed Armv7 linker errors ("b/bl/blx ARM branch out of range"). - iOS/IL2CPP: Fixed crash in reflecting over custom attributes. - iOS/IL2CPP: Gamecenter integration works now. - iOS/IL2CPP: Fixed incorrect code being generated for open generic types deriving from UnityEngine.Object. - iOS/IL2CPP: Fixed memory leak in reflection code. - iOS/IL2CPP: Fixed race condition in internal reflection implementation. - iOS/IL2CPP: Ignore managed types not in the UnityEngine namespace when the types which should not be stripped are discovered. - iOS/IL2CPP: BinaryFormatter serializer works now. - iOS/IL2CPP: Generated C++ code is a lot easier to read now. - iOS/IL2CPP: Treat arrays created with a lower bound of zero (via Array.CreateInstance) as SZARRAY types. - Linux: Make device unique identifier more consistent. - Mac OS X Standalone: Release player builds are now stripped off symbols again. - MonoDevelop: Generated solutions include 'indent size' directive to match tab size now. - Oculus Plugin: Fixed GearVR Unity Pro + Android Basic license issue. - Physics 2D: HingeJoint2D gizmo is displayed correctly with respect to any reference angle. - Physics 2D: Changes to the EdgeCollider2D points are now saved when used in prefabs. - Physics 2D: Setting the Rigidbody2D position or rotation directly now wakes the body. - Physics 2D: SliderJoint2D & HingeJoint2D reference angles are now reset when connecting to another Rigidbody2D. - Physics 2D: Static 2D collider gizmos now render at the correct Transform Z position. - Scripting: Fixed a harmless but annoying error message when using StopCoroutine(Coroutine). - Scripting: Fixed issue with Console.InputEncoding and Console.OutputEncoding throwing an exception the first they were set on the .NET 2.0 Subset profile. - Shaders: Fixed editor memory leak in shader error reporting. - UI: Changing any Transition settings on a Selectable Component will now immediately reflect on the Scene and Game View. - UI: Don't apply AspectRatioFitter logic when component is inactive. - UI: Fixed a bug which caused wrong Y cursor alignment in TextField with custom fonts. - UI: Fixed division by zero if ScrollRect content size has zero width or height. - UI: Fixed issue where adding and removing a parent canvas wouldn't update parent canvas relationship of child objects. - UI: Fixed issue where keyboard would not display on mobile devices. - UI: Fixed regression with events being sent to wrong object in some cases when using multiple GraphicRaycasters. - UI: Make sure we copy the pointer enter for the right and middle mouse pointers when we fetch them. - UI: Moved EventSystemEditor from UnityEditor.UI namespace to UnityEditor.EventSystems namespace. - UI: Prevent the '/n' from appearing when reactivating an input-field in the disable call. - UI: Sliced image with transparent borders (padding) works correctly with non-default pixelsPerUnit. - UI: When activating the standaloneInputModule do not set selected element to NULL. - Version Control: Fixed drag-dropping assets between change lists only moving a single asset. - Windows Phone 8: It's now possible to specify plugins that should not be processed just like in Windows Store Apps. - Windows Phone 8.1/Store Apps: Fixed an issue which caused casting arrays in UnityScript sometimes throw MissingMethodException deep inside Boo.Lang.dll. - Windows Phone/Store Apps: Fixed a rare crash that was caused by skinned meshes. - WWW: Fixed bug in WWW Caching when is canceled using. Changeset: Unity 4.6.2
https://unity3d.com/ru/unity/whats-new/unity-4.6.2
CC-MAIN-2021-04
refinedweb
1,416
52.66
Fluent APIs Make Developers Love Using Your Libraries James Hickey Updated on ・4 min read Ever find yourself frustrated with 3rd party libraries that are supposed to be useful? Easy to use? Ever gone back to some nice/reusable class that you built a few weeks ago only to realize you have no idea how to get started with it. Nothing obviously sticks out as a starting point? So, you decide to check out the documentation only to spend an hour trying to figure out how to get started with the one thing you need the library for! I've been there so many times! Throughout my career, I've always wondered if there was a way to build reusable pieces that are just 100% plain and obvious to use. Something that just guides you through the proper usage. Let's Learn From The Best Let's try to learn from the best. The tools that are the easiest to use. Here are a few tools that I personally find are enjoyable to use: - Laravel (PHP Framework) - JQuery - .NET Core - LINQ These represent, to me, some of the easiest-to-use yet powerful tools I've encountered in my career. I don't use JQuery anymore, nor will I (by choice). But everyone would agree that JQuery made working with the DOM enjoyable compared to the native tools at the time. So - what do all of these tools have in common? What makes them so easy to use? They are Fluent APIs. Eh? What's A Fluent API? The term "fluent" has the connotation that "fluent API" somehow relates to (spoken) languages. You can be fluent in English, for example. Fluent interfaces are a style of programming that focuses on how your code reads easily and naturally - like you are reading a book. Readability For example, in .NET Core you might find code like this: app.UseDeveloperExceptionPage() .UseDatabaseErrorPage(); This is very easy to understand and to read. You intend to use the developer exception page (which has nice debugging info for developers). You also wish to use some special error page when you get database errors. Unlocking New Methods Let's look at another example: services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); In this example, calling the AddMvc method unlocks access to other methods that only make sense within that specific context. This to me is the most powerful aspect of fluent interfaces - they only let you use what makes sense to use within the current context. Other Benefits When a fluent API is done properly you shouldn't be able to: - Call methods in the wrong order (ever used code like this?) - Be confused where to start (since the IDE intellisense will tell you what methods are available to "get started") - Call methods in a specific chain partially. (E.g. "You forgot to call the "Done" method of some class so it never performed it's logic) If you want to continue reading about these ideas you can read this post where I discuss more benefits you get with fluent APIs. Applied To A Real Library For the reasons above (and the reasons in the post I linked to) I opted to use a fluent API when writing Coravel. I think this is one of the main reasons that people are using it - it's so easy to work with. For example, can you figure out what this code is intending to do? This is how easy code written in a fluent style can be to understand. There's no mistaking what this code does. Wizard-like Code Completion Take this example of me using Coravel in Visual Studio Code: When someone wants to schedule something they get access to new methods. These methods are only ever available in the context of scheduling something. There's no bleeding of methods from other contexts here. After selecting the frequency those methods are gone and you get access to a new group of selections: Let's Build A Fluent API Right Now! So you're dying to know - how do I actually build one? Building basic fluent APIs can actually be really simple. The key "trick" is that the methods in your class can return an interface that restricts what methods the caller can use. Here's what a working example might look like: public class MyFluentClass : ICalculation, IResult { private int _value; private int _result; private MyFluentClass() { } public static ICalculation WithValue(int value) { return new MyFluentClass { _value = value }; } public IResult Add(int toAdd) { this._result = this._value + toAdd; return this; } public IResult Subtract(int toSubtract) { this._result = this._value - toSubtract; return this; } public int Result() => this._result; } public interface ICalculation { IResult Add(int toAdd); IResult Subtract(int toSubtract); } public interface IResult { int Result(); } Things to notice: - Use a private constructor so the caller is forced to use the static factory method - The static factory method has access to the instance's private members WithValuereturns the interface ICalculation. This is what begins to restrict what methods the caller can use. Addand Subtractreturn the interface IResult. This is what unlocks the next series of methods in the chain (which happens to be Result). Here's what it looks like in action: Conclusion Thanks for taking the time to go through this - I hope you learned something new and enjoyed the content! By the way, this is part 2 of my series "What I've Learned So Far Building Coravel". Here are the other parts of the series: Part 1 - What I've Learned So Far Building Coravel (Open Source .NET Core Tooling) This post originally appeared on builtwithdot.net's blog.! Love fluid API's. Decided to re-write our Messaging library on .NET Standard earlier last month. Followed this approach, and have been hearing nothing but good things from the team since they upgraded. Awesome! That proves it's not only a helpful pattern for public libraries 👍 Learning about fluent UI's and how to design them was one of the most pivitol moments in my career, no joke. Great post! I love fluent APIs. But please, please don't make fluent APIs mutable! They become very confusing. Consider this code using your class: This is one of the things that is killing moment.jsthat otherwise was pretty great. I would agree 100%. The class I used in the article actually wouldn't work in the snippet you made 😉 The second line of your code snippet would throw an exception since the only available method would be Result, which I highlighted in the article. It should actually do what you want (immutable) 👍 You are right, sorry, my bad! Try this: Sure, anyone can try to misuse code if they really want 😜😂
https://dev.to/jamesmh/fluent-apis-make-developers-love-using-your-libraries-2d7c
CC-MAIN-2020-16
refinedweb
1,117
64.2
I've been building a web application for the past month, and things have been going surprisingly smoothly for how new I am to all of this. That is, until yesterday, when I did an AJAX overhaul on a page to provide users with live feedback of a server-side process. Now when I boot up the application, I get an error on my first line of code (which has produced no problems up to this point) where I check the session object to see if an operation is active. I am getting the error: UnboundLocalError: local variable 'session' referenced before assignment if 'active_op' not in session: print 'bizbaz' session = {'foo':'bar'} Make sure you import session before you use it from flask import session EDIT The main problem was that you were assigning a dictionary to the 'session' variable which you should not do. # Incorrect session = {'foo':'bar'} Instead, it should be session['foo'] = 'bar'
https://codedump.io/share/QmVfJHXktI3z/1/flask-session-variable-not-allowing-assignment
CC-MAIN-2017-30
refinedweb
156
57.74
Best Practices for Developing Web Parts for SharePoint Products and Technologies Susan Harney Microsoft Corporation June 2004 Applies to: Microsoft Windows SharePoint Services Microsoft Office SharePoint Portal Server 2003 Summary: Using the programming model behind Windows SharePoint Services, you can create your own Web Parts that provide new functionality to enhance your Web Part Pages. Learn best practices to improve performance and usability of Web Parts, and ways to create Web Parts that integrate well with other components of a Web Part Page. (15 printed pages) Contents Description Attributes Conclusion Introduction This article offers guidelines that are recommended best practices for Web Part developers. You can use them to improve the performance and usability of the Web Parts you design, and to assist you to create Web Parts that integrate well with other components of a Web Part Page. Note These guidelines are common to all Web Parts. They are not designed to test Web Part-specific functionality. Handle All Exceptions to Prevent Web Part Page Failures Your Web Part should handle all exceptions rather than risk the possibility of causing the Web Part Page to stop responding. You can help make this possible by placing the sections of code that might throw exceptions in a try block and placing code to handle these exceptions in a catch block. Following is an example. private void SetSaveProperties() { if (this.Permission != Microsoft.SharePoint.WebPartPages.Permissions.None) { try { SaveProperties = true; } Catch (Exception ex) { // Setting SaveProperties can throw many exceptions. // Two examples are: // 1) SecurityException if the user doesn't have the "ObjectModel" // SharePointPermission or the "UnsafeSaveOnGet" // SharePointPermission // 2) WebPartPageUserException if the user doesn't have sufficient // rights to save properties (for example, the user is a Reader) errorText = ex.Message; } } } For more information, see Using the Try/Catch Block to Handle Exceptions in the .NET Framework Developer's Guide in the MSDN Library. Check Permissions Before Rendering Your Web Part and Customize the User Interface Accordingly Because Web Parts are managed by the user at run time, you should render your Web Part with a user interface that is appropriate for each user's permissions. To do this, always check the Permissions property before rendering the Web Part—if the value is None, you should suppress the portions of your Web Part user interface that require certain permissions. For example, if a Web Part displays a Save button, you can disable or hide it if the user does not have permissions to save changes. If a user is unable to use your Web Part as you designed it, several things could be happening: - The user is a Reader. - The Web Part is not in a Web Part zone. Although your Web Part may be designed to be dynamic, if a user adds it to a blank page in Microsoft Office FrontPage 2003, for example, it becomes a static Web Part. Static Web Parts cannot save changes in either shared or personal view. - The user is anonymous. For more information, see the Permissions property in the Microsoft SharePoint Products and Technologies 2003 Software Development Kit (SDK). Validate Properties Whenever You Attempt to Save Changes to the Database You can edit property values in a number of places outside of your Web Part's UI, for example: - In the Web Part description (.dwp) file. - In the tool pane. - In an HTML editor compatible with Windows SharePoint Services, such as FrontPage 2003 - Using the Web Part Pages Services Component (WPSC) to set properties from the client browser. Because of the variability of places in which you can edit property values, whenever you attempt to save changes to the database you should not make assumptions about the state of your properties. For example, you cannot assume that properties are unchanged because you suppressed them in the UI, or that properties are valid because you validated them when they were entered in the user interface. To make sure that you account for all the different places that properties can be set, we recommend that you place your validation code in the property's Set accessor method. Specify Custom Error Messages When Appropriate By default, when an exception occurs, the Web Part infrastructure redirects the user to an error page and renders a generic error message. To specify your own error message to the end user, use the WebPartPageUserException class, as shown in the following example. For more information, see WebPartPageUserException class in the Microsoft SharePoint Products and Technologies 2003 SDK. Validate All User Input Like any Web control or application, you should thoroughly validate all user input before performing operations with that input. This validation can help to protect against not only accidental misuse, but also deliberate attacks such as SQL injection, cross-site scripting, buffer overflow, and so on. For more information about creating secure Web Parts, see the Microsoft Security Developer Center. Register the Client-side Script Shared by Multiple Web Parts to Improve Performance There are two ways to render client-side script for a Web Part page. - Place the script in an external file and register the script for the page. - Send code to the client for each request. If you have multiple Web Parts that share client-side script, you can improve performance and simplify maintenance by placing the script in an external file and registering the script for the page. In this way, the code is cached on the client computer on first use and does not need to be resent to the client for each request. To register client-side script shared by multiple Web Parts - Place the script in a separate file. - Create the appropriate folder on the server to save the file.If the assembly is deployed in the global assembly cache, save the script file in the _wpresources virtual directory If the assembly is located in the bin, save the script file in the wpresourcesvirtual directory - In your Web Part code, register the script using the page's RegisterClientScriptBlock method. For detailed instructions, see Creating a Web Part with Client-side Script in the Microsoft SharePoint Products and Technology 2003 SDK. Specify Whether Web Part Properties Can be Exported When you export a Web Part, you create a Web Part description (.dwp) file automatically. The .dwp file is an XML document that represents the Web Part and its property values. Users can import this file to add the Web Part with all the properties set. By default, each property is included in the .dwp file whenever you export a Web Part. However, because you may have properties that contain sensitive information, for example, a date of birth, the Web Part infrastructure enables you to identify a property as controlled, allowing you or the user to have the choice to exclude the value if the Web Part is exported. Only properties that are exported when the user is in personal view can be controlled; in shared view, all property values are exported because it is not likely that sensitive information would be included on a shared page. There are two properties that work together to provide this functionality: the ControlledExport property of the WebPartStorageAttribute class, and the ExportControlledProperties property of the WebPart class. ControlledExport The ControlledExport property of the WebPartStorageAttribute class, if set to true, specifies the property as a controlled property. This property is defined along with other property attributes as follows: Note If no WebPartStorage attribute is defined, or if the ControlledExport property is not explicitly included, this value is false. ExportControlledProperties The ExportControlledProperties property of the WebPart class is used at run time to determine whether controlled properties are exported when the user is in personal view. The default value is false, which prevents properties from being exported while in personal view. This property maps directly to the Allow Export Sensitive Properties check box in the Advanced category of the tool pane, enabling the user to set this value at run time. By default, this check box is not selected, which prevents controlled properties from being exported. The user has to explicitly select this check box to allow different behavior. (This option applies only to controlled properties.) Figure 1. Advanced category as viewed in the tool pane Note The Advanced category in the tool pane appears only in the view in which the Web Part was added. For example, if the Web Part is added in shared view, the Advanced section appears in the tool pane only when you are modifying properties in the Shared Page; if it is added in personal view, the Advanced section of the tool pane appears only when you are modifying properties in My Page. In either case, the setting determines how properties are exported only when the user is exporting in personal view. Implement the IDesignTimeHtmlProvider Interface in Your Web Part to Ensure Correct Rendering in FrontPage Because Microsoft Office FrontPage is the environment where many end users edit Web Part Pages, you should make sure your Web Parts render correctly there. You can specify how you want your Web Part to render in the FrontPage Design view by implementing the IDesignTimeHtmlProvider interface. If you do not implement this interface, and a user opens a Web Part Page in the FrontPage Design view, your part appears only as the message, "There is no preview available for this part." Following is an example of a simple IDesignTimeHtmlProvider implementation. namespace MyWebParts { [XmlRoot(Namespace = "MyNamespace")] public class DesignTimeHTMLSample : Microsoft.SharePoint.WebPartPages.WebPart, IDesignTimeHtmlProvider { private string designTimeHtml = "This is the design-time HTML."; private string runTimeHtml = "This is the run-time HTML."; public string GetDesignTimeHtml() { return SPEncode.HtmlEncode(designTimeHtml); } protected override void RenderWebPart(HtmlTextWriter output) { output.Write(this.ReplaceTokens(runTimeHtml)); } } } For more information, see the IDesignTimeHtmlProvider interface in the Microsoft SharePoint Products and Technologies 2003 SDK. Make Properties User-Friendly in the Tool Pane Because the tool pane is where users modify Web Part properties, you should be aware of how your properties appear in it. Following are some attributes you should use to ensure that your users can work with your Web Part properties easily in the tool pane. - FriendlyNameAttribute. Controls how the property name is displayed. This name should be user friendly, for example, a property named MyText should be "My Text" (notice the space between the two words). - Description. Specifies the tool tip shown when the user pauses the mouse pointer over the property. Try to write the property description so that a user can figure out how and why they should set the property. Try to minimize users having to navigate away from your UI and seek help in the documentation to set a property. - Category. Describes the general section the property belongs to, for example, Advanced, Appearance, Layout, or Miscellaneous. If possible, avoid the Miscellaneous category, which is used if no category is specified for a property. Because this category title is not descriptive, your user has no indication of what is included in Miscellaneous without expanding it. A custom property is also placed in the Miscellaneous category if you attempt to include it in the Appearance, Layout, or Advanced categories. These categories are reserved for base class properties only. For example, the following attribute statements demonstrate the attributes for a custom property that is a string displayed as a text box in the tool pane. // Create a custom category in the tool pane. [Category("Custom Properties")] // Assign the default value. [DefaultValue(c_MyStringDefault)] // Make property available in both Personalization // and Customization mode. [WebPartStorage(Storage.Personal)] // The caption that appears in the tool pane. [FriendlyNameAttribute("My Custom String")] // The tool tip that appears when pausing the mouse pointer over // the friendly name in the tool pane. [Description("Type a string value.")] // Display the property in the tool pane. [Browsable(true)] [XmlElement(ElementName="MyString")] Additional Customization Tips for Properties in the Tool Pane You can customize the appearance of your properties in the tool pane by doing the following: - Expanding and collapsing specific categories when the pane opens. Use the Expand method of either the WebPartToolPart or CustomPropertyToolpart class to expand selected categories. - Hiding base class properties. Use the Hide method of the WebPartToolPart class to hide selected properties. - Controlling the order of tool parts within a tool pane. Order the tool parts as you want them to appear in the tool pane in the array passed to the GetToolParts method of the WebPart class. For more information, see Creating a Web Part with Custom Properties in the Microsoft SharePoint Products and Technologies 2003 SDK. HTMLEncode All User Input Rendered to the Client Use the HTMLEncode method of the SPEncode class as a security precaution to help prevent malicious script blocks from being able to execute in applications that execute across sites. You should use HTMLEncode for all input that is rendered to the client; this can reduce dangerous HTML tags to more secure escape characters. Following is an example of using the HTMLEncode method to render HTML to a client computer. For more information, see the SPEncode class in the Microsoft SharePoint Products and Technologies 2003 SDK. Check Web Part Zone Properties Whenever You Attempt to Save Changes to Your Web Part Web Part zones have properties that control whether a user can persist changes. If you attempt to save changes to a Web Part without the correct permissions, it could result in a broken page. For this reason, you should account for any combination of permissions for your Web Part. Following are the list of properties in the WebPartZone class that determine whether a Web Part can persist properties: - AllowCustomization property. If false, and the user is viewing the page in shared view, the Web Part cannot persist any changes to the database. - AllowPersonalization property. If false, and the user is viewing the page in personal view, the Web Part cannot persist any changes to the database. - LockLayout property. If true, changes to the AllowRemove, AllowZoneChange, Height, IsIncluded, IsVisible, PartOrder, Width, and ZoneID properties are not persisted to the database regardless of view. Fortunately, the Web Part infrastructure does a lot of the work. You can check the Permissions property, which takes into account the values of the zone's AllowCustomization and AllowPersonalization properties. If, however, your user interface permits changes to the properties controlled by the LockLayout property, you must explicitly check this value, typically in your property's Set accessor method. The following code illustrates how you can get a reference to a Web Part's containing zone to check the LockLayout property. Use Simple Types for Custom Properties You Define Web Part property values can be specified in one of two ways: - As XML elements contained in the Web Part. For example, - As attributes of the Web Part For example, Because of how the Web Part infrastructure handles property values, we recommend that you define your properties as simple so they work properly if specified as attributes of the Web Part. If your code requires a value to be a complex type, you can convert the value to a complex type as required by your program. For a list of simple types, see C# Simple Types, or Visual Basic .NET Primitive Types. Make Properties Independent of Each Other if They both Appear in the Tool Pane There is no guarantee of the order that properties are set in the tool pane. For this reason, Web Part developers should avoid writing Web Part properties that are dependent on each other and that both appear in the tool pane. For example, if logic in property A's set function sets B=2 if A=1, and if the end user inputs A=1 and B=4 in the tool pane and clicks Apply, then property A might get set first, setting B to the value of 2. However, then B is set again to 4 based on the user input, resulting in values of A=1 and B=4. Make Web Parts Easily Searchable in the Galleries Web Part galleries can contain numerous custom Web Parts, so the Web Part infrastructure provides Search capability to help users quickly find the Web Parts they want. Figure 2. The search box for Web Parts Search uses the Title and Description properties of your Web Part to build the result set, so you should provide comprehensive information in these fields to increase the chance of your Web Part being returned from Search. In addition, each Web Part in the Web Part List has an icon that appears on the left. Figure 3. A Web Part icon By default, the Web Part infrastructure uses generic icons for each Web Part; however, you can customize this icon using the PartImageLarge property. Provide a Preview of Your Web Part for the Web Part Gallery Be sure to create previews for your Web Parts so that administrators are able to review the parts included in the Web Part gallery. In your RenderWebPart method, you can determine whether you are in preview mode using the following code. If you are in preview mode, you should render the HTML for the content you want to appear in the preview—typically an image. The chrome and title bar are provided by the infrastructure, with the Web Part title appearing in the title bar. To view a Web Part preview, follow these steps. - On the top-level site, select Site Settings, then Go to Site Administration. - Select Manage Web Part Gallery to see the list of available Web Parts. - Click on the Web Part name and the preview is displayed if one is available. Techniques to Improve Web Part Performance If your Web Part is working with large amounts of data, you can significantly improve its performance by using the following techniques in your code. Asynchronous Data Fetching Use an asynchronous thread for any operation that could take a significant amount of time. In particular, if a database or HTTP request is made, an asynchronous fetch allows other parts to continue processing without being blocked. To register asynchronous operations, call the RegisterWorkItemCallback method of the WebPart class before calling the RenderWebPart method. At the beginning of the render cycle, the base class waits for any pending work items. Note The RegisterWorkItemCallback method operates in a manner similar to System.Threading.ThreadPool.QueueUserWorkItem, but is implemented to work with the event model within a Web Part Page. For more information, including details particular to connectable Web Parts, see Asynchronous Data Fetching in the Microsoft SharePoint Products and Technologies 2003 SDK. Caching Use a Web Part cache to store property values and to expedite data retrieval. Values are stored in the Web Part cache on a per-part or per-user basis by specifying the storage type in the call to the PartCacheRead and PartCacheWrite methods. You can also determine the type of cache to use—either the content database (objects must be serializable) or the ASP.NET Cache object—by setting the value of the WebPartCache element in the web.config file. Note By default, exceptions related to caching are not propagated to the surface by the Web Part infrastructure. For debugging purposes, you can make the following changes to your web.config file. - In the <SharePoint> tag, locate the <SafeMode MaxControls="50" CallStack="false"/> tag and change it to <SafeMode MaxControls="50" CallStack="true"/>, causing the ASP .NET error message to display with stack trace information. - In the <system.web> tag, locate the <customErrors mode="On"> tag and change it to <customErrors mode="Off" /> to see the ASP .NET exception when an error occurs instead of being redirected to the error page. Note For security reasons, these changes are recommended for a development environment only; this information is not suitable for a production environment as it can contain sensitive data. For more information about caching, see Web Parts and Caching in the Microsoft SharePoint Products and Technologies 2003 SDK. Localize Your Custom Property's FriendlyName, Title, and Description Attributes By planning for localization at the development phase, you can provide a more usable user interface and save the costs associated with localizing your Web Part post-development. The Web Part infrastructure provides a simple way to localize certain attributes (FriendlyName, Category, and Description) of your custom properties, making it easier for users to work with them in the tool pane. To localize the FriendlyName, Title, and Description property attributes as they appear in the tool pane - Add an assembly resource file to your project. With your project open in Microsoft Visual Studio .NET, click Add New Item, and then select Assembly Resource File. (This adds Resource1.resx file to your project.) - Enter your localized strings to the .resx file. Select the Resource1.resx file and enter a localized string for FriendlyName, Category, and Description. Figure 4. Assembly Resource File data as viewed in Visual Studio .NET 2003 - Add the ResourceAttribute attribute to each property you localize. The ResourceAttribute attribute takes three string parameters, which map to the name values you entered in the .resx file, in this case PropertyNameID = 1, CategoryID=2, and DescriptionID = 3. [ResourceAttribute ("1", "2", "3")] - Override the LoadResource method of the WebPart class. This method takes one string called id, which is the string passed to ResourceAttribute. The Web Part infrastructure passes this string to the LoadResource method. Following is an example of the LoadResource function. - Create a .resource file by using the ResGen tool provided by .NET Framework tools. In a command prompt window enter: cd c:\Program Files\<Your Visual Studio .Net folder>\<SDK>\Bin Then type the following: ResGen <path of your Resource1.resx file> For more information, including a code sample, see the ResourcesAttribute class in the Microsoft SharePoint Products and Technologies 2003 SDK. Ensure that When Anonymous Access is On, the User Can View the Web Part Page without Logging In You do not want to prompt users for a login if the site has anonymous access enabled. You can determine whether anonymous access is enabled by querying the AllowAnonymousAccess property of the SPWeb class. If this value is true, anonymous access is enabled and you should not perform any action that requires credentials. Conclusion This article presents best practices that can assist you when developing Web Parts. By using some of these techniques, you can reduce the chance for errors and improve the performance and usability of your Web Parts.
http://msdn.microsoft.com/en-us/library/dd583135(v=office.11).aspx
CC-MAIN-2014-35
refinedweb
3,711
51.68
What. When you're building APIs on the Web, there are several ways you can build APIs on the Web. These include HTTP/RPC, and what this means is using HTTP in Remote Procedure Call to call into things, like Methods, across the Web. The verbs themselves are included in the APIs, like Get Customers, Insert Invoice, Delete Customer, and that each of these endpoints end up being a separate URI. Why use the Web API? Currently most mobile devices, browsers and tablets are the medium for accessing most of the internet and in this also people are using mobile apps the most and to provide data to apps we are now going to use the Microsoft new technology called Web API. When to use it If you want to expose the data/information of your application to your clients and other people then that other people can use your data and interact with the data/information you expose to them. For example, a mobile application requires a service. HTML 5 requires a service. Desktop PC and tablets require services. Currently most device apps require Web API services. The ASP.Net Framework leverages both web standards such as HTTP, JSON and XML and it provides a simple way to build and expose REST-based data services.. Some core concepts of ASP.Net MVC are similar to the ASP.Net Web API such as routing and controllers. Web API with MVC Project: Visual Studio 2013 for Web includes Web API template which creates a new Web API project with ASP.NET MVC application and includes all the necessary references to get started. For this, open Visual Studio for Web and click on File menu and click on New Project. This will open New Project popup as below.. Adding a Model A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message. Let's start by creating a simple model that represents a product. If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select. Now open the "ProductsController" and write the code below using ProductsApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Http; namespace ProductsApp.Controllers { public class ProductsController : ApiController { // Here we are adding products by creating Products Class Array Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; //This method will return All the products public IEnumerable<Product> GetAllProducts() { return products; } //This method will return product by Id public IHttpActionResult GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } } } To keep the example simple, products are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source. The controller defines two methods that return products: - The GetAllProductsmethod returns the entire list of products as an IEnumerable<Product> type. - The GetProductmethod looks up a single product by its ID. Now, You have a working web API. Each method on the controller corresponds to one or more URIs: For the GetProduct method, the id in the URI is a placeholder. For example, to get the product with ID of 5, the URI is api/products/5.". Place this code in index.html < project in browser give's results
https://qawithexperts.com/article/web-api/web-api-tutorial-for-beginners/25
CC-MAIN-2021-21
refinedweb
673
65.52
Well once I went through and changed all the int's to long's, the program gave all the correct outputs. The issue was that I neglected to replace the int's used for the counters in the for loops. ... Type: Posts; User: jwroblewski44 Well once I went through and changed all the int's to long's, the program gave all the correct outputs. The issue was that I neglected to replace the int's used for the counters in the for loops. ... @nonpuz I spoke with my department chair(he was a judge during the comp) and he gave me the test cases for the problem. When I have some free time ( thanksgiving break? ), I'm going to check test... Yes. I agree that writing my own sort was not the best approach. Simply, I don't have much experience using the standard system sorts, but I did have access to a book with a sort method I was... @grumpy If you could be more specific as to how I'm failing to do what the program asked. From the last paragraph of the description: "Your team is to write a program to assist the director... Hello, all! First off, this is program from the ACM programming contest, of which today I and two teammates competed. We managed to solve two of nine correctly, but sadly the two programs I was... Thank you. I am working on an intro to OS book and have some questions about this code: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> So when I have a string in quotes, there is an implied null byte at the end? I'm not understanding why the string provided for initialization is too long? int main() { char array[1] = "A"; return 0; Thank you laserlight. That makes sense. Otherwise the contents of the array would be alterable, right? I am writing a class Player which has several char arrays as private fields. I am trying to write a method which returns an array as a pointer, but doesn't alter the array in any way, thus the const.... Well I am not sure what UART is, but this is wrong: *(unsigned int*) AHB_LED_BASE = 0x55; //wrong ... *(unsigned int*) AHB_LED_BASE = 0xAA; //wrong The define preprocessor command... Thanks. More reading on streams is definitely required. So if I'm understanding correctly, the return value of getline is a boolean value, which is the opposite value of std::basic_ios::fail. And std::basic_ios::fail returns true if eofbit is set, and... Sorry to rehash old topics, but I couldn't find a relevant post to my question. I have smashed together some code that does what I want, but I'm not quite sure why. The problem I'm trying to solve is... Address space layout randomization - Wikipedia, the free encyclopedia I would say that grumpy's original idea would be best. It's not meant to be robust, just an example. But thanks for pointing that out. Here is a sample program using a linked list. Note that the most basic of operations have been given their own functions. linkedlistop.h // linkedlistop.h struct node { Memory management is key to using C, so it shouldn't be shrugged off. Do research on the tool Valgrind, and use it. Don't forget; all dynamic memory allocated MUST be free'd by the programmer to... Could you tell us what algorithm you're using? Always check the returned pointer from malloc to check for failed allocation. Also I would modify it so you can search for a particular value, rather than just showing the last element. Your... edit: didn't read entire thread Were you planning on using C or C++? This seems best suited for C++, but I found a link on stack overflow that might be of use if you demand good ol' C: oop - How can I simulate OO-style... If you ask me, your solutions simplicity is a good thing. With small programs like this, moving a one liner into a function is simply a matter of preference. But when your code portions start to... im sorry, you are correct.
https://cboard.cprogramming.com/search.php?s=1dc9d54440565ab5f1943f99077e568c&searchid=2221242
CC-MAIN-2019-51
refinedweb
702
74.9
PROLOGThis manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. NAMEsys/shm.h — XSI shared memory facility SYNOPSIS #include <sys/shm.h> DESCRIPTIONThe <sys/shm.h> header shall define the following symbolic constants: - SHM_RDONLY - Attach read-only (else read-write). - SHM_RND - Round attach address to SHMLBA. - SHMLBA - Segment low boundary address multiple. - shmatt_t - Unsigned integer used for the number of current attaches that must be able to store values at least as large as a type unsigned short.(). void *shmat(int, const void *, int); int shmctl(int, int, struct shmid_ds *); int shmdt(const void *); int shmget(key_t, size_t, int);
http://jlk.fjfi.cvut.cz/arch/manpages/man/sys_shm.h.0p.en
CC-MAIN-2018-30
refinedweb
128
50.02
import urllib2 urllib2.urlopen('') GRANT ALL PRIVILEGES ON `xbmc_%`.* TO 'xbmc'@'%'; aptalca Wrote:First of all, the two best options (if you're on a budget and want to do it all yourself) for home automation are: z-wave and x10. (For others, there are systems you can have installed by professionals and they include control 4, crestron, knx, etc. but they are beyond the scope of this guide) aptalca Wrote:For X10, you can start by looking at x10.com Their prices for individual devices are high, but they a lot of really good combo deals. Watch out though, their website and their marketing strategies seem a little shady, but all my orders came through with no problems. If you would like to purchase devices separately, there are quite a few ebay dealers that sell a ton of x10 devices with free shipping. Their prices are comparable to the combo deals from x10.com. Just look for the ones that are power sellers with really good feedback. For instance, the usb device + main software (no plugins) costs $50 on their website. However you can buy the usb device + main software + 4 plugins for $50 on ebay. I ended up getting the same ebay deal + ActivePhone plugin + floodlights w/motion sensor for $50 from x10.com when they had a "one day only" sale the other day. Liking their Facebook page gave me an extra 15% off as well. (I used a dummy Facebook account that doesn't have any of my personal info) That deal made me bite the bullet and get started. So just check their website frequently as they have different deals ALL the time, otherwise ebay dealers sell them the cheapest individually. When I need a module I just search for "x10" and the model number on ebay, I get a ton of listings. Good luck TonyNoone Wrote:That's funny. You managed to squeeze "best" and "X10" into the same sentence! That's a stretch. You could have used "cheapest" and "X10" but, BEST? How about UNRELIABLE and X10? While I commend you for beginning a system and even more so for documenting it so others could benefit, I'm afraid that of every three who try to follow, two will fail. Simply because X10 is, well there's no nice way to put it, garbage. giftie Wrote:Other great systems to look up are the following: UPB - Most notably Simply Automated and Pulseworx Lutron RadioRA2 - Probably the upper end of DIY system Personally I like the UPB system over X10 or Insteon as it is a fair bit reliable. It would be a good idea to stick with a system that can be enlarged since once you have the Theatre done, you know you'll want to do the rest...
http://forum.kodi.tv/showthread.php?tid=101300
CC-MAIN-2016-07
refinedweb
466
71.55