text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
Using ES6 with Asset Pipeline on Ruby on Rails
Read in 7 minutes
This article has been updated. Read Using ES2015 with Asset Pipeline on Ruby on Rails1, which is now called ES6. The first drafts were published in 2011, but the final specification was released in June of this year.
ES6 has so many new features:
Browsers are implementing new features in a fast pace, but it would still take some time until we could actually use ES6. Maybe years. Fortunately, we have Babel.js. We can use all these new features today without worrying with browser compatibility.
Babel.js2 is just a pre-processor. You write code that uses these new features, which will be exported as code that browsers can understand, even those that don’t fully understand ES6.
Using Babel.js
To install Babel make sure you have Node.js installed. Then you can install Babel using NPM.
$ npm install babel -g
You can now use
babel command to compile your JavaScript files. You can enable the watch mode, which will automatically compile modified files. The following example with watch
src and export files to
dist.
$ babel --watch --out-dir=dist src
One of the features I like the most is the new class definition, which abstracts constructor functions. In the following example I create a
User class that receives two arguments in the initialization.
class User { constructor(name, email) { this.name = name; this.email = email; } }
After processing this file with Babel, this is what we have:
User = (function () { function User() { _classCallCheck(this, User); } _createClass(User, [{ key: 'construct', value: function construct(name, email) { this.name = name; this.email = email; } }]); return User; })(); var user = new User('John', 'john@example.com'); console.log('name:', user.name); console.log('email:', user.email);
Note that Babel generates all the required code for supporting the class definition. Alternatively, you can use
--external-helpers to generate code that uses helpers (helpers can be generated with the
babel-external-helpers command).
$ babel --external-helpers --watch --out-dir=dist src
Now all supporting code will use the
babelHelpers object.
'use strict'; var User = (function () { function User() { babelHelpers.classCallCheck(this, User); } babelHelpers.createClass(User, [{ key: 'construct', value: function construct(name, email) { this.name = name; this.email = email; } }]); return User; })(); var user = new User('John', 'john@example.com'); console.log('name:', user.name); console.log('email:', user.email);
Using Babel.js with Asset Pipeline
Instead of using Babel’s CLI, some people prefer builders like Grunt or Gulp to automate the compilation process. But if you’re using Ruby on Rails you’re more likely to use Asset Pipeline for front-end assets compilation.
Unfortunately there’s no built-in support on the stable release of Sprockets. But if you like to live on the edge3, you can use the master branch.
Update your
Gemfile to include these dependencies..
//= require_tree . //= require_self
Now if you access the page on your browser, you’ll see an
alert box like this:
If you want the new module system, you still have some things to configure.
Using ES6 modules
ES6' source '' do gem 'rails-assets-almond' end
You also have to configure Babel; just create a file at
config/initializers/babel.rb with the following code:
Rails.application.config.assets.configure do |env| babel = Sprockets::BabelProcessor.new( 'modules' => 'amd', 'moduleIds' => true ) env.register_transformer 'application/ecmascript-6', 'application/javascript', babel end
Finally, update
app/assets/javascripts/application.js so it loads almond.
//= require almond //= require jquery //= require turbolinks //= require_tree . //= require_self almond //= require jquery //= require turbolinks //= require_tree . //= require_self require(['application/boot']);
You have to create
app/assets/javascripts/application/boot.es6. I’ll listen to some events, like DOM’s
ready and Turbolinks’
page load.
import $ from 'jquery'; function runner() { // All scripts must live in app/assets/javascripts/application/pages/**/*.es6. var path = $('body').data('route'); // Load script for this page. // We should use System.import, but it's not worth the trouble, so // let's use almond's require instead. try { require([path], onload, null, true); } catch (error) { handleError(error); } } function onload(Page) { //('page:load', runner);
This script needs a
data-route property property on your
<body> element. You can add something like the following to your layout file (e.g.
app/views/layouts/application.html.erb):
<body data-66 today is a viable option. With Babel you can use all these new features without worrying with browser compatibility. The integration with Asset Pipeline make things easier, even for those that don’t fully grasp the Node.js ecosystem.
There’s a working repository available at Github.
ES6 is also known as ES.Next or ES2015 (this is the official name, defined after I first published this article). ↩
This project used to be called 6to5.js. Read more. ↩
The Go community does this all the time, so maybe is not a big deal. ¯\(ツ)/¯ ↩ | http://nandovieira.com/using-es6-with-asset-pipeline-on-ruby-on-rails | CC-MAIN-2017-04 | en | refinedweb |
Unmanaged Code, Screenshots and IronPython
IronPython & Windows Forms, Part X
Note
This is part of a series of tutorials on using IronPython with Windows Forms.
Follow my exploration of living a spiritual life and finding the kingdom at Unpolished Musings.
Screenshots from IronPython
This is an example from work that I am allowed to show you.
It comes from our functional test suite, where the only way we could test a feature was by taking a screenshot of part of the main form.
This is pretty easy, but can only be done from unmanaged code, it is GDI functionality and there is no .NET API that we could find.
This means that we have to drop into C#. Using unmanaged code from C# is very easy, but you need to add a class attribute specifying the dll you are using. C# attributes cannot be applied from IronPython.
So the following is a great example of :
- Taking a screenshot with IronPython
- Creating a class in C# and using it from IronPython
- Using unmanaged code from IronPython and C#
What a bargain for a single example.
To ensure that it this is not a frivolous and trivial example, we will use the screenshot code to do something useful, like create some ASCII art...
Note
The code in this example is adapted from this page.
If you are running Windows and don't want to install Visual Studio, you can download a copy of UnmanagedCode.dll.
Alternatively, if you want more of a walk-through in creating a new class library with Visual Studio, visit C# and the Clipboard.
The functions we need to use are in user32.dll and GDI32.dll.
The attribute we need to mark our methods with is DllImport.
To make the managed (C#) wrapper round the unmanaged code, create a new class library called 'UnmanagedCode' in Visual Studio [1] with the code shown below.
It creates two classes in the UnmanagedCode namespace : GDI32 and User32.
You can see what the class members look like, they are references to the functions in the Dlls, marked with the DllImport attribute, and declared as public static extern. We need to declare the types of the arguments passed to the functions and their return values. We use IntPtr instead of int as type declarations for the handle values. This allows the code to work on 64 bit platforms.); } }
When you build this class library you should create a file called UnmanagedCode.dll. This contains our newly created classes. Place this dll in the same directory as the Python script you use it from.
Originally we had another class with a static method that used all this to take the screenshot. Translating it into IronPython turned out to be as easy as removing the declarations and the semicolons.
So here is the IronPython code to do the business :
clr.AddReference('UnmanagedCode')
clr.AddReference('System.Drawing')
from System.Drawing import Bitmap, Image
I'm not going to step through this in detail, but you can follow the basic flow. We add a reference to our class library and import the two classes from it.
Then we get a handle and context for the main screen and create a new handle for the destination image we are creating.
We then do some GDI magic involving the BitBlt function and a copy raster operation. We then create a new Bitmap image object from the filled in bitmap.
Our new ScreenCapture function takes an x and y co-ordinate for the top left corner, plus a width and a height for the rectangle we wish to take a screenshot of.
Lets put this into action by taking a screenshot of this smiley -
- and turning it into ASCII art.
Now down to business. We'll assume a pixel is light (represented by a space) if its R+G+B value is greater than 384 (half of 256 * 3). Otherwise the pixel is dark and we will represent it with an 'X'.
So we need to iterate over all the pixels in each row. luckily the Bitmap class has a useful method, GetPixel. This returns a Color which we can interrogate for its value.
image = ScreenCapture(84, 179, 16, 16)
for y in range(image.Height):
row = []
for x in range(image.Width):
color = image.GetPixel(x, y)
value = color.R + color.G + color.B
if value > 384:
row.append(' ')
else:
row.append('X')
print ''.join(row)
And the result ?
XXXXX XX XX X X X XX XX X X X X X X X X X X X X X X X X X X XXXXXXXXX X X X X X X XXXXX X X X XX XX XXXXX
Of course, you might want to do something else with the image, like saving it.
To do this you might use the Save method of the image, and specify an ImageFormat. Like this :
from System.Drawing.Imaging import ImageFormat
def SaveBitmap(image, filename):
image.Save(filename, ImageFormat.Bmp)
For buying techie books, science fiction, computer hardware or the latest gadgets: visit The Voidspace Amazon Store.
Last edited Fri Nov 27 18:32:35 2009.
Counter... | http://www.voidspace.org.uk/ironpython/winforms/part10.shtml | CC-MAIN-2017-04 | en | refinedweb |
All, the pyArkansas flyer has been updated with a couple of talks and a few new sponsors. I didnt have much room left on it, its pretty busy, but I'm really really crunched for time tonight. The pdf is here: and the jpeg is on flickr: chad! -------------------------------------------------------- Chad Cooper On Thu, Aug 28, 2008 at 8:43 AM, Greg Lindstrom <gslindstrom at gmail.com>wrote: > Jeff Rush will be coming up, too, and teaching the following in the > "intermediate python" class. He has also offered to host a talk in the > afternoon, so I may request a 4th classroom (I'd like to see the "eggs" and > "eclipse" talks be offered). > > --greg > > 1) A Tour of Pythonic Concepts > > names, values and namespaces > control structures > being callable > being iterable > subscripting and slicing > introspection > about strings, formatting and parsing > > 2) A Walkthru of Interesting Python Techniques > > RDBMS / dbapi > OODBMS / ZODB / Durus > STAN templating > reStructuredText usage re piece extraction > > > On Thu, Aug 28, 2008 at 8:24 AM, Chad Cooper <supercooper at gmail.com>wrote: > >> Bob, I've been meaning to update it with our new sponsors and talk topics, >> I can do it first thing after work today and get it out then. I'll let the >> list know as soon as its done. >> >> chad >> >> >> >> >> >> On Thu, Aug 28, 2008 at 8:21 AM, Bob Fahr <bob.fahr at gmail.com> wrote: >> >>> Do we have an up-to-date flyer for the conference? I've gotten a >>> request for info and I'd like to send the flyer. >>> >>> _______________________________________________ >>> PyAR2 mailing list >>> PyAR2 at python.org >>> >>> >>> >> >> _______________________________________________ >> PyAR2 mailing list >> PyAR2 at python.org >> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/pyar2/2008-August/000283.html | CC-MAIN-2017-04 | en | refinedweb |
(Extra copy to the list, since Google Groups breaks the recipient list :P) inspect.Signature.bind() supports this in Python 3.3+ For earlier versions, Aaron Iles backported the functionality on PyPI as "funcsigs". You can also just define an appropriate function, call it as f(*args, **kwds) and return the resulting locals() namespace. Cheers, Nick. On 19 Sep 2013 04:39, "Neil Girdhar" <mistersheik at gmail.com> wrote: > As far as I know, the way that arguments are mapped to a parameter > specification is not exposed to the programmer. I suggest adding a > PassedArgSpec class having two members: args and kwargs. Then, > inspect.ArgSpec can take an argument specification and decode the > PassedArgSpect (putting the right things in the right places) and return a > dictionary with everything in its right place. > > I can only think of one use for now, which is replacing "arguments" in the > returned tuple of __reduce__ and maybe allowing it to be returned by > "__getnewargs__". It might also be nice to store such argument > specifications instead of the pair args, kwargs when storing them in lists. > > Best, > > Neil > > _______________________________________________ > Python-ideas mailing list > Python-ideas at python.org > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/python-ideas/2013-September/023238.html | CC-MAIN-2017-04 | en | refinedweb |
Opened 9 years ago
Closed 4 years ago
#3064 closed defect (fixed)
[Patch] Plugin does not show up in trac admin
Description
This plugin does not appear to be working, nor does it show up in the Trac plugins list on the trac-admin page after installation.
I am running a Windows 2003 Server with Trac 0.11b2 and Python 2.5. All necessary application dependencies (swish-e, catdoc, catppt, pdftotext) are installed.
The .egg file was compiled using the "python setup.py bdist_egg" command, and then copied to the environment's plugin directory. Necessary changes were made to the trac.ini file [components] and [attachment] secionts, but the plugin still does not show up.
I have also attempted to install this as a global plugin, but that has not worked either.
Attachments (0)
Change History (6)
comment:1 Changed 8 years ago by kennethxu
- Type changed from defect to enhancement
comment:2 Changed 8 years ago by wouter
- Type changed from enhancement to defect
I have exactly the same problem here. Running Windows 2003 Server too, using Trac 0.11b1 and Python 2.5... Does not show up in the admin either, uploading new attachments does not create new index files, I put the config in the [attachment] section instead of [attachments] as dictated by the wiki, after checking in the plugin's code which section it would look at. Still does not work.
Probably because the plugin simply doesn't get picked up by Trac?
comment:3 Changed 8 years ago by wouter
Additionally, here is what I see in the log file:
2008-10-02 12:13:34,717 Trac[loader] DEBUG: Loading TracSearchAttachmentsPlugin from c:\repositories\sandbox-trac\plugins\tracsearchattachmentsplugin-0.1-py2.5.egg 2008-10-02 12:13:34,717 Trac[loader] ERROR: Skipping "TracSearchAttachmentsPlugin = searchattachments": (can't import "bad local file header in c:\repositories\sandbox-trac\plugins\tracsearchattachmentsplugin-0.1-py2.5.egg")
I can view the file with a ZIP viewer though.
comment:4 Changed 8 years ago by anonymous
I believe I've found the problem in searchattachments/searchattachments.py line 13:
from trac.Search import ISearchSource
should be:
from trac.search import ISearchSource
When I made this change, the plugin showed up in the admin page of a trac 0.11 installation, and seemed capable of finding terms in pdf files.
I hope someone can confirm and check this change in to the code repository.
comment:5 Changed 7 years ago by rjollos
- Summary changed from Plugin does not show up in trac admin to [Patch] Plugin does not show up in trac admin
comment:6 Changed 4 years ago by rjollos
- Resolution set to fixed
- Status changed from new to closed
I think the problem is simply because this plugin doesn't support 0.11. Any plan to support 0.11. I loved this plugin and will be missing it... | https://trac-hacks.org/ticket/3064 | CC-MAIN-2017-04 | en | refinedweb |
We have looked at generic method but in C#, generic classes are also used widely.
Generic classes allow operations that are not specific to a particular data type. Usually, those data types are of type integer or string.
If you look at programming literature related to WPF, you will come across this symbol <> quite frequently.
The symbol <> actually denotes either generic method, class or generic interface.
Generic classes are used commonly in WPF such as this ObservableCollection class where it is used to track items in a list or combo box.
using System; class Mix<T,U> { T val1; U val2; public Mix(T t, U u) { // The field has the same type as the parameter. this.val1 = t; this.val2 = u; } public void Write() { Console.WriteLine(this.val1); Console.WriteLine(this.val2); } public void Write1() { Console.WriteLine("I have " + this.val1 + " " + this.val2); } } class Program { static void Main() { Mix<int, int> m1 = new Mix<int, int>(5, 6); m1.Write(); Console.WriteLine(); Mix<int, string> m2 = new Mix<int, string>(5,"cats"); m2.Write1(); Console.ReadKey(); } }
In this example, the class Mix will be able to take in either integers or strings. In the class declaration, we use <T,U> and in fact they can be any letter or combination of letters. | http://codecrawl.com/2014/10/07/c-generic-classes/ | CC-MAIN-2017-04 | en | refinedweb |
spiff Wrote:that being said, you can probably have your property, i'll have to check that we have a dedicated localized string for it.
Hitcher Wrote:Thanks, all good here
def getFeelsLike( T=10, V=25 ): """ The formula to calculate the equivalent temperature related to the wind chill is: T(REF) = 13.12 + 0.6215 * T - 11.37 * V**0.16 + 0.3965 * T * V**0.16 Or: T(REF): is the equivalent temperature in degrees Celsius V: is the wind speed in km/h measured at 10m height T: is the temperature of the air in degrees Celsius source: """ FeelsLike = T #Wind speeds of 4 mph or less, the wind chill temperature is the same as the actual air temperature. if round( ( V + .0 ) / 1.609344 ) > 4: FeelsLike = ( 13.12 + ( 0.6215 * T ) - ( 11.37 * V**0.16 ) + ( 0.3965 * T * V**0.16 ) ) # return str( round( FeelsLike ) )# test FeelsLike and check table in site = -10for windspeed in range( 101 ): FeelsLike = getFeelsLike( tCelsius, windspeed ) print FeelsLikeprint "-"*100
import mathdef getDewPoint( Tc=0, RH=93, minRH=( 0, 0.075 )[ 0 ] ): """ Dewpoint from relative humidity and temperature If you know the relative humidity and the air temperature, and want to calculate the dewpoint, the formulas are as follows. """ #First, if your air temperature is in degrees Fahrenheit, then you must convert it to degrees Celsius by using the Fahrenheit to Celsius formula. # Tc = 5.0 / 9.0 * ( Tf - 32.0 ) #The next step is to obtain the saturation vapor pressure(Es) using this formula as before when air temperature is known. Es = 6.11 * 10.0**( 7.5 * Tc / ( 237.7 + Tc ) ) #The next step is to use the saturation vapor pressure and the relative humidity to compute the actual vapor pressure(E) of the air. This can be done with the following formula. #RH=relative humidity of air expressed as a percent. or except minimum(.075) humidity to abort error with math.log. RH = RH or minRH #0.075 E = ( RH * Es ) / 100 #Note: math.log( ) means to take the natural log of the variable in the parentheses #Now you are ready to use the following formula to obtain the dewpoint temperature. try: DewPoint = ( -430.22 + 237.7 * math.log( E ) ) / ( -math.log( E ) + 19.08 ) except ValueError: #math domain error, because RH = 0% #return "N/A" DewPoint = 0 #minRH #Note: Due to the rounding of decimal places, your answer may be slightly different from the above answer, but it should be within two degrees. return str( int( DewPoint ) )# Check Dew Point Calculator with = 10for humidity in range( 101 ): DewPoint = getDewPoint( tCelsius, humidity ) print DewPointprint "-"*100
odoll Wrote:hm, not here - maybe blind, but I just dl'ed the latest win32 nightly build XBMCSetup-20111116-57ba0cb-master.exe
Weather is gone from the main menu, however going to System -> Weather OR System Add-Ons there's non "Weather add-on" to pick?!
Searching Add-Ons for Weather just returns "MEdia sources - DMI TV Vejrudsigt".
Hitcher Wrote:You may need to Force Refresh XBMCs repository for it to show up.
bcamp929 Wrote:No Fahrenheit? | http://forum.xbmc.org/showthread.php?tid=114637&pid=937146 | CC-MAIN-2014-35 | en | refinedweb |
Abhijeet Pathak wrote:Dude it's a rule "You cannot access protected variables from subclass by creating an object of base class in the subclass."
can not override static method/variables . but can be accessed by sub class
Mo Jay wrote:you can inherit a static variable from the parent class and you can override it by changing its value. Give it a try to see.
A sub class can, of course, still change the value contained in the static.
Nitish Bangera wrote:Abhijeet you are right that protected variables cannot be accesed from a different class.
my question is when the variable in class A was declares as protected static. it was accessed using the class A's reference variable a.x. It worked properly. I am asking why does it work
When the variable is just protected then yes abhijeet's answer is right
but when it is declared as protected static then it can be accessed.
Nitish wrote:When the variable is just protected then yes abhijeet's answer is right
Jason wrote: No it is not. See above.
Nitish Bangera wrote:Jason its quiet clear now.... Thanks and don't be angry ok... This seems to be a simple topic of statics but it had stuck on my mind that why it does work this way and not that way. Well now its clear Thanks for the reply.
Abhijeet Pathak wrote:Explain yourself.
Himanshu Kansal wrote:[code]This wont compile if "x" is not static in A. Hence static has a role to play.
And I clearly assume A and B are in 2 different packages.
Jason Irwin wrote:
Abhijeet Pathak wrote:Explain yourself.
Can you follow why this works?class Super
{
protected int i = 0;
}
public class Sub extends Super
{
public void doIt()
{
Super mySuper = new Super();
System.out.println(mySuper.i); //Access of protected member on super class instance
}
public static void main(String... args)
{
Sub mySub = new Sub();
mySub.doIt();
}
}
Nitish Bangera wrote:Static members are one for the class.. but are they inherited when an other extends a class with static members???please help me on this issue... | http://www.coderanch.com/t/455647/java-programmer-SCJP/certification/statics | CC-MAIN-2014-35 | en | refinedweb |
Although the bulk of a Web application may lay in presentation, its value and competitive advantage may lay in a handful of proprietary services or algorithms. If such processing is complex or protracted, it's best performed asynchronously, lest the Web server become unresponsive to incoming requests. Indeed, an especially compute-intensive or specialized function is best performed on one or more separate, dedicated servers.
The Gearman library for PHP distributes work among a collection of
machines. Gearman queues jobs and doles out assignments, distributing
onerous tasks to machines set aside for the task. The library is available
for Perl, Ruby,
C, Python, and PHP developers
and runs on any UNIX®-like platform, including Mac OS X,
Linux®, and Sun Solaris.
Adding Gearman to a PHP application is easy. Assuming that you host your
PHP applications on a typical LAMP configuration, Gearman requires an
additional daemon and a PHP extension. As of November 2009, the latest
version of the Gearman daemon is 0.10, and two PHP extensions are
available — one that wraps the Gearman
C
library with PHP and one that's written in pure PHP. This tip uses the
former. Its latest version is 0.6.0, and its source code is available from
PECL or Github (see Resources).
Note: For purposes of this article, a producer is a machine that generates work requests, a consumer is a machine that performs work, and the agent is the intermediary that connects a producer with a suitable consumer.
Installing Gearman
Adding Gearman to a machine requires two steps: building and starting the daemon and building the PHP extension to match your version of PHP. The daemon package includes all the libraries required to build the extension.
To begin, download the latest source code for
gearmand, the Gearman daemon, unpack the
tarball, and build and install the code. (The installation step requires
the privileges of the superuser, root.)
$ wget\ 0.10/+download/gearmand-0.10.tar.gz $ tar xvzf gearmand-0.10.tar.gz $ cd gearmand-0.10 $ ./configure $ make $ sudo make install
When
gearmand is installed, build the PHP
extension. You can fetch the tarball from PECL or clone the repository
from Github.
$ wget $ cd pecl-gearman # # or # $ git clone git://github.com/php/pecl-gearman.git $ cd pecl-gearman
Now that you have the code, building the extension is typical:
$ phpize $ ./configure $ make $ sudo make install
The Gearman daemon is commonly installed in /usr/sbin. You can launch the daemon directly from the command line or add the daemon to your startup configuration to launch each time the machine reboots.
Next, you must enable the Gearman extension. Open your php.ini file (you
can identify it quickly with the command
php --ini), and add the line
extension = gearman.so:
$ php --ini Loaded Configuration File: /etc/php/php.ini $ vi /etc/php/php.ini ... extension = gearman.so
Save the file. To verify that the extension is enabled, run
php --info and look for Gearman:
$ php --info | grep "gearman support" gearman gearman support => enabled libgearman version => 0.10
You can also verify a proper build and installation with a snippet of PHP code. Save this little application to verify_gearman.php:
<?php print gearman_version() . "\n"; ?>
Next, run the program from the command line:
$ php verify_gearman.php 0.10
If the version number matches that of the Gearman library you built and installed previously, your system is ready.
Running Gearman
As mentioned earlier, a Gearman configuration has three kinds of actors:
- One or more producers generate work requests. Each work request names the function it wants, such as
analyze.
- One or more consumers fulfill demand. Each consumer names the function or functions it provides and registers those capabilities with the agent. A consumer is also called a worker.
- The agent collectively catalogs all services provided by consumers that contact it. It marries producers with capable consumers.
You can experiment with Gearman quickly right from the command line:
- Launch the agent, the Gearman daemon:
$ sudo /usr/sbin/gearmand --daemon
- Run a worker with the command-line utility
gearman. The worker needs a name and can run any command-line utility. For example, you can create a worker to list the contents of a directory. The
-fargument names the function the worker is providing:
$ gearman -w -f ls -- ls -lh
- The last piece of the puzzle is a producer, or a job that generates lookup requests. You can generate a request with
gearman, too. Again, use the
-foption to spell out which service you want help from:
$ gearman -f ls < /dev/null drwxr-xr-x@ 43 supergiantrobot staff 1.4K Nov 15 15:07 gearman-0.6.0 -rw-r--r--@ 1 supergiantrobot staff 29K Oct 1 04:44 gearman-0.6.0.tgz -rw-r--r--@ 1 supergiantrobot staff 5.8K Nov 15 15:32 gearman.html drwxr-xr-x@ 32 supergiantrobot staff 1.1K Nov 15 14:04 gearmand-0.10 -rw-r--r--@ 1 supergiantrobot staff 5.3K Jan 1 1970 package.xml drwxr-xr-x 47 supergiantrobot staff 1.6K Nov 15 14:45 pecl-gearman
Using Gearman from PHP
Using Gearman from PHP is similar to the previous example, except that you create the producer and consumer actors in PHP. The work of each consumer is encapsulated in one or more PHP functions.
Listing 1 shows a Gearman worker written in PHP. Save the code in a file named worker.php.
Listing 1. Worker.php
<?php $worker= new GearmanWorker(); $worker->addServer(); $worker->addFunction("title", "title_function"); while ($worker->work()); function title_function($job) { return ucwords(strtolower($job->workload())); } ?>
Listing 2 shows a producer, or client, written in PHP. Save this code in a file named client.php.
Listing 2. Client.php
<?php $client= new GearmanClient(); $client->addServer(); print $client->do("title", "AlL THE World's a sTagE"); print "\n"; ?>
You can now connect client to worker from the command line:
$ php worker.php & $ php client.php All The World's A Stage $ jobs [3]+ Running php worker.php &
The worker application continues to run, ready to serve another client.
Advanced features of Gearman
There are many possible uses for Gearman in a Web application. You can
import large amounts of data, send reams of e-mail, encode video files,
mine data, and build a central log facility — all without affecting
the experience and responsiveness of your site. You can process data in
parallel. Moreover, because the Gearman protocol is language and platform
independent, you can mix programming languages in your solution. You can
write a producer in PHP but the workers in
C,
Ruby, or any language for which a Gearman library is available.
A Gearman network, tying clients to workers, can take virtually any shape you can imagine. Many configurations run multiple agents and scatter workers on numerous machines. Load balancing is implicit: Each operational and available worker, perhaps many per worker host, pulls jobs from the queue. A job can run synchronously or asynchronously and with a priority.
Recent releases of Gearman have expanded the system's features to include persistent job queues and a new protocol to submit work requests via HTTP. For the former, the Gearman work queue remains in memory but is backed by a relational database. Thus, if the Gearman daemon fails, it can recreate the work queue on restart. Another recent refinement added queue persistence via a memcached cluster. The memcached store relies on memory, too, but is distributed over several machines to preclude a single point of failure.
Gearman is a nascent but capable work-distribution system. According to Gearman author Eric Day, Yahoo! uses Gearman across 60 or more servers to process 6 million jobs per day. News aggregator Digg has built a Gearman network of similar size to crunch 400,000 jobs per day. You can find an elaborate example of Gearman in Narada, an open source search engine (see Resources).
Future releases of Gearman will collect and report statistics, provide
advanced monitoring, and cache job results, among other things. To track
the Gearman project, subscribe to its Google group, or visit its IRC
channel,
#gearman, on Freenode.
Resources
Learn
- Learn more about this library from the Gearman site.
- The Narada search engine is an open source project that makes a point of using the latest open source technologies, including Gearman.
-
- Check out Gearman downloads and extensions, including the PHP extension for the
Clibrary.
-
- Visit the Gearman group.
-. | http://www.ibm.com/developerworks/library/os-php-gearman/ | CC-MAIN-2014-35 | en | refinedweb |
11 January 2012 08:22 [Source: ICIS news]
Correction: In the ICIS news story headlined "China’s Shenhua Ningxia switches to copolymer PP output in Jan" dated 11 January 2012, please read in the second paragraph ... 500,000 tonnes/year ... instead of ... 50,000 tonnes/year .... A recast of the second paragraph was also done to ensure clarity. A corrected story follows.
SINGAPORE (ICIS)--Shenhua Ningxia Coal Industry will be producing 5,000 tonnes of copolymer polypropylene (PP) this month at its facility in northwestern ?xml:namespace>
The company’s 500,000 tonne/year plant at Ningxia has been producing PP yarns, but will switch to copolymer PP production for five days in January this year, the source said.
Copolymer PP prices in China had fluctuated between yuan (CNY) 10,250-13,700/tonne ($1,624-2,171/tonne) EXWH (ex-warehouse) last year, according to Chemease, an ICIS service in China.
This kind of co-polymer PP can be used in battery shell, among others.
PP yarn prices in the domestic Chinese market, meanwhile, hit a high of CNY12,900/tonne last year, Chemease | http://www.icis.com/Articles/2012/01/11/9522432/corrected-chinas-shenhua-ningxia-switches-to-copolymer-pp-output-in-jan.html | CC-MAIN-2014-35 | en | refinedweb |
tree tag in struts2 - Struts
tree tag in struts2 I have an arraylist of values retrieved from the database and i want all the values in the arraylist to be viewed in a subtree...
and for each country(INDIA,UK,USA )i want a node which should have the respective2
struts2 sir.... i am doing one struts2 application and i have to make pagination in struts2....how can i do
Struts2 ComponentTagSupport - Struts
working. but my requirement is with the help of my custom tag i have to display the body if the name attribute is present how do i do that?
public class...Struts2 ComponentTagSupport I am working on struts2 custom tags
Struts2 - Struts
Struts2 Hi,
I am using doubleselect tag in struts2.roseindia is giving example of it with hardcoded values,i want to use it with dynamic values.
Please give a example of it.
Thanks
Checkbox Tag <html:checkbox>:
:checkbox
> tag :
Here you will learn to use the Struts Html <html:checkbox...Checkbox Tag <html:checkbox>:
html: checkbox Tag - is used to create a Checkbox Input
how to call servlet from html page at anchor tag ?
how to call servlet from html page at anchor tag ? I have a very different problem as i am using
netbeans ide 6.9 ml to make a website in java... buttons image
and for referrence i use anchor tag {for ex: ()}
to go
javascript call action class method instruts
javascript call action class method instruts in struts2 onchange event call a method in Actionclass with selected value as parameter how can i
javascript - Struts
javascript how to make code in struts2 for check valid name like javascript Hi friend,
For solving the problem visit to :
Thanks
Generating dynamic fields in struts2
Generating dynamic fields in struts2 Hi,
I want generate a web page which should have have some struts 2 tags in a group and a "[+]" button... and so on. Can anybody tell me how can I accomplish this task? If I accomplish how validation problem - Struts
struts validation problem i used client side validation in struts 2... it on the top of the page ya right side of the component.
Que: how to configure parameter for the message tag or any other alternative solution? Hi
JavaScript - JavaScript Tutorial
is JSP using JavaScript
I this example we will show you how to validate... on the checkbox option while selecting any option or we can call the
JavaScript method... how to immediately put JavaScript to validate forms, calculate
values,
Checkbox Problem--Please Check this - JSP-Servlet
Checkbox Problem I am facing a problem while creating a check box in JavaScript. Can any one share the part of code to create a checkbox in JavaScript2 - Struts
Struts2 and Ajax Example how to use struts2 and ajax
code problem - Struts
code problem hi friends i have 1 doubt regarding how to write the code of opensheet in action class i have done it as
the action class code...(SHEET_OPEN_SUCCESS);
return af;
}
i have to retrive it by date if u
Struts2
enable disable checkbox in javascript
enable disable checkbox in javascript How to enable disable checkbox in javascript using
struts html tag - Struts
struts html tag Hi, the company I work for use an "id" tag on their tag like this: How can I do this with struts? I tried and they don't work
How to Assign struts2 property to jsp variable
How to Assign struts2 property to jsp variable In Struts2
<s:property
I wants to assign
<% int count = %><s... will provide you a good example that will illustrate you struts property tag easily -
function call in javascript - Java Beginners
function call in javascript hi all,
i've written a javascript , but i m unable to call a function getExpression.i dont know why getExpression... is :
Hi Friend,
The function you have tag - Struts
Struts tag I am new to struts,
I have created a demo struts application in netbean,
Can any body please tell me what are the steps to add new tags to any jsp page
jsp usebean problem - Struts
the below javascript
var... the appropriate popup window...for example if i select the client
for client popupwindow jsp below code run..
...here iam getting the problem..in the below - Framework
struts2 i m beginner for struts2.i tried helloworld program from....
when i execute the program it showing this only
Current date and time is:
i downloaded example from below link-blank-1.3.10.jar
it shows the below one
Microsoft Windows [Version 6.1.7600
Checkbox pagination problem
Checkbox pagination problem HI .,
Following is my code
test.jsp... Selected Domains
" type=checkbox...
My actual proble is as follows:
Above code is working, but i
xcode make phone call
xcode make phone call xcode make phone call - Our iPhone application required a feature to call over any given mobile or phone number. Just wondering how to enable this feature in my application. Though i have see
JavaScript Checkbox getElementById
JavaScript Checkbox getElementById...() for
checkbox in JavaScript.
In the given example we are going to show an image on clicking the checkbox.
This is done by using the JavaScript method getElementById
struts2 - Framework
struts2 thnx ranikanta
i downloaded example from below link
i m using JDK 1.6 and Tomcat 6.0 ,eclipse 3.3in my application.
i extract
Javascript Examples
area can be deleted or erased using Javascript. In the
example below, we have...; with JavaScript.
JavaScript XML to HTML
As you have already learned how to access... to any past date. The example below shows how to delete the cookie from the browser
Struts problem - Struts
Struts problem I have a registration form that take input from user and show it on next page when user click on save button it save the input in db, give me some hints to achieve it using struts | http://roseindia.net/tutorialhelp/comment/46021 | CC-MAIN-2014-35 | en | refinedweb |
explanation to your code - Java Beginners
explanation to your code sir,
I am very happy that you have...)?And i have imported many classes.but in your code you imported a very few classes.sir i need your brief explanation on this code and also your guidance.this
I need your help - Java Beginners
I need your help What is the purpose of garbage collection in Java, and when is it used? Hi check out this url :
I need your help - Java Beginners
the file name is ApplicationDelivery.java
Your program must follow proper Java...I need your help For this one I need to create delivery class for a delivery service .however, this class should contain (delivery number which
This Question was UnComplete - Java Beginners
your need.Create a sourceFile and goahead.
/**
* Program to take an single... to delete the temporary file). **/
public void deleteFile(String fileName
java - Java Beginners
();
}
}
/**
* Deletes the object file.
*/
public void deleteFile() {
File
Controlling your program
statements (break, continue, return)
in Java programming language.
Selection
The if statement: To start with controlling statements in Java, lets have.... That is the if statement in
Java is a test of any boolean expression. The statement following
java beginners - Java Beginners
java beginners
the patteren u received is not the actual patteren... to sent the different patterns so that your will get the right one...(.) and send your pattern.
Thanks
java beginners - Java Beginners
java beginners
let me know the java code for the followign... args[])
{
System.out.println("try these........");
System.out.println("your... these........");
System.out.println("your series is.....");
for(i=1;i<=3;i
Java basics - Java Beginners
:// for more code and examples on Java...literals in java program Why we use literals in java program? ...; literals are represented directly in your code without requiring computation. As shown
Java programming - Java Beginners
to :
Thanks...Java programming hi sir, my question are as follows...
hope u can solve my java programming problem..
Write a program to develop a class to hold
java programming problem - Java Beginners
.. programming problem Hello..could you please tell me how can I
java - file delete - Java Beginners
java - file delete I will try to delete file from particular folder. My code is executed correctly in other project and main function. In same... class DeleteFile {
public static void main(String[] args) {
String
small java project - Java Beginners
small java project i've just started using java at work and i need to get my self up to speed with it, can you give me a small java for beginners project to work on.
your concern will be highly appreciated
Java Basic Tutorial for Beginners
Java Basic Tutorial for Beginners - Learn how to setup-development
environment and write Java programs
This tutorial will get you started with the Java...)
More tutorials for beginners
Getting
Started with Java
Learn
Java projects for beginners
In this tutorial you will be briefed about the Java projects for beginners... will explore your java ideas and your
thoughts.
It is advised that students... about the nature of your projects
being beginners.
You should also add
Creating your own package in java
and subpackage click on the
following links
Create Your Own Package
Create
java-io - Java Beginners
Thanks...java-io Hi Deepak;
down core java io using class in myn... your code do some changes in your code :
int r,c;
int arr[][];
intialize r
java - Java Beginners
visit these following pages for your answers :
I hope this will help you...java Q 1- write a program in java to generate Armstrong numbers
Java Syntax - Java Beginners
/java/beginners/array_list_demo.shtml
Thanks...Java Syntax Hi!
I need a bit of help on this...
Can anyone tell... Lists unless you provide your own method
java.util Implementations of List
Java Objects - Java Beginners
Java Objects Hi I have the following question, What method in Java is used to destroy your objects.
Thanks in advance
Ask Programming Questions and Discuss your Problems
Ask Programming Questions and Discuss your Problems
Dear Users, Analyzing your plenty of problems and your love for Java and Java and Java related fields, Roseindia Technologies
java - Java Beginners
; Advanced->Environment Variables and create your JAVA_HOME, CLASSPATH etc. there.
The value of JAVA_HOME variable is the root folder location of your JAVA... variable is the "bin" folder location in your JAVA Installation. Eg: C:\Program Files
java programming - Java Beginners
java programming asking for the java code for solving mathematical equation with two unknown .thnx ahead.. Hi Friend,
Please clarify your question. Which mathematical equations you want to solve?
Thanks
java program - Java Beginners
java program 1.java program to Develop a multi-threaded GUI application of your choice.
2.program to Develop a template for linked-list class along with its methods in Java
java - Java Beginners
java Develop a multi-threaded GUI application of your choice. Hi Friend,
Please visit the following link:
Hope that it will be helpful
Java - Java Beginners
OutOfMemoryError error is your Java program, you should consider increasing the JVM space...Java 1.How do you declare the starting point of a Java application?
2. What happened if your program terminates with an OutOfMemoryError a java code that takes input regular expression and a string and produces as output all lines of the string that contains a substring denoted by regular expression Hi Friend,
Please clarify your problem
java - Java Beginners
to your employer, peers and customers that you are proficient in Java...java What is SCJP and write its benefits. How it is useful for JAVA programmers. Hi Friend,
Sun Certified Java Programmer
java - Java Beginners
to your employer, peers and customers that you are proficient in Java...java What is SCJP and write its benefits. How it is useful for JAVA programmers. Hi Friend,
Sun Certified Java Programmer
java Frames - Java Beginners
java Frames Hi friend,
Thanks for your reply. Can i use frames in socket program. Hi anita,
I am sending you a link...://
Thanks
JAVA statement - Java Beginners
JAVA statement The import statement is always the first noncomment statement in a Java program file.Is it true? Hi Friend,
No,it is not true.If your class belongs to a package, the package statement should
Java Query - Java Beginners
Java Query Q.What is "Identifier Expected Error" in Java and when... the code inside the class body.
3)If you will not call your method properly... will not declare your class, constructor and method properly.
5)If your class name
Java Tutorial for Beginners
This Java tutorial for beginners is very useful for a person new to Java. You....
First we will ensure that the Java is installed and configured on your computer..., first install and configure Java on your computer.
Lets write an application
Java Project - Java Beginners
Java Project Dear Sir,
Right now i am working in java image..., shape .
So how to split one image like Texture, color, shape , kindly give your...,
Please visit the following links:
java - Java Beginners
java your website is best
look i am intension of this java... the following links:
http
insertionSort - Java Beginners
insertionSort 1 Problem Task
Your task is to develop part...));
}
}
For more information on Java Array visit to :
Thanks
Java Tutorial for Beginners in Java Programming
Java Tutorial for Beginners - Getting started tutorial for beginners in Java
programming language
These tutorials for beginners in Java will help you....
Let's get started with the Java Tutorial for Beginners
Here are the basic
java - Java Beginners
java how to manipulate thumb impression using java.for that what technology i should use? Give your details correctly. Cant able to understand your question
Core java - Java Beginners
multiple inheritance from java is removed.. with any example..
Thank you in advance for your valuable answer
Hi,
I am sending you...://
Thanks Hi
java hi,
i'm chandrakanth.k. i dont know about java. but i'm...:// project - Java Beginners
java project hi this amol
i wish to do a project on banking software in java
can u help
how can i help u .. and what the kind... adam
certified java programmer
certified websphere ya sure!!
what
java encoding - Java Beginners
://
Your comments are welcome regarding...java encoding how to encode String variable to ASCII,FromBase64String,UTF8 Hi
It's very easy to convert String Variable into ASCII
java methods - Java Beginners
java methods Hello,
what is difference between a.length() and a.length;
kindly can anybody explain.
thanks for your time Hi Friend,
length() is used to find the length of string whereas length is used Error - Java Beginners
Java Error Hello Sir ,How i Can solve Following Error
Can not find Symbol - in.readLine();
Here Error Display at in Hi Friend,
It seems that you haven't defined the object 'in'.Anyways, Send your code so that we
java programming - Java Beginners
java programming heloo expert,
thanks for your coding
i recently asked about the question on abt how to program a atm system
may i noe in which platform can i run those codes ??
netbeans ?? any suggestions
core java - Java Beginners
core java when write java program in editplus.then save&compile the file.
1-text file
2-class file
3-bak file
how can get this files plz tell me Hi Friend,
Please clarify your problem.
Thanks
java - Java Beginners
java E:\sushant\Core Java\threading>javac -Xlint...; This warning comes when methods of old Java Versions are invoked. Just ignores this warning and run the program. Your program will successfully runs.
JAVA PROJECT - Java Beginners
JAVA PROJECT Dear Sir,
I going to do project in java " IT in HR, recruitment, Leave management, Appriasal, Payroll"
Kindly guide me about... etc. I am doing project first time.
waiting for your reply,
Prashant
Package in Java - Java Beginners
myPackage and under that you can see your java file andd class file of packageExp... that folder of related java files.
ex,
if you write a jaava class like
Java Compilation - Java Beginners
Java Compilation How do you design a Java application that inputs a single letter and prints out the corresponding digit on a telephone?
It should... for your Help
Java Stack - Java Beginners
Java Stack Can you give me a code using Java String STACK
using the parenthesis symbol ( )
the user will be the one to input parenthesis... for your help
sample output
Enter a string: ()()
VALID
Enter a string
Java Project - Java Beginners
Java Project Hey, thanks for everything your doing to make us better. Am trying to work on a project in java am in my first year doing software Engineering and the project is m end of year project. Am really believing
JAVA - Java Beginners
JAVA Dear Sir,
Kindly arrange to send urgently the answers to the following in JAVA rega1.JAVA rding True or False, please.
1. JAVA is pure object oriented Language .. True/False
2. Private number of your Class - Java Beginners
java what does the following mean?
1.this
2.is-a
3.has-a
Hi Friend,
Please clarify your problem.
Thanks
java - Java Beginners
java /* Write a program that converts a number entered in Roman numerals to decimal. Your program should consists
* of a class, say Roman...
* L 50
* X 10
* V 5
* I 1
*
* d) test your program using
java - Java Beginners
java what is the difference between classpath and path ... files
While Classpath is Enviroment Variable that tells JVM or Java Tools where to find your classes.
In PATH Environment variable you need to specify only
Link List proble, - Java Beginners
/java/beginners/linked-list-demo.shtml
Hope that it will be helpful for you... Node
to your list and Delete to your list......
my brain is bleeding can you
Java Compilation - Java Beginners
Java Compilation Dear Sir,
Thanks for giving the code for the question which i posted.
I went through the program
"Write a Java program to read... that each DNA sequence is just a String). Your program should sort the sequences
java - Java Beginners
:
C:\mywork> path c:\Program Files\Java\jdk1.5.0_09\bin;%path%
4. Compile your class(es):
C:\mywork> javac *.java
5. Create... Command Prompt.
2. Navigate to the folder that holds your class files
java - Java Beginners
error is could not create a java virtual machine.. The error UnsupportedClassVersionError means you are trying to run Java code compiled with a new version of Java with an old version of the runtime environment.
Version 49.0
java array - Java Beginners
java array 1.) Consider the method headings:
void funcOne(int...];
int num;
Write Java statements that do the following:
a. Call... and Alist, respectively.
THANK YOU GUYS FOR SHARING YOUR IDEA ABOUT THIS.THANK
java problem - Java Beginners
java problem Suppose list is an array of five components of the type int.What is stored in list after the following Java code executes?
for (i...] - 3;
}
THANK YOU GUYS FOR SHARING YOUR IDEA ABOUT THIS.THANK YOU SO MUCH!ILL
Java - Java Beginners
Please let me know the way
Thanks in advance
Awaiting your reply Hi Friend
your first answer is absolutely right.i am...://
java program - Java Beginners
java program plzzzzz help me on this java programming question?
hello people.. can u plzzzzzzzzzzzzzzzzzzz help me out with this java programm. its...
1. Enter your move: D a
-----------------------
Board Positions
+ A
o
java program - Java Beginners
java program what is the program the a simple program in Java that allows a user to enter 3 integers representing the lengths of the sides... the following code to solve your problem.
class Triangle
{
public static
Java Array - Java Beginners
Java Array Can someone help me to convert this to java?
I have an array called Projects{"School", "House", "Bar"}
I want all the possible... -> ["School", "House", "Bar"]
Thanks in advance for your time
java program - Java Beginners
java program i have two classes like schema and table. schema class... name, catelogue,columns, primarykeys, foreignkeys. so i need to write 2 java... retrieves data from database(mysql). Hi friend,
Please specify your
java - Java Beginners
java hello,
Please help me with code for the following
well,i am supposed to create a java program that recieves information from other programs... you.
and your previous code really helped me alot thanks alot.
java - Java Beginners
it is the ability to "reflect" on the structure of your program.
For more information, visit the following link:
Thanks
java code - Java Beginners
java code Write a program that performs flashcard testing of simple mathematical problems. Allow the user
to pick the category. Repetitively... and have the following concepts in your program:
? Array of objects.
? Class
core java - Java Beginners
; Hi friend,
As per your requirement code for equilateral traiangle...://
Thanks
java - Java Beginners
it is the ability to "reflect" on the structure of your program.
For more information, visit the following link:
OOP - Java Beginners
);
}
For more information on Java visit to :
Thanks...)
{
one =a;
two=b;
}
}
Hi friend,
We check your code having
java - Java Beginners
java All programming languages have different pattern of data declaration, data types and operators it supports. Hi Friend,
Please clarify your problem.
Thanks
Java Not running - Java Beginners
Java Not running Hi,
I tried to create a grade(type array...) {
System.out.print("Your Final Grade is A");
} else if ((average <= 60) && (average < 70)) {
System.out.print("Your Final Grade
java - Java Beginners
java
Reading a file content in java(with concept & source code)
Reading contents of any URL in java (with concept & source code) Hi...) {
System.out.println("Sorry! Your given file is too large.");
System.exit(0
java - Java Beginners
java i have to make a programm in java to multiply any number with 100 without using any math operator.I hav got this answer. but i hav to make... to solve your problem. Here is a sample code which you can use for your help
Java - Java Beginners
codes (sorting and partitioning) to Java. It should be able
to execute any set of data. Note:- You should provide the test data and the results of
your program.
(d) Modify your program to show the performance of the quicksort algorithm when
java Code - Java Beginners
java Code Write a Java Program that find out the age of person...{
public static void main(String[]args){
System.out.println("Enter your Date...) - cal1.get(Calendar.YEAR) + factor;
System.out.println("Your age
java - Java Beginners
java java.lang.NoClassDefFoundError
runtime exception
check whatever class u used are exist or not in your current project path Thrown if the Java Virtual Machine or a ClassLoader instance tries to load
java code - Java Beginners
java code
Sir
Ineed one code for Matrix
"Take a 2D array and display all elements in matrix form using only one loop "
request
this question i asked last one week back but Your people send me one answer
Java - Java Beginners
Java Dear Sir,
I am working image searching in java project , in that i have to split one
image like texture , color , shape then after... to what i am giving.
Kindly give your suggestions and i need source coding also
java - Java Beginners
java write a java programe to get the multiplication table from 1 - 10..
Hi Friend,
Here we are sending you a code which prints the table for any number you want to insert. Please check the code to solve your
Java Program - Java Beginners
Java Program Hi I have this program I cant figure out.
Write a program called DayGui.java that creates a GUI having the following properties...
Mnemonic B
Add individual event handlers to the your program so that when
java multithread - Java Beginners
java multithread Hi,
Thanks for your multithreading java code. It helped me a lot.
But i have one issue. My code is look like this.
public class classname extends Thread {
public classname() {
super
java answerURGENT! - Java Beginners
java answerURGENT! consider folowing method headings:
public static... these parameters in a call to the method test?
e.Write a Java statement that prints..., and 'z'.
f.Write a Java statement that prints the value returned by method two
Java examples for beginners
of
examples.
Java examples for beginners: Comparing Two Numbers
The tutorial provide...In this tutorial, you will be briefed about the word of Java examples, which
help to understand functioning of different Java classes and way. It also
java - Java Beginners
in Java. PROGRAM TO IMPLEMENT LINKED LIST
Implementation File... s1;
node newnode=new node();
System.out.println("Input your data for your...;
newnode.nxt=head.nxt;
head.nxt=newnode;
System.out.print("Your node
java - Java Beginners
java how to wtite a program that evaluates the series for some integer n input by the user where n! is a factorial of n Hi Friend,
Please clarify your problem. Do you want to print the factorial of a number | http://www.roseindia.net/tutorialhelp/comment/41665 | CC-MAIN-2014-35 | en | refinedweb |
NAME
pfind, zpfind - locate a process by number
SYNOPSIS
#include <sys/param.h> #include <sys/proc.h> struct proc * pfind(pid_t pid); struct proc * zpfind(pid_t pid);
DESCRIPTION
pfind() takes a pid as its argument and returns a pointer to the proc structure whose PID is specified in the argument only if the pid is on the allproc list. zpfind() takes a pid as its argument. If zpfind() finds a process whose PID is equal to that of argument and is a zombie process, meaning that it must reside on the zombproc list, zpfind() returns a pointer to that proc structure. Both pfind() and zpfind() lock the proc structure that is returned using PROC_LOCK(p).
RETURN VALUES
pfind() and zpfind() return a pointer to a proc structure on success and a NULL on failure.
SEE ALSO
pgfind(9)
AUTHORS
This manual page was written by Evan Sarmiento 〈kaworu@sektor7.ath.cx〉. | http://manpages.ubuntu.com/manpages/jaunty/man9/zpfind.9freebsd.html | CC-MAIN-2014-35 | en | refinedweb |
51589/query-regarding"
^
You can perform this task in two ways as below,,
Hope this helps!
If you want to know more about Apache Spark Scala, It's highly recommended to go for Spark certification course today.
Thanks!!
1) Use the concat() function. Refer to the below ...READ MORE
You can use this:
lines = sc.textFile(“hdfs://path/to/file/filename.txt”);
def isFound(line):
if ...READ MORE
Function Definition :
def test():Unit{
var a=10
var b=20
var c=a+b
}
calling ...READ MORE
Hi,
You can see this example to,
To format a string, use the .format ...READ MORE
All prefix operators' symbols are predefined: +, -, ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/51589/query-regarding-appending-to-a-string-in-scala | CC-MAIN-2022-33 | en | refinedweb |
function_ref: a non-owning reference to a
Callable
This paper proposes the addition of
function_ref<R(Args...)> to the Standard Library, a “vocabulary type” for non-owning references to
Callable objects.
Made copy constructor and copy assignment
= default;
Changed uses of
std::decay_t to
std::remove_cvref_t;
Added “exposition only”
void* and pointer to function data members;
Moved “Open questions” section to “Annex: previously open questions”;
Change
function_ref(F&&) constructor’s precondition to use
remove_cvref_t to check if
F is an instance of the
function class template;
Dropped
function_ref<Signature>:: qualification in member function specification.
We want to prevent construction of std::function from std::function_ref (but not other callable-taking things like std::bind).
SF F N A SA
0 0 4 8 0
We want to revise the paper to include discussion of ref-qualified callables.
SF F N A SA
0 3 6 6 0
Forward paper as-is to LWG for C++20?
SF F N A SA
3 9 3 0 0
Should the
!f precondition when constructing
function_ref from an instance
f of
std::function be removed? The behavior in that case is well-defined, as
f is guarateed to throw on invocation.
The
std::is_nothrow_invocable constraint in
function_ref construction/assignment for
noexcept signatures prevents users from providing a non-
noexcept function, even if they know that it cannot ever throw (e.g. C functions). Should this constraint be removed? Should an
explicit constructor without the constraint be provided?
Propagating
const to
function_ref::operator() doesn’t make sense when looking at
function_ref as a simple “reference” class.
const instances of
function_ref should be able to invoke a
mutable lambda, as the state of
function_ref itself doesn’t change. E.g.
auto l0 = []() mutable { }; const function_ref<void()> fr{l0}; fr(); // Currently a compilation error
An alternative is to only propagate
noexcept from the signature to
function_ref::operator(), and unconditionally
const-qualify
function_ref::operator(). Do we want this?
We want to avoid double indirection when a
function_ref instance is initialized with a
reference_wrapper.
function_ref could just copy the pointer stored inside the
reference_wrapper instead of pointing to the wrapper itself. This cannot be covered by the as-if rule as it changes program semantics. E.g.
auto l0 = []{ }; auto l1 = []{ }; auto rw = std::ref(l0); function_ref<void()> fr{rw}; fr(); // Invokes `l0` rw = l1; fr(); // What is invoked?
Is adding wording to handle
std::reference_wrapper as a special case desirable?
Is it possible and desirable to remove
function_ref’s template assignment operator from
F&& and rely on an implicit conversion to
function_ref + the default copy assignment operator?
Should
function_ref only store a
void* pointer for the callable object, or a
union? In the first case, seemingly innocent usages will result in undefined behavior:
If a
union is stored instead, the first usage could be well-formed without any extra overhead (assuming
sizeof(void*) == sizeof(void(*)())). The second usage could also be made well-formed, but with size overhead as
sizeof(void(C::*)()) > sizeof(void*).
Regardless, the exposition-only members should clearly illustrate the outcome of this decision.
Note that if we want the following to compile and be well-defined, a
void(*)() would have to be stored inside
function_ref:
Should the
function_ref(F&&) deduction guide take its argument by value instead? This could simplify the wording.
Removed empty state and comparisons with
nullptr;
Removed default constructor;
Added support for
noexcept and
const-qualified function signatures (these are propagated to
function_ref::operator());
Added deduction guides for function pointers and arbitrary callable objects with well-formed
&remove_reference_t<F>::operator();
Added two new bullet points to “Open questions”;
Added “Example implementation”;
Added “Feature test macro”;
Removed
noexcept from constructor and assignment.
option 1
function_ref, non-nullable, not default constructible
option 2
function_ptr, nullable, default constructible
We want 1 and 2
SF F N A SA
1 2 8 3 6
ref vs ptr
SR R N P SP
6 5 2 5 0
The poll above clearly shows that the desired direction for
function_ref is towards a non nullable, non default-constructible reference type. This revision (P0792R2) removes the “empty state” and default constructibility from the proposed
function_ref. If those semantics are required by users, they can trivially wrap
function_ref into an
std::optional<function_ref</* ... */>>.
targetand
target_type
We want target and target-type (consistent with std::function) if they have no overhead
Unanimous consent
We want target and target-type (consistent with std::function) even though they have overhead
SF F N A SA
0 0 1 9 4
I am not sure whether
target and
target_type can be implemented without introducing overhead. I seek the guidance of the committee or any interested reader to figure that out. If they require overhead, I agree with the poll: they will be left out of the proposal. Signature> class function_ref { void* object; // exposition only R(*erased_function)(Args...) qualifiers; // exposition only // `R`, `Args...`, and `qualifiers` are the return type, the parameter-type-list, // and the sequence "cv-qualifier-seq-opt noexcept-specifier-opt" of the function // type `Signature`, respectively. public: constexpr function_ref(const function_ref&) noexcept = default; template <typename F> constexpr function_ref(F&&); constexpr function_ref& operator=(const function_ref&) noexcept = default; template <typename F> constexpr function_ref& operator=(F&&); constexpr void swap(function_ref&) noexcept; R operator()(Args...) qualifiers; // `R`, `Args...`, and `qualifiers` are the return type, the parameter-type-list, // and the sequence "cv-qualifier-seq-opt noexcept-specifier-opt" of the function // type `Signature`, respectively. }; template <typename Signature> constexpr void swap(function_ref<Signature>&, function_ref<Signature>&) noexcept; template <typename R, typename... Args> function_ref(R (*)(Args...)) -> function_ref<R(Args...)>; template <typename R, typename... Args> function_ref(R (*)(Args...) noexcept) -> function_ref<R(Args...) noexcept>; template <typename F> function_ref(F&&) -> function_ref<see below>; }
The template argument
Signature shall be a non-
volatile-qualified function type.
<functional>header
Add the following to
[functional.syn]:
namespace std { // ... template <typename Signature> class function_ref; template <typename Signature> constexpr void swap(function_ref<Signature>& lhs, function_ref<Signature>& rhs) noexcept; // ... }
function_refreferring to the same callable
rhsrefers to.
Requires: none of the following must hold:
f is a null function pointer value.
f is a null member pointer value.
remove_cvref_t<F> is an instance of the
function class template, and
!f.
Effects: constructs a
function_ref referring to
f.
Remarks: This constructor...>.
Where
R,
Args..., and
cv-qualifiers are the return type, the parameter-type-list, and the sequence “cv-qualifier-seq-opt” of the function type
Signature, respectively.
Postconditions:
*this refers to the same callable
rhs refers to.
Returns:
*this.
Requires: none of the following must hold:
f is a null function pointer value.
f is a null member pointer value.
F is an instance of the
function class template, and
!f.
Remarks: This function...>.
Postconditions:
*this refers to
f.
Returns:
*this.
*thisand
rhs.
return INVOKE<R>(f, std::forward<Args>(xs)...);, where
fis the callable object referred to by
*this, qualified with the same cv-qualifiers as the function type
Signature.
&remove_reference_t<F>::operator()is well-formed when treated as an unevaluated operand. In that case, if
decltype(&remove_reference_t<F>::operator())is of the form
R(G::*)(A...) qualifiersfor a class type
G, then the deduced type is
function_ref<R(A...) qualifiers>, where
qualifiersis the sequence “cv-qualifier-seq-opt noexcept-specifier-opt” of the function type
F.
template <typename Signature> constexpr void swap(function_ref<Signature>& lhs, function_ref<Signature>& rhs) noexcept;
lhs.swap(rhs).
I propose the feature-testing macro name
__cpp_lib_function_ref.
An example implementation is available here on GitHub.. E.g.
The usage shown above is completely safe: the temporary closure generated by the lambda expression is guarantee to live for the entirety of the call to
foo. Unfortunately, this also means that the following code snippet will result.
The name
function_ref is subject to bikeshedding. Here are some other potential names:
function_view
callable_ref
callable_view
invocable_ref
invocable_view
fn_view
fn_ref
Thanks to Agustín Bergé, Dietmar Kühl, Eric Niebler, Tim van Deurzen, and Alisdair Meredith for providing very valuable feedback on earlier drafts of this proposal.
Below are some unanswered questions for which I kindly ask guidance from members of the commitee and readers of this paper.
function_ref<Signature>’s signature currently only accepts any combination of
const and
noexcept. Should this be extended to include ref-qualifiers? This would mean that
function_ref::operator() would first cast the referenced callable to either an lvalue reference or rvalue reference (depending on
Signature’s ref qualifiers) before invoking it. See P0045R1 19 and N4159 20) for additional context.
constand
noexcepthave useful cases, but we could not find enough motivation to include support for ref-qualified signatures. Nevertheless, this could be added as a non-breaking extension to
function_refin the future.
Constructing a
std::function<Signature> from a
function_ref<Signature> is completely different from constructing a
std::string from a
std::string_view: the latter does actually create a copy while the former remains a reference. It may be reasonable to prevent implicit conversions from
function_ref to
std::function in order to avoid surprising dangerous behavior.
std::functionconstruction from
std::function_refas it would special-case
std::functionand there are other utilities in the Standard Library (and outside of it) that would need a similar change (e.g.
std::bind).
function_ref::operator() is not currently marked as
constexpr due to implementation issues. I could not figure a way to implement a
constexpr-friendly
operator(). Is there any possibility it could be marked as
constexpr to increase the usefulness of
function_ref?
constexpr
function_ref::operator()and that we do not want to impose that burden on implementations↩ | https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0792r2.html | CC-MAIN-2022-33 | en | refinedweb |
----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.STM.TSem -- Copyright : (c) The University of Glasgow 2012 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (requires STM) -- -- 'TSem': transactional semaphores. -- -- @since 2.4.2 ----------------------------------------------------------------------------- {-# LANGUAGE DeriveDataTypeable #-} module Control.Concurrent.STM.TSem ( TSem , newTSem , waitTSem , signalTSem , signalTSemN ) where import Control.Concurrent.STM import Control.Monad import Data.Typeable import Numeric.Natural -- | 2.4.2 newtype TSem = TSem (TVar Integer) deriving (Eq, Typeable) -- | Construct new 'TSem' with an initial counter value. -- -- A positive initial counter value denotes availability of -- units 'waitTSem' can acquire. -- -- The initial counter value can be negative which denotes a resource -- \"debt\" that requires a respective amount of 'signalTSem' -- operations to counter-balance. -- -- @since 2.4.2 newTSem :: Integer -> STM TSem newTSem i = fmap TSem (newTVar $! i) -- NOTE: we can't expose a good `TSem -> STM Int' operation as blocked -- 'waitTSem' aren't reliably reflected in a negative counter value. -- | Wait on 'TSem' (aka __P__ operation). -- -- This operation acquires a unit from the semaphore (i.e. decreases -- the internal counter) and blocks (via 'retry') if no units are -- available (i.e. if the counter is /not/ positive). -- -- @since 2.4.2 waitTSem :: TSem -> STM () waitTSem (TSem t) = do i <- readTVar t when (i <= 0) retry writeTVar t $! (i-1) -- Alternatively, the implementation could block (via 'retry') when -- the next increment would overflow, i.e. testing for 'maxBound' -- | Signal a 'TSem' (aka __V__ operation). -- -- This operation adds\/releases a unit back to the semaphore -- (i.e. increments the internal counter). -- -- @since 2.4.2 signalTSem :: TSem -> STM () signalTSem (TSem t) = do i <- readTVar t writeTVar t $! i+1 -- | Multi-signal a 'TSem' -- -- This operation adds\/releases multiple units back to the semaphore -- (i.e. increments the internal counter). -- -- > signalTSem == signalTSemN 1 -- -- @since 2.4.5 signalTSemN :: Natural -> TSem -> STM () signalTSemN 0 _ = return () signalTSemN 1 s = signalTSem s signalTSemN n (TSem t) = do i <- readTVar t writeTVar t $! i+(toInteger n) | https://downloads.haskell.org/ghc/8.10.7/docs/html/libraries/stm-2.5.0.1/src/Control-Concurrent-STM-TSem.html | CC-MAIN-2022-33 | en | refinedweb |
Combines two images in a checkerboard pattern. More...
#include <sitkCheckerBoardImageFilter.h>
Combines two images in a checkerboard pattern.
CheckerBoardImageFilter takes two input images that must have the same dimension, size, origin and spacing and produces an output image of the same size by combining the pixels from the two input images in a checkerboard pattern. This filter is commonly used for visually comparing two images, in particular for evaluating the results of an image registration process.
This filter is implemented as a multithreaded filter. It provides a DynamicThreadedGenerateData() method for its implementation.
Definition at line 44 of file sitkCheckerBoardImageFilter.h.
Setup for member function dispatching
Definition at line 87 of file sitkCheckerBoardImageFilter.h.
Define the pixels types supported by this filter
Definition at line 56 of file sitkCheckerBoardImageFilter.h.
Definition at line 46 of file sitkCheckerBoardImageFilter.h.
Destructor
Default Constructor that takes no arguments and initializes default parameters
Execute the filter on the input images
Set/Get the checker pattern array, i.e. the number of checker boxes per image dimension.
Definition at line 70 of file sitkCheckerBoardImageFilter.h.
Name of this class
Implements itk::simple::ProcessObject.
Definition at line 73 of file sitkCheckerBoardImageFilter.h.
Set/Get the checker pattern array, i.e. the number of checker boxes per image dimension.
Definition at line 62 of file sitkCheckerBoardImageFilter.h.
Set the values of the CheckerPattern vector all to value
Definition at line 65 of file sitkCheckerBoardImageFilter.h.
Print ourselves out
Reimplemented from itk::simple::ProcessObject.
Definition at line 91 of file sitkCheckerBoardImageFilter.h.
Definition at line 96 of file sitkCheckerBoardImageFilter.h.
Definition at line 93 of file sitkCheckerBoardImageFilter.h. | https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1CheckerBoardImageFilter.html | CC-MAIN-2022-33 | en | refinedweb |
How to Play, Record and Merge Videos in iOS and Swift
Learn the basics of working with videos on iOS with AV Foundation in this tutorial. You’ll play, record and even do some light video editing!
Version
- Swift 5, iOS 13, Xcode 11
Recording videos and playing around with them programmatically is one of the coolest things you can do with your phone. However, not nearly enough apps offer this ability, which you can easily add using the AV Foundation framework.
AV Foundation has been a part of macOS since OS X Lion (10.7) and iOS since iOS 4 in 2010. It’s grown considerably since then, with well over 100 classes to date.
This tutorial gets you started with AV Foundation by covering media playback and some light editing. In particular, you’ll learn how to:
- Select and play a video from the media library.
- Record and save a video to the media library.
- Merge multiple clips into a single, combined video complete with a custom soundtrack.
Avoid running the code in this tutorial on the simulator because. A free account will work just fine for this tutorial.
Ready? Lights, cameras, action!
Getting Started
Download the project materials by clicking the Download Materials button at the top or bottom of the tutorial.
Open the starter project and look around. This project contains a storyboard and several view controllers with the UI for a simple video playback and recording app.
The main screen contains the three buttons below, which segue to other view controllers:
- Select and Play Video
- Record and Save Video
- Merge Video
Build and run and test the buttons. Only the three buttons in the initial scene do anything, but you’ll change that soon!
Selecting and Playing Video
The Select AVKit import MobileCoreServices
Importing
AVKit gives you access to
AVPlayer, which plays the selected video.
MobileCoreServices contains predefined constants such as
kUTTypeMovie, which you’ll need later on.
Next, add the following class extensions at the end of the file. Make sure
PlayVideoViewController to adopt the
UIImagePickerControllerDelegate and
UINavigationControllerDelegate protocols.
You’ll use the system-provided
UIImagePickerController to let the user browse videos in the photo library. That class communicates back to your app through these delegate protocols. Although the class is named “image picker”, rest assured it works with videos too!
Next, head back to
PlayVideoViewController‘s main class definition and add the following code to
playVideo(_:):
VideoHelper.startMediaBrowser(delegate: self, sourceType: .savedPhotosAlbum)
This is a call to a helper method called
startMediaBrowser(delegate:sourceType:) from
VideoHelper. This call will open the image picker, setting the delegate to
self. The source type of
.savedPhotosAlbum opts to choose an image from the camera roll. Later, you’ll add helper tools of your own in
VideoHelper.
To see what’s under the hood of this method, open VideoHelper.swift. It does the following:
- Checks if the source is available on the device. Sources include the camera roll, the camera itself and the full photo library. This check is essential whenever you use
UIImagePickerControllerto pick media. If you don’t do it, you might try to pick media from a non-existent source, which will usually result in a crash.
- If the source you want is available, it creates a
UIImagePickerControllerand sets its source and media type. Since you only want to select videos, the code restricts the type to
kUTTypeMovie.
- Finally, it presents
UIImagePickerControllermodally.
Now, you’re ready to give your project another whirl! Build and run. Tap Select and Play Video on the first screen, then tap Play Video on the second screen. The camera roll will pop up like this:
Once you see the list of videos, select one. You’ll proceed to another screen that shows the video in detail, along with buttons to Cancel, Play and Choose. Tap the Play button and, unsurprisingly, the video will play.
If you tap the Choose button, however, the app just returns to the Play Video screen! This is because you haven’t implemented any delegate methods to handle choosing a video from the picker.
Back in Xcode open PlayVideoViewController.swift again and find the
UIImagePickerControllerDelegate extension. Then add the following delegate method implementation:
func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { // 1 guard let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String, mediaType == (kUTTypeMovie as String), let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL else { return } // 2 dismiss(animated: true) { //3 let player = AVPlayer(url: url) let vcPlayer = AVPlayerViewController() vcPlayer.player = player self.present(vcPlayer, animated: true, completion: nil) } }
Here’s what you’re doing in this method:
- You get the media type of the selected media and URL and ensure it’s a video.
- Next, you dismiss the image picker.
- In the completion block, you create an
AVPlayerViewControllerto play the media.
Build and run. Tap Select and Play Video, then Play Video and choose a video from the list. The video will play in the media player.
Recording Video
Now that you have video playback working, it’s time to record a video using the device’s camera and save it to the media library.
Open RecordVideoViewController.swift and add the following import:
import MobileCoreServices
Then, add the following to the end of the file:
// MARK: - UIImagePickerControllerDelegate extension RecordVideoViewController: UIImagePickerControllerDelegate { } // MARK: - UINavigationControllerDelegate extension RecordVideoViewController: UINavigationControllerDelegate { }
This adopts the same protocols as
PlayVideoViewController.
Next, add the following code to
record(_:):
VideoHelper.startMediaBrowser(delegate: self, sourceType: .camera)
It uses the same helper method as in
PlayVideoViewController, except that it accesses
.camera to instruct the image picker to open in the built in camera mode.
Build and run to see what you have so far.
Go to the Record screen and tap Record Video. Instead of the Photo Gallery, the camera UI opens. When the alert dialog asks for camera permissions and microphone permissions, click OK.
Finally, start recording a video by tapping the red record button at the bottom of the screen; tap it again when you’re done recording.
Now, you have two options: use the recorded video or do a retake. Tap Use Video. You’ll notice that it just dismisses the view controller. That’s because — you guessed it — you haven’t implemented an appropriate delegate method to save the recorded video to the media library.
Saving Video
Back in RecordVideoViewController.swift, add the following method to the
UIImagePickerControllerDelegate extension:
func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { dismiss(animated: true, completion: nil) guard let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String, mediaType == (kUTTypeMovie as String), // 1 let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL, // 2 UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(url.path) else { return } // 3 UISaveVideoAtPathToSavedPhotosAlbum( url.path, self, #selector(video(_:didFinishSavingWithError:contextInfo:)), nil) }
Don’t worry about the error — you’ll take care of that shortly.
- As before, the delegate method gives you a URL pointing to the video.
- Verify that the app can save the file to the device’s photo album.
- If it can, save it.
UISaveVideoAtPathToSavedPhotosAlbum is the function provided by the SDK to save videos to the device’s photo album. You pass it the path to the video you want to save as well as a target and action to call back, which will inform you of the status of the save operation.
Next, add the implementation of the callback to the main class definition:
@objc func video( _ videoPath: String, didFinishSavingWithError error: Error?, contextInfo info: AnyObject ) { let title = (error == nil) ? "Success" : "Error" let message = (error == nil) ? "Video was saved" : "Video failed to save" let alert = UIAlertController( title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction( title: "OK", style: UIAlertAction.Style.cancel, handler: nil)) present(alert, animated: true, completion: nil) }
The callback method simply displays an alert to the user, announcing whether the video file was saved or not, based on the error status.
Build and run. Record a video and select Use Video when you’re done recording. If you’re asked for permission to save to your video library, tap OK.. Your user will select two videos and a song from the music library, and the app will combine the two videos and mix in the music.
The project already has a starter implementation in MergeVideoViewController.swift, with the code similar to the code you wrote to play a video. The big difference is when merging, the user must select two videos. That part is already set up, so the user can make two selections that will be stored in
firstAsset and
secondAsset.
The next step is to add the functionality to select the audio file.
Selecting the Audio File
UIImagePickerController provides functionality to select only video and images from the media library. To select audio files from your music library, you must use(mediaPickerController, animated: true, completion: nil)
The code above creates a new
MPMediaPickerController instance and displays it as a modal view controller.
Build and run. Now, tap Merge Video, then Load Audio.
Select a song from the list and you’ll notice that nothing happens. That’s right!
MPMediaPickerController needs delegate methods!
To implement them, find the
MPMediaPickerControllerDelegate extension at the bottom of the file and add the following two methods to it:
func mediaPicker( _ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection ) { // 1 dismiss(animated: true) { // 2 let selectedSongs = mediaItemCollection.items guard let song = selectedSongs.first else { return } // 3 let title: String let message: String if let url = song.value(forProperty: MPMediaItemPropertyAssetURL) as? URL { self.audioAsset = AVAsset(url: url) title = "Asset Loaded" message = "Audio Loaded" } else { self.audioAsset = nil title = "Asset Not Available" message = "Audio Not Loaded" } // 4 let alert = UIAlertController( title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) { // 5 dismiss(animated: true, completion: nil) }
The code above is similar to the delegate methods for
UIImagePickerController. Here’s what it does:
- Dismiss the picker just like you did before.
- Find the selected songs and, from that, the first one in the case that multiple are selected.
- Obtain the URL to the media asset that backs the song. Then make an
AVAssetpointing to the song that was chosen.
- Finally, for
mediaPicker(_:didPickMediaItems:), show an alert to indicate if the asset was successfully loaded or not.
- In the case the media picker was canceled, simply dismiss the view controller.
Build and run, then go to the Merge Videos screen. Select an audio file and you’ll see the Audio Loaded message.
You now have all your assets loading correctly so it’s time to merge the various media files into one file. But before you get into that code, you need to do a bit of setup.
Merging Completion Handler
You will shortly write the code to merge your assets. This will need a completion handler that saves the final video to the photo album. You’ll add this first.
Add the following import statement at the top of the MergeVideoViewController.swift file:
import Photos
Then, add the method below to
MergeVideoViewController:
func exportDidFinish(_ session: AVAssetExportSession) { // 1 activityMonitor.stopAnimating() firstAsset = nil secondAsset = nil audioAsset = nil // 2 guard session.status == AVAssetExportSession.Status.completed, let outputURL = session.outputURL else { return } // 3 let saveVideoToPhotos = { // 4 let changes: () -> Void = { PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputURL) } PHPhotoLibrary.shared().performChanges(changes) { saved, error in DispatchQueue.main.async { let success = saved && (error == nil) let title = success ? "Success" : "Error" let message = success ? "Video saved" : "Failed to save video" let alert = UIAlertController( title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction( title: "OK", style: UIAlertAction.Style.cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } } // 5 if PHPhotoLibrary.authorizationStatus() != .authorized { PHPhotoLibrary.requestAuthorization { status in if status == .authorized { saveVideoToPhotos() } } } else { saveVideoToPhotos() } }
Here’s what that code does:
- There’s a spinner that will animate when the assets are being processed. This stops the spinner and then clears the assets ready to select new ones.
- Ensure that the processing is complete and there is a URL of the resulting video.
- Create a closure that…
- Tells the photo library to make a “create request” from the resulting video before showing an alert to indicate if this succeeds or fails.
- Check if there is permission to access the photo library. If there is not permission, then ask for it before running the closure that saves the video. Otherwise, simply run the closure immediately as permission is already granted.
Now, you’ll add some code to
merge(_:). Because there’s a lot of code, you’ll complete this in steps.
Merging: Step 1
In this step, you’ll merge the videos into one long video.
Add the following code to
merge(_:):
guard let firstAsset = firstAsset, let secondAsset = secondAsset else { return } activityMonitor.startAnimating() // 1 let mixComposition = AVMutableComposition() // 2 guard let firstTrack = mixComposition.addMutableTrack( withMediaType: .video, preferredTrackID: Int32(kCMPersistentTrackID_Invalid)) else { return } // 3 do { try firstTrack.insertTimeRange( CMTimeRangeMake(start: .zero, duration: firstAsset.duration), of: firstAsset.tracks(withMediaType: .video)[0], at: .zero) } catch { print("Failed to load first track") return } // 4 guard let secondTrack = mixComposition.addMutableTrack( withMediaType: .video, preferredTrackID: Int32(kCMPersistentTrackID_Invalid)) else { return } do { try secondTrack.insertTimeRange( CMTimeRangeMake(start: .zero, duration: secondAsset.duration), of: secondAsset.tracks(withMediaType: .video)[0], at: firstAsset.duration) } catch { print("Failed to load second track") return } // 5 // TODO: PASTE CODE A
In the code above:
- You create an
AVMutableCompositionto hold your video and audio tracks.
- Next, you create an
AVMutableCompositionTrackfor the video and add it to your
AVMutableComposition.
- Then, you insert the video from the first video asset to this track.
Notice that
insertTimeRange(_:ofTrack:atStartTime:)allows you to insert a part of a video, rather than the whole thing, into your main composition. This way, you can trim the video to a time range of your choice.
In this instance, you want to insert the whole video, so you create a time range from
CMTime.zeroto your video asset duration.
- Next, you do the same thing with the second video asset.
Notice how the code inserts
firstAssetat time
.zero, and it inserts
secondAssetat the end of the first video. That’s because this tutorial assumes you want your video assets one after the other, but you can also overlap the assets by playing with the time ranges.
// TODO: PASTE CODE Ais a marker — you’ll replace this line with the code in the next section.
In this step, you set up two separate
AVMutableCompositionTrack instances. Now, you need to apply an
AVMutableVideoCompositionLayerInstruction to each track to make some editing possible.
Merging the Videos: Step 2
Next up is to add instructions to the composition to tell it how you want the assets to be merged.
Add the next section of code after track code above in
merge(_:). Replace
// TODO: PASTE CODE A with the following code:
// 6 let mainInstruction = AVMutableVideoCompositionInstruction() mainInstruction.timeRange = CMTimeRangeMake( start: .zero, duration: CMTimeAdd(firstAsset.duration, secondAsset.duration)) // 7 let firstInstruction = AVMutableVideoCompositionLayerInstruction( assetTrack: firstTrack) firstInstruction.setOpacity(0.0, at: firstAsset.duration) let secondInstruction = AVMutableVideoCompositionLayerInstruction( assetTrack: secondTrack) // 8 mainInstruction.layerInstructions = [firstInstruction, secondInstruction] let mainComposition = AVMutableVideoComposition() mainComposition.instructions = [mainInstruction] mainComposition.frameDuration = CMTimeMake(value: 1, timescale: 30) mainComposition.renderSize = CGSize( width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) // 9 // TODO: PASTE CODE B
Here’s what’s happening in this code:
- First, you set up
mainInstructionto wrap the entire set of instructions. Notice that the total time here is the sum of the first asset’s duration and the second asset’s duration.
- Next, you set up two instructions, one for each asset. The instruction for the first video needs one extra addition: You set its opacity to 0 at the end so it becomes invisible when the second video starts.
- Now that you have your
AVMutableVideoCompositionLayerInstructioninstances for the first and second tracks, you simply add them to
mainInstruction. Next, you add
mainInstructionto the instructions property of an instance of
AVMutableVideoComposition. You also set the frame rate for the composition to 30 frames/second.
// TODO: PASTE CODE Bis a marker — you’ll replace this line with the code in the next section.
OK, so you’ve now merged your two video files. It’s time to spice them up with some sound!
Merging the Audio: Step 3
To give your clip some musical flair, add the following code to
merge(_:). Replace
// TODO: PASTE CODE B with the following code:
// 10 if let loadedAudioAsset = audioAsset { let audioTrack = mixComposition.addMutableTrack( withMediaType: .audio, preferredTrackID: 0) do { try audioTrack?.insertTimeRange( CMTimeRangeMake( start: .zero, duration: CMTimeAdd( firstAsset.duration, secondAsset.duration)), of: loadedAudioAsset.tracks(withMediaType: .audio)[0], at: .zero) } catch { print("Failed to load Audio track") } } // 11 guard let documentDirectory = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask).first else { return } let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .short let date = dateFormatter.string(from: Date()) let url = documentDirectory.appendingPathComponent("mergeVideo-\(date).mov") // 12 guard let exporter = AVAssetExportSession( asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) else { return } exporter.outputURL = url exporter.outputFileType = AVFileType.mov exporter.shouldOptimizeForNetworkUse = true exporter.videoComposition = mainComposition // 13 exporter.exportAsynchronously { DispatchQueue.main.async { self.exportDidFinish(exporter) } }
Here’s what the code above does:
- Similarly to video tracks, you create a new track for your audio and add it to the main composition. You set the audio time range to the sum of the duration of the first and second videos, because that will be the complete length of your video.
- Before you can save the final video, you need a path for the saved file. Create a unique file name based upon the current date and time that points to a file in the documents folder.
- Render and export the merged video. To do this, you create an
AVAssetExportSessionthat transcodes the contents of the composition to create an output of the form described by a specified export preset. Because you’ve already configured
AVMutableVideoComposition, all you need to do is assign it to your exporter.
- After you’ve initialized an export session with the asset that contains the source media, the export
presetNameand
outputFileType, you run the export by invoking
exportAsynchronously().
Because the code performs the export asynchronously, this method returns immediately. The code calls the completion handler you supply to
exportAsynchronously()whether the export fails, completes or the user cancels it.
Upon completion, the exporter’s status property indicates whether the export has completed successfully. If it fails, the value of the exporter’s error property supplies additional information about the reason for the failure.
AVComposition combines media data from multiple file-based sources. At its top level, before and that will come up again.
Finally, build and run.
Select two videos and an audio file and merge the selected files. You’ll see a Video Saved message, which indicates that the merge was successful. At this point, your new video will be present in the photo album.
Go to the photo album or browse using the Select and Play Video screen in the app and you might notice some orientation issues in the merged video. Maybe portrait video is in landscape mode, and sometimes videos are upside down.
This is due to the default
AVAsset orientation. All movie and image files recorded using the default iPhone camera app have the video frame set to landscape, so the iPhone saves the media in landscape mode. You’ll fix these problems next.
Orienting Video
AVAsset has a
preferredTransform that contains the media orientation information. It applies this to a media file whenever you view it using the Photos app or QuickTime.
In the code above, you haven’t applied a transform to your
AVAssets, hence the orientation issue. Fortunately, this is an easy fix.
Before you can do it, however, you need to add the following helper method to
VideoHelper in VideoHelper.swift:
static func orientationFromTransform( _ transform: CGAffineTransform ) -> (orientation: UIImage.Orientation, isPortrait: Bool) { var assetOrientation = UIImage.Orientation.up var isPortrait = false let tfA = transform.a let tfB = transform.b let tfC = transform.c let tfD = transform.d if tfA == 0 && tfB == 1.0 && tfC == -1.0 && tfD == 0 { assetOrientation = .right isPortrait = true } else if tfA == 0 && tfB == -1.0 && tfC == 1.0 && tfD == 0 { assetOrientation = .left isPortrait = true } else if tfA == 1.0 && tfB == 0 && tfC == 0 && tfD == 1.0 { assetOrientation = .up } else if tfA == -1.0 && tfB == 0 && tfC == 0 && tfD == -1.0 { assetOrientation = .down } return (assetOrientation, isPortrait) }
This code analyzes an affine transform to determine the input video’s orientation.
Next, add the following import:
import AVFoundation
and one more helper method to the class:
static func videoCompositionInstruction( _ track: AVCompositionTrack, asset: AVAsset ) -> AVMutableVideoCompositionLayerInstruction { // 1 let instruction = AVMutableVideoCompositionLayerInstruction(assetTrack: track) // 2 let assetTrack = asset.tracks(withMediaType: AVMediaType.video)[0] // 3 let transform = assetTrack.preferredTransform let assetInfo = orientationFromTransform(transform) var scaleToFitRatio = UIScreen.main.bounds.width / assetTrack.naturalSize.width if assetInfo.isPortrait { // 4 scaleToFitRatio = UIScreen.main.bounds.width / assetTrack.naturalSize.height let scaleFactor = CGAffineTransform( scaleX: scaleToFitRatio, y: scaleToFitRatio) instruction.setTransform( assetTrack.preferredTransform.concatenating(scaleFactor), at: .zero) } else { // 5 let scaleFactor = CGAffineTransform( scaleX: scaleToFitRatio, y: scaleToFitRatio) var concat = assetTrack.preferredTransform.concatenating(scaleFactor) .concatenating(CGAffineTransform( translationX: 0, y: UIScreen.main.bounds.width / 2)) if assetInfo.orientation == .down { let fixUpsideDown = CGAffineTransform(rotationAngle: CGFloat(Double.pi)) let windowBounds = UIScreen.main.bounds let yFix = assetTrack.naturalSize.height + windowBounds.height let centerFix = CGAffineTransform( translationX: assetTrack.naturalSize.width, y: yFix) concat = fixUpsideDown.concatenating(centerFix).concatenating(scaleFactor) } instruction.setTransform(concat, at: .zero) } return instruction }
This method takes a track and an asset and returns a
AVMutableVideoCompositionLayerInstruction which wraps the affine transform needed to get the video right-side up. Here’s what’s going on, step-by-step:
- You create
AVMutableVideoCompositionLayerInstructionand associate it with your
track.
- Next, you create
AVAssetTrackfrom your
AVAsset. An
AVAssetTrackprovides the track-level inspection interface for all assets. You need this object to access the dimensions of the asset and
preferredTransform.
- Then, you save the preferred transform and the amount of scale required to fit the video to the current screen. You’ll use these values in the following steps.
- If the video is in portrait, you need to recalculate the scale factor — the default calculation is for videos in landscape. All you need to do then is apply the orientation rotation and scale transforms.
- If the video is in landscape, there’s a similar set of steps to apply the scale and transform. However, there’s one extra check, because the user could have produced the video in either landscape left or landscape right.
Because there are two landscapes, the aspect ratio will match but the video might be rotated 180 degrees. The extra check for a video orientation of
.downhandles this case.
With the helper methods set up, find
merge(_:) in MergeVideoViewController.swift. Locate where
firstInstruction and
secondInstruction are created and replace them with the following:
let firstInstruction = VideoHelper.videoCompositionInstruction( firstTrack, asset: firstAsset)
let secondInstruction = VideoHelper.videoCompositionInstruction( secondTrack, asset: secondAsset)
The changes above will use the new helper functions and implement the rotation fixes you need.
Whew — that’s it!
Build and run. Create a new video by combining two videos — and, optionally an audio file — and you’ll see that the orientation issues disappear when you play it back.
Where to Go From Here?
Download the final project using the Download Materials link at the top or bottom of this tutorial.
You should now have a good understanding of how to play video, record video and merge multiple videos and audio in your apps.
AV Foundation gives you a lot of flexibility when playing with videos. You can also apply any kind of
CGAffineTransform to merge, scale or position videos.
If you haven’t already done so, take a look at the WWDC videos on AV Foundation, such as WWDC 2016 session 503, Advances in AVFoundation Playback.
Also, be sure to check out the Apple AVFoundation Framework documentation.
I hope this tutorial has been useful to get you started with video manipulation in iOS. If you have any questions, comments or suggestions for improvement, please join the forum discussion below! | https://www.raywenderlich.com/10857372-how-to-play-record-and-merge-videos-in-ios-and-swift | CC-MAIN-2022-33 | en | refinedweb |
>> largest good number in the divisors of given number N in C++
In this problem, we are given a number N. Our task is to find the largest good number in the divisors of given number N.
A good number is a number in which every digit is larger than the sum of digits of its right (all less significant bits than it). For example, 732 is a good number, 7> 3+2 and 3>2.
Let's take an example to understand the problem,
Input : N = 15 Output : 15
Explanation −
Divisors of 15 : 1, 3, 5, 15.
Solution Approach
A simple solution to the problem is by finding all the divisors of N. And they find the largest good number which is extracted as a product of all prime divisors of the number.
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; int findLargestGoodNumber(int n){ vector<int> primeFactors; int x = n; for (int i = 2; i * i <= n; i++) { if (x % i == 0) { primeFactors.push_back(i); while (x % i == 0) x /= i; } } if (x > 1) primeFactors.push_back(x); int goodNumber = 1; for (int i = 0; i < primeFactors.size(); i++) goodNumber = goodNumber * primeFactors[i]; return goodNumber; } int main(){ int n = 28; cout<<"The largest good Number in divisor of "<<n<<" is "<<findLargestGoodNumber(n); return 0; }
Example
The largest good Number in divisor of 28 is 14
- Related Questions & Answers
- Find the number of divisors of all numbers in the range [1, n] in C++
- Count the number of common divisors of the given strings in C++
- Find the Largest number with given number of digits and sum of digits in C++
- Find sum of divisors of all the divisors of a natural number in C++
- First triangular number whose number of divisors exceeds N in C++
- Find largest sum of digits in all divisors of n in C++
- How to find the n number of largest values in an R vector?
- Find the largest palindrome number made from the product of two n digit numbers in JavaScript
- Find the largest number in a Java array.
- Find the largest number with n set and m unset bits in C++
- Find the largest number that can be formed with the given digits in C++
- Largest N digit number divisible by given three numbers in C++
- Program to find out the sum of the number of divisor of the divisors in Python
- Find number from its divisors in C++
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors in C++
Advertisements | https://www.tutorialspoint.com/find-the-largest-good-number-in-the-divisors-of-given-number-n-in-cplusplus | CC-MAIN-2022-33 | en | refinedweb |
The BootLoader.In an AVR microcontroller writing a Boot-Loader code is comparatively easy, since any code which is written to the BLS section of the flash memory can have complete access to the hardware of the microcontroller. The flash memory of the AVR microcontroller is divided into two sections; an Application flash section and a Boot-Loader section (BLS).
Any code which executes from the BLS can use Self Programming Mode (SPM). Using the SPM feature a code from the BLS section can read or write the entire flash memory including the BLS section where the code is running from. This feature can be used to load any application code binary to the flash memory and let it execute. The required initialization of the controller peripherals like USART, port bits etc. and the initialization of the external devices like LCD etc. can be done from the BLS itself before loading the application code. microcontroller used in this project is ATMEGA16, and the programmer used is USBASP. The AVR studio 4 is used as the IDE and the burner software used is AVR-BURNO-MAT.
The AVR flash memory is divided into two sections namely the application section and the Boot-Loader section (BLS). In case of the ATMEGA16 it has 16 KB of flash memory of which the 15KB is application section and the remaining 1KB is BLS. The memory architecture of the ATMEGA16 is shown in the following figure;
The code for both the BLS and application section can be written as normally does and there is no much difference. The only thing to be careful about is the size of the code binary. It should not be more than 1KB, otherwise it won’t be able to code programmed into the BLS. The project on AVR BLS coding discusses how to program a simple code into the BLS of ATMEGA16 microcontroller with the help of AVR studio as IDE, USBasp as the programmer and AVR-Burnomat as the burner software.
In this particular project the Boot-Loader is coded to perform UART initialization along with a simple LED pin initialization and also an external hardware initialization of the 4 bit LCD. Hence the application codes does not require those codes in them, still they works because before executing the application codes the initialization functions will be executed by the Boot-Loader.
The BLS code has the initialization functions which should not be there in the application codes. The initialization functions used in the Boot-Loader code for this project are given below;
Any application code can directly use the following function calls to access the USART, LCD and LED without their initializing functions anywhere in their code.
The hardware initialization before executing the application code is explained in detail in a projecton Initializing hardware from AVR BLS.
The major function of the Boot-Loader is load a code binary form storage medium or which can be received through the external communication with other devices to the flash memory. The SPM feature available for the code executing from the BLS helps in loading an application code binary to the flash memory. The task of writing the BLS code with SPM has been made simple by the APIs available in the header file <avr/boot.h>. The following are the important APIs available in the header file which helps in the SPM.
Fig. 5: Important APIs in AVR
The steps required to do the SPM on the application flash memory is explained in a project on using SPM in AVR flash to flash programming.
In this particular project the Boot-Loader is coded in such a way that it will try to load any application code binary which has been loaded into the built-in internal EEPROM of the AVR microcontroller. The APIs available in the <avr/eeprom.h> is used to read the data bytes from the EEPROM and with the help of APIs from the <avr/boot.h> the data bytes are stored into a temporary buffer and then flashed into the application section of the flash memory.
The API provided by the <avr/eeprom.h> to read the data bytes from the built-in EEPROM of the AVR microcontroller is;
uint8_t eeprom_read_byte (const uint8_t *p)
Fig. 6: API <avr/eeprom.h> to read data bytes from in-built EEPROM of AVR microcontroller
With the help of the above discussed APIs from both <avr/boot.h> and <avr/eeprom.h> one can use the SPM feature of the AVR microcontroller to write a Boot-Loader code which can load an application which has been programmed into the built-in EEPROM of the AVR microcontroller. For that one should follow the steps mentioned below which are explained in a project on using SPM in AVR EEPROM to flash programming.
{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}· {C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}Step: 1 Erase the flash page which is about to write into
{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}· {C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}Step: 2 Store the code binary which are read from the EEPROM into a temporary buffer before write into a flash page
{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}· {C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}{C}Step: 3 Program the filled temporary buffer into the already erased flash page
After performing the above three steps the Boot-Loader can then make a jump using the statement
asm ( “jmp 0x0000” );
to the application code section and let the newly programmed application to execute.
Flash the Boot-Loader code to the BLS first any small sized application code to the EEPROM memory using the steps explained in the previous project on LED blinking from BLS of AVR. Once the EEPROM programming has completed and when the controller resets the Boot-Loader will start executing. Once can observe that it is performing the initialization functions and is loading the application from the built-in EEPROM.
Project Source Code
###
#define _LCD_H #ifndef F_CPU #define F_CPU 8000000 #endif #include<avr/io.h> #include<util/delay.h> #include<inttypes.h> #define rs PA0 #define rw PA1 #define en PA2 void lcd_init(); void dis_cmd(char); void dis_data(char); void lcdcmd(char); void lcddata(char); void lcd_clear(void); void lcd_2nd_line(void); void lcd_1st_line(void); void lcd_string(const char *data); void lcd_string(const char *data) { for(;*data;data++) dis_data (*data); } void lcd_clear(void) { dis_cmd(0x01); _delay_ms(10); } void lcd_2nd_line(void) { dis_cmd(0xC0); _delay_ms(1); } void lcd_1st_line(void) { dis_cmd(0x80); _delay_ms(1); } void lcd_init() // fuction for intialize { DDRA=0xFF; dis_cmd(0x02); // to initialize LCD in 4-bit mode. dis_cmd(0x28); //to initialize LCD in 2 lines, 5X7 dots and 4bit mode. dis_cmd(0x0C); dis_cmd(0x06); dis_cmd(0x80); dis_cmd(0x01); _delay_ms(10); } void dis_cmd(char cmd_value) { char cmd_value1; cmd_value1 = cmd_value & 0xF0; //mask lower nibble because PA4-PA7 pins are used. lcdcmd(cmd_value1); // send to LCD cmd_value1 = ((cmd_value<<4) & 0xF0); //shift 4-bit and mask lcdcmd(cmd_value1); // send to LCD } void dis_data(char data_value) { char data_value1; data_value1=data_value&0xF0; lcddata(data_value1); data_value1=((data_value<<4)&0xF0); lcddata(data_value1); } void lcdcmd(char cmdout) { PORTA=cmdout; PORTA&=~(1<<rs); PORTA&=~(1<<rw); PORTA|=(1<<en); _delay_ms(1); PORTA&=~(1<<en); } void lcddata(char dataout) { PORTA=dataout; PORTA|=(1<<rs); PORTA&=~(1<<rw); PORTA|=(1<<en); _delay_ms(1); PORTA&=~(1<<en); } #endif
###
Project Source Code
###
#define rs PA0 #define rw PA1 #define en PA2 #include <avr/io.h> #include <util/delay.h> void dis_data(char data_value); void usart_putch(unsigned char send); unsigned int usart_getch(); int main ( void ) { int i; unsigned int c; //——– led test ———–// DDRD |= 0x80; for ( i =0; i < 5; i ++ ) { PORTD = ~PORTD; _delay_ms ( 500 ); } //——– led test ———–// //—– usart + lcd test ——-// while ( 1 ) { c = usart_getch(); usart_putch( ( unsigned char ) c ); dis_data( ( char ) c ); } //—– usart + lcd test ——-// } void dis_data(char data_value) { char data_value1; data_value1=data_value&0xF0; PORTA=data_value1; PORTA|=(1<<rs); PORTA&=~(1<<rw); PORTA|=(1<<en); _delay_ms(1); PORTA&=~(1<<en); data_value1=((data_value<<4)&0xF0); PORTA=data_value1; PORTA|=(1<<rs); PORTA&=~(1<<rw); PORTA|=(1<<en); _delay_ms(1); PORTA&=~(1<<en); } void usart_putch(unsigned char send) { while ((UCSRA & (1 << UDRE)) == 0); // Do nothing until UDR is ready.. // for more data to be written to it UDR = send; // Send the byte } unsigned int usart_getch() { while ((UCSRA & (1 << RXC)) == 0); // Do nothing until data have been received and is ready to be read from UDR return(UDR); // return the byte }
###
Circuit Diagrams
Project Components
Project Video
For more detail: How To Write a Simple Bootloader For AVR In C language | https://atmega32-avr.com/how-to-write-a-simple-bootloader-for-avr-in-c-language/ | CC-MAIN-2022-33 | en | refinedweb |
Contents
- 1 Introduction
- 2 Matplotlib Histogram Tutorial
- 3 Conclusion
Introduction
Importing Matplotlib Library
Before beginning with this matplotlib histogram tutorial, we’ll need Matplotlib Library. So let’s import Matplotlib and other important libraries relevant to our examples.
import matplotlib.pyplot as plt import numpy as np import pandas as pd
Matplotlib Histogram Tutorial
Histogram is a way through which one can visualize the distribution of numerical data.
Let us take a look at syntax of matplotlib histogram function below.
Syntax of Histogram
matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, *, data=None, **kwargs)
- x : (n,) array or sequence of (n,) arrays – This parameter holds the input values in the form of array or sequence of arrays.
- bins : int or sequence or str, default: 10 – The bins parameter accepts either integer values or sequence values. When integer values are provided, then equal-width bins are present in the given range but if the other option is provided, bins may be unequally spaced.
- range : tupe or None, default: None – The lower and upper range of bins is passed in this parameter.
- density : bool, default: False – If passed – This parameter determines the impact of the input values. Each value will have a weight associated with it.
- cumulative: bool or -1, default: False – If True, it shows the individual count of each bin along with the counts of bins for previous values. The last bin shows the result as 1.
- bottom: array-like, scalar, or None, default: None – This parameter sets the location of the bottom of each bin.
- histtype : {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}, default: ‘bar’ – A brief information about each value is provided below – ‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side.‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other. ‘step’ generates a lineplot that is by default unfilled. ‘stepfilled’ generates a lineplot that is by default filled.
- align : {‘left’, ‘mid’, ‘right’}, default: ‘mid’ – This helps in setting the position of the plot
- orientation : {‘vertical’, ‘horizontal’}, default: ‘vertical’ – Through this parameter, histogram is made vertically or horizontally.
- rwidth : float or None, default: None – It helps in setting the relative width of bins.
- color : color or array-like of colors or None, default: None – Color or sequence of colors, one per dataset. Default (None) uses the standard line color sequence.
- label : str or None, default: None – This helps in rendering the labels.
- stacked : bool, default: False – If True, multiple data are stacked on top of each other If False multiple data are arranged side by side if histtype is ‘bar’ or on top of each other if histtype is ‘step’
The result returned contains histogram with array or list of arrays depicting the bins and values of the bins.
Example 1: Simple Matplotlib Histogram
This is the first example of matplotlib histogram in which we generate random data by using numpy random function.
To depict the data distribution, we have passed mean and standard deviation values to variables for plotting them.
The histogram function is provided the count of total values, number of bins, and patches to be created. Other parameters like density, facecolor, and alpha help in changing the appearance of the histogram.
The hist() function uses the default value for histtype parameter in this case.
With the help of xlim and ylim functions, we are able to set the minimum and maximum values for both x-axis and y-axis.
# Fixing random state for reproducibility np.random.seed(19680801) mu, sigma = 100, 20 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, density=True, facecolor='pink', alpha=0.75) plt.xlabel('Values') plt.ylabel('Probability Distribution') plt.title('Histogram showing Data Distribution') plt.text(60, .025, r'$\mu=100,\ \sigma=20$') plt.xlim(40, 160) plt.ylim(0, 0.03) plt.grid(True) plt.show()
Important Note
For large numbers of bins (>1000), ‘step’ and ‘stepfilled’ can be significantly faster than ‘bar’ and ‘barstacked’.
In this example of the matplotlib histogram, we will be customizing the color of the histogram for showing the data distribution. This will help in visualizing the different values across the range of data.
Once the dataset and distribution is created, we create the histogram. For this plot, the subplots function will be used. To make this plot more appealing, axes spines and x,y ticks are removed. After this padding and gridlines are added.
Lastly, the hist() function is called for plotting the histogram. The color is set over the histogram by dividing it in fractions. Through this method, different sections of the histogram are colored different colors.
With the help of the “for” loop, we can easily visualize the histogram with a range of colors over a range of data. As you can see the color darkens at the extreme ends and in the middle there is a lighter shade of color.
In the case of a histogram, the facecolor keyword helps in setting the color of the histogram.
from matplotlib import colors from matplotlib.ticker import PercentFormatter # Creating dataset np.random.seed(23685752) N_points = 100000 n_bins = 30 # Creating distribution x = np.random.randn(N_points) y = .8 ** x + np.random.randn(100000) + 35 legend = ['distribution'] # Creating histogram fig, axs = plt.subplots(1, 1, figsize =(10, 7), tight_layout = True) # Remove axes spines for s in ['top', 'bottom', 'left', 'right']: axs.spines[s].set_visible(False) # Remove x, y ticks axs.xaxis.set_ticks_position('none') axs.yaxis.set_ticks_position('none') # Add padding between axes and labels axs.xaxis.set_tick_params(pad = 5) axs.yaxis.set_tick_params(pad = 10) # Add x, y gridlines axs.grid(b = True, color ='grey', linestyle ='-.', linewidth = 0.5, alpha = 0.6) # Creating histogram N, bins, patches = axs.hist(x, bins = n_bins) # Setting color fracs = ((N**(1 / 5)) / N.max()) norm = colors.Normalize(fracs.min(), fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = plt.cm.cool_r(norm(thisfrac)) thispatch.set_facecolor(color) # Adding extra features plt.xlabel("X-axis") plt.ylabel("y-axis") plt.legend(legend) plt.title('Customized histogram') # Show plot plt.show()
Example 3: Matplotlib Histogram with Bars
In the 3rd example of this matplotlib histogram tutorial, we’ll now see how to incorporate bars into a histogram. For this, we simply have to generate random data by using numpy’s random() function. Then, when we call the hist() function of the matplotlib library, we can pass the value bar in the histtype parameter. We also have the option of creating a stacked bar chart in the histogram by passing barstacked value in above mentioned parameter.
The size of the legend can also be increased or decreased by using the legend function.
np.random.seed(10**9) n_bins = 18 x = np.random.randn(10000, 3) colors = ['red', 'blue', 'lime'] plt.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors) plt.legend(prop ={'size': 10}) plt.show()
Example 4: Matplotlib Histogram with KDE Plot
This histogram example will showcase how one can combine histogram and kernel density estimation or KDE plot in a single visualization. For this example, we will assign random values to means and standard deviations. Then a dataframe is created with means passed to ‘loc’ parameter and standard deviations passed to ‘scale’ parameter.
This helps in generating random data. We also have a look at the aggregate values i.e. minimum, maximum, mean, and standard deviation of the two columns of values in this random data.
means = 25, 70 stdevs = 5, 10 dist = pd.DataFrame(np.random.normal(loc=means, scale=stdevs, size=(10000, 2)),columns=['a', 'b']) dist.agg(['min', 'max', 'mean', 'std']).round(decimals=2)
Out[5]:
With the help of subplots function, we can plot the KDE and histogram together. The output shown below depicts the probability distribution of data where the kernel density estimation plot also helps in knowing the probability of data in a given space.
fig, ax = plt.subplots() dist.plot.kde(ax=ax, legend=True, title='Histogram: A vs. B') dist.plot.hist(density=True, ax=ax) ax.set_ylabel('Probability') ax.grid(axis='y')
Example 5: Probability Histogram with multiple values
For the next two examples, we will be using a dataset in which different pearls are rated on different attributes. So with the help of pandas, we first load the csv file into a dataframe. The next step is to assign data into different variables for creating three different groups on the basis of pearl ratings. To obtain apt visualization we have to normalize the data.
At last, we call the hist() function thrice to render the histograms for the three quality ratings of pearl. The gca() function or get the current axis function helps in the creation of appropriate axes if there is no axis for a particular figure.
import pandas as pd df = pd.read_csv("pearls.csv") df.head()
x1 = df.loc[df.Rating=='Ideal', 'Depth'] x2 = df.loc[df.Rating=='Fair', 'Depth'] x3 = df.loc[df.Rating=='Good', 'Depth'] # Normalize kwargs = dict(alpha=0.5, bins=50, density=True, stacked=True) # Plot plt.hist(x1, **kwargs, color='g', label='Ideal') plt.hist(x2, **kwargs, color='b', label='Fair') plt.hist(x3, **kwargs, color='r', label='Good') plt.gca().set(title='Probability Histogram of Pearl Depths', ylabel='Probability') plt.xlim(50,75) plt.legend();
Example 6: Histogram for visualizing categories
In this last example of our matplotlib tutorial on histogram, we are plotting histogram for different categories of a given dataset. This kind of histogram is useful in comparison studies. Here in this case, 5 different histograms are created for 5 different quality ratings of the pearls.
Again to visualize multiple plots, we use subplots() function. After specifying the color for the 5 different plots, we will be using for loop along with enumerate function to plot the 5 different histograms on the basis of different Ratings of pearls.
We use suptitle function to give the plot a title and we also use set_xlim function for providing the minimum and maximum limits for x-axis.
The reason behind using tight_layout function is that it helps in displaying the subplots in the figure cleanly by managing the parameters on its own.
# Plot fig, axes = plt.subplots(1, 5, figsize=(10,2.5), dpi=100, sharex=True, sharey=True) colors = ['tab:blue', 'tab:red', 'tab:green', 'tab:pink', 'tab:purple'] for i, (ax, Rating) in enumerate(zip(axes.flatten(), df.Rating.unique())): x = df.loc[df.Rating==Rating, 'Depth'] ax.hist(x, alpha=0.5, bins=55, density=True, stacked=True, label=str(Rating), color=colors[i]) ax.set_title(Rating) plt.suptitle('Probability Histogram of Different Pearl Ratings', y=1.05, size=16) ax.set_xlim(50, 70); ax.set_ylim(0, 1); plt.tight_layout();
Conclusion
It’s time to end this matplotlib histogram tutorial in which we built various kinds of interesting histograms. We looked at how colors can be customized for histograms, how we can visualize different histograms for multiple categories in a dataset. And we also talked about the minute details that are involved in building a complete histogram with all the necessary information.
Reference – Matplotlib Documentation | https://machinelearningknowledge.ai/matplotlib-histogram-complete-tutorial-for-beginners/ | CC-MAIN-2022-33 | en | refinedweb |
This section provides general guidelines and recommendations for making choices about security in your namespace. This section contains the following topics:
Because NIS+ provides security that NIS did not, NIS+ security requires more administrative work. It may also require more work from users who are not used to performing chkey, keylogin, or keylogout procedures. Furthermore, the protection provided by NIS+ is not entirely secure. Given enough computing power and the right knowledge, the Diffie-Hellman public-key cryptography system can be broken. In addition, the secret key stored with the key server process is not automatically removed when a credentialed nonroot user logs out unless that user logs out with keylogout. (See the keylogout command description for more information.) The root user's key, created by keylogin -r and stored in /etc/.rootkey, remains until the .rootkey file is explicitly removed. The superuser cannot use keylogout.
NIS+ security benefits users because it improves the reliability of the information they obtain from NIS+, and it protects their information from unauthorized access. However, NIS+ security requires users to learn about security and requires them to perform some. When the NIS+ user password and credential are changed with the passwd command, the credential information is automatically changed for the user.
If your site allows users to maintain passwords in their local /etc/passwd files in addition to their Secure RPC passwords, and if these passwords are different from the Secure RPC passwords, then users must run keylogin each time they run login. For more information, see Administering Passwords.
Because AIX 4.3.3 includes the DES encryption mechanism for authentication, administrators who need secure operation do not need to purchase a separate encryption package. However, administrators must train users how and when to use the passwd command. log in remotely:
NIS+ provides two types of credential: local and DES. and the type of credential.
NIS+ principals can be users or the superuser identity on the client workstation, as shown in the following figure.
Figure 3-4. NIS+ Principals.. This illustration shows a user logged on to a client machine has User credentials. A user logged on as root to a client machine has Workstation credentials.
When you determine the credentials you need to create, make sure you know which type of principal the credential is for. For instance, when you set up an NIS+ client with the nisclient script, you will create credentials for both the workstation and for the corresponding user. All users on that workstation must run the nisclient script to be configured as NIS+ users. Unless credentials for the user are also created, the user would only have the access rights granted to the nobody class. If you do not give some access rights to the nobody class, the namespace will not be available to users.
Note: The nisclient script fails unless the user has existing entries in the passwd and cred tables.
NIS+ is designed to be run at security level 2, which is the default. Security levels 0 and 1 are provided only for the purpose of testing and debugging. Do not run an operational network with real users at any level other than level 2. See Administering NIS+ Directories for more information on the NIS+ security levels.
Password-aging is a mechanism that you can use to force users to periodically change their passwords. Password-aging allows you to:, and Administering Passwords.
NIS+ uses groups as a means to provide NIS+ access rights to several NIS+ principals at one time; it is used only for NIS+ authorization.
An NIS+ group is one of the four authorization classes on which access rights are based. The four classes are:
The default name of the group created by NIS+ scripts for such purposes is the admin group. You can create other groups with different names and assign different groups to different NIS+ objects. This can be done as a default parameter by setting the environment variable NIS_GROUPS to whatever group you prefer.
Member users of an object's group usually have special privileges to that object, such as permission to make certain changes to the object. For example, you could add several junior administrators to, select the access rights that are required in the namespace. To make that task easier, first decide how many administrative groups you will need. Using separate groups is useful when you want to assign them different rights. Usually, you create groups by domain. Each domain should have only one admin group.
After arranging your principals into groups, determine the kind of access rights granted by the objects in the namespace to those groups, as well as to the other classes of principal (nobody, owner, group, and world). Planning these assignments ahead of time will help you establish a coherent security policy.
As shown in the following table, NIS+
provides different default access rights for different namespace
objects.
You can use the default rights or assign your own. If you assign your own, consider how the objects in your namespace will be accessed. Keep in mind that the nobody class comprises all requests from NIS+ clients, whether authenticated or not. The world class comprises all authenticated requests from NIS+ clients. Therefore, if you do not want to provide namespace access to unauthenticated requests, do not assign any access rights to the nobody class; reserve them only for the world class. On the other hand, if you expect some clients--through applications, for instance--to make unauthenticated read requests, assign read rights to the nobody class. If you want to support NIS clients in NIS-compatibility mode, assign read rights to the nobody class.
Also consider the rights each type of namespace object will assign may informational objects. Access to NIS+ tables is required by all NIS+ principals and applications running on behalf of those principals. Therefore, their access requirements are somewhat different.
The following table.
Note: NIS-compatible domains give the nobody class read rights to the passwd table at the table level.
As you can see in the previous table, read access is provided by default the previous table.
Table owners and entry owners are rarely and not necessarily the same NIS+ principals. Thus, table-level read access for the owner does not imply read access for the owner of any particular entry.
For a more complete explanation and discussion of table-, entry-, and column level-security, see Chapter 7, Security. | http://ps-2.kev009.com/wisclibrary/aix51/usr/share/man/info/en_US/a_doc_lib/aixbman/nisplus/trans_secur.htm | CC-MAIN-2022-33 | en | refinedweb |
current position:Home>Webengine loading local html is invalid, and html is the dynamic address generated by JS, which can be solved
Webengine loading local html is invalid, and html is the dynamic address generated by JS, which can be solved
2022-04-29 12:37:23【CSDN Q & A】
The phenomenon and background of the problem
Realize the demand : Will local html File by webengine Output on software ( Software means pyqt5-designer Designed pages , Just learned don't know how to say don't spray )
platform MacOS and win Both platforms have tried , direct load(‘svgaPage.html’) None of the local files are valid
I dare not say the whole network , At least it's stuck 3 God , No less than 1000 A solution , Still not solved ( There may be a solution, but I don't understand , So it's troublesome to post specially )
After testing, the local html Open it with a browser , Copy the address in the browser to be effective , Can successfully output ; Prove that the source code is OK ; But the actual situation is that the address is dynamic after packaging , It's the tail ?html=1x3jk Such , Randomly generated ; So I can't use it correctly .
My guess is webengine There is no call JS, But for beginners, one , I'm not sure , I've been searching like a headless fly for a long time .
Problem related code , Do not paste screenshots
structure : All in the root directory
【svgaPage.html】
<html> <script src="[email protected]/build/svga.min.js"></script> <script src="//s1.yy.com/ued_web_static/lib/jszip/3.1.4/??jszip.min.js,jszip-utils.min.js" charset="utf-8"></script> <script src="./SVGAPlayer/build/svga.min.js">import SVGA from 'svgaplayerweb'</script> <div id="demoCanvas" style="width: 100%;height: 100%;background-color: chartreuse"></div> <script> var player = new SVGA.Player('#demoCanvas'); var parser = new SVGA.Parser('#demoCanvas'); // If you need support IE6+, Then you must pass the same selector to Parser. parser.load('./fansCrad/fans.svga', function(videoItem) { // Here we begin to control player.loops = 1; // cycles player.clearsAfterStop = true; // Whether to clear the content after playing player.setVideoItem(videoItem); // Need to get load Return parameters to take effect ( I don't know what it means for the moment ) player.startAnimation(); // Start playing // player.pauseAnimation(); Pause play // player.stopAnimation(); Stop playing // player.onFrame(); What frame is currently playing , Adjust according to business }) </script> </html>
【main.py】
def showSvga(self): #【 This link goes directly into QUrl If so, it will take effect , But it's actually a dynamic address , I can't just write it in like this 】 self.videoEngine.load(QUrl(r"./fansCrad/fans.svga")) self.horizontalLayout.addWidget(self.videoEngine) # Put code components into layout Layers self.videoEngine.show() # This seems to be OK
Operation results and error reporting contents
layout The layer changes from transparent to white , The description should be in the past ; But the web content doesn't show at all ; No error content
My solution ideas and tried methods
Because directly speaking, the browser address is copied to url It can be opened , So basically, it can be said that there is no problem with the code ; It should be on this dynamic address .
What I want to achieve
I learned that one way seems to be called reverse compilation ? Does this mean to js The address of content generation is reversed to form a code state that can be used for QURL? I don't understand much .
The solutions I can think of at present are 2 individual ;
1、 Use the server , So you have the address ( But it's really unnecessary ; Just a small program ; And this is not the root of the problem ; There is still no local implementation )
2、 stay main Write directly in the code js?? I don't know if this can be achieved ; After reading a lot of fragmented code, it is incomplete ; So it's hard to understand .
If a friend can help , I hope it can be as complete and popular as possible ( Manual than heart ); by the way , I use it python3 Page is qt-designer The design of | https://en.qdmana.com/2022/112/202204291237171555.html | CC-MAIN-2022-33 | en | refinedweb |
@Generated(value="OracleSDKGenerator", comments="API Version: 20160918") public final class TagNamespace extends ExplicitlySetBmcModel
A managed container for defined tags. A tag namespace is unique in a tenancy. For more information, see Managing Tags and Tag Namespaces.
Warning:** Oracle recommends that you avoid using any confidential information when you supply string values
using the API.
Note: Objects should always be created or deserialized using the
TagNamespace.Builder. This model distinguishes fields
that are
null because they are unset from fields that are explicitly set to
null. This is done in
the setter methods of the
TagNamespace","name","description","freeformTags","definedTags","isRetired","lifecycleState","timeCreated","locks"}) public TagNamespace(String id, String compartmentId, String name, String description, Map<String,String> freeformTags, Map<String,Map<String,Object>> definedTags, Boolean isRetired, TagNamespace.LifecycleState lifecycleState, Date timeCreated, List<ResourceLock> locks)
public static TagNamespace.Builder builder()
Create a new builder.
public TagNamespace. Boolean getIsRetired()
Whether the tag namespace is retired. tagNamespace was created, in the format defined by RFC3339.
Example:
2016-08-25T21:10:29.600Z
public List<ResourceLock> getLocks()
Locks associated with this resource. | https://docs.oracle.com/en-us/iaas/tools/java/2.44.0/com/oracle/bmc/identity/model/TagNamespace.html | CC-MAIN-2022-40 | en | refinedweb |
#include <rte_pipeline.h>
Parameters for pipeline output port creation. The action handlers have to
be either both enabled or both disabled (by setting them to NULL). When enabled, the pipeline selects between them at different moments, based on the number of packets that have to be sent to the same output port.
Opaque parameter to be passed to the action handler when invoked
Opaque parameter to be passed to create operation when invoked
Callback function executing the user actions on single input
packet
Callback function executing the user actions on bust of input
packets
Output port operations (specific to each table type) | https://doc.dpdk.org/api-2.0/structrte__pipeline__port__out__params.html | CC-MAIN-2022-40 | en | refinedweb |
Qt Device Utilities WiFi Tutorial
Importing NetworkSettings
Import the NetworkSettings module as follows:
import QtDeviceUtilities.NetworkSettings 1.0
Filtering WiFi Networks
In order to connect to WiFi instead of wired networks, set NetworkSettingsManager in a WiFi filtering mode:
Component.onCompleted: NetworkSettingsManager.services.type = NetworkSettingsType.Wifi;
After you have set the filter, NetworkSettingsManager.services contains the NetworkService objects services representing WiFi networks.
Connecting to WiFi
In order to connect to Wifi, invoke the connectService method on NetworkService.
If no passphrase is needed, connectService connects to a WiFi network and changes the connected property of the selected service.
If a passphrase is needed, NetworkSettingsManager.userAgent emits the showUserCredentialsInput signal. Before a WiFi network is connected, you must provide the passphrase via NetworkSettingsManager.userAgent.setPassPhrase.
To implement the passphrase handling, you must set a signal handler as follows:
Connections { target: NetworkSettingsManager.userAgent onShowUserCredentialsInput : { // obtain the passphrase and set it } onError: { // handle errors } }
Implementing User Interface
When you are implementing a user interface for handling WiFi connections, remember that NetworkSettingsManager.services is designed to be used as a model. The Settings UI implementation uses it directly to display a list of available WiFi networks.
Handling WiFi connections and passphrases for list selections should be straightforward as described in Filtering WiFi Networks and Connecting to WiFi.. | https://doc.qt.io/QtDeviceUtilities/qtdeviceutilities-wifitutorial.html | CC-MAIN-2022-40 | en | refinedweb |
Each Answer to this Q is separated by one/two green lines.
There is a JSON like this:
{ "P1": "ss", "Id": 1234, "P2": { "P1": "cccc" }, "P3": [ { "P1": "aaa" } ] }
How can I find all
P1‘s value without it iterating all JSON?
P.S.:
P1 can be anywhere in the JSON.
If no method can do this, can you tell me how to iterate through the JSON?
As I said in my other answer, I don’t think there is a way of finding all values associated with the
"P1" key without iterating over the whole structure. However I’ve come up with even better way to do that which came to me while looking at @Mike Brennan’s answer to another JSON-related question How to get string objects instead of Unicode from JSON?
The basic idea is to use the
object_hook parameter that
json.loads() accepts just to watch what is being decoded and check for the sought-after value.
Note: This will only work if the representation is of a JSON
object (i.e. something enclosed in curly braces
{}), as in your sample.
from __future__ import print_function import json def find_values(id, json_repr): results = [] def _decode_dict(a_dict): try: results.append(a_dict[id]) except KeyError: pass return a_dict json.loads(json_repr, object_hook=_decode_dict) # Return value ignored. return results json_repr="{"P1": "ss", "Id": 1234, "P2": {"P1": "cccc"}, "P3": [{"P1": "aaa"}]}" print(find_values('P1', json_repr))
(Python 3) output:
['cccc', 'aaa', 'ss']
I had the same issue just the other day. I wound up just searching through the entire object and accounted for both lists and dicts. The following snippets allows you to search for the first occurrence of a multiple keys.
import json def deep_search(needles, haystack): found = {} if type(needles) != type([]): needles = [needles] if type(haystack) == type(dict()): for needle in needles: if needle in haystack.keys(): found[needle] = haystack[needle] elif len(haystack.keys()) > 0: for key in haystack.keys(): result = deep_search(needle, haystack[key]) if result: for k, v in result.items(): found[k] = v elif type(haystack) == type([]): for node in haystack: result = deep_search(needles, node) if result: for k, v in result.items(): found[k] = v return found deep_search(["P1", "P3"], json.loads(json_string))
It returns a dict with the keys being the keys searched for. Haystack is expected to be a Python object already, so you have to do json.loads before passing it to deep_search.
Any comments for optimization are welcomed!
My approach to this problem would be different.
As JSON doesn’t allow depth first search, so convert the json to a Python Object, feed it to an XML decoder and then extract the Node you are intending to search
from xml.dom.minidom import parseString import json def bar(somejson, key): def val(node): # Searches for the next Element Node containing Value e = node.nextSibling while e and e.nodeType != e.ELEMENT_NODE: e = e.nextSibling return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e else None) # parse the JSON as XML foo_dom = parseString(xmlrpclib.dumps((json.loads(somejson),))) # and then search all the name tags which are P1's # and use the val user function to get the value return [val(node) for node in foo_dom.getElementsByTagName('name') if node.firstChild.nodeValue in key] bar(foo, 'P1') [u'cccc', u'aaa', u'ss'] bar(foo, ('P1','P2')) [u'cccc', u'cccc', u'aaa', u'ss']
Using
json to convert the json to Python objects and then going through recursively works best. This example does include going through lists.
import json def get_all(myjson, key): if type(myjson) == str: myjson = json.loads(myjson) if type(myjson) is dict: for jsonkey in myjson: if type(myjson[jsonkey]) in (list, dict): get_all(myjson[jsonkey], key) elif jsonkey == key: print myjson[jsonkey] elif type(myjson) is list: for item in myjson: if type(item) in (list, dict): get_all(item, key)
Converting the JSON to Python and recursively searching is by far the easiest:
def findall(v, k): if type(v) == type({}): for k1 in v: if k1 == k: print v[k1] findall(v[k1], k) findall(json.loads(a), 'P1')
(where a is the string)
The example code ignores arrays. Adding that is left as an exercise.
Bearing in mind that json is simply a string, using regular expressions with look-ahead and look-behind can accomplish this task very quickly.
Typically, the json would have been extracted from a request to external api, so code to show how that would work has been included but commented out.
import re #import requests #import json #r1 = requests.get( ... url to some api ...) #JSON = str(json.loads(r1.text)) JSON = """ { "P1": "ss", "Id": 1234, "P2": { "P1": "cccc" }, "P3": [ { "P1": "aaa" } ] } """ rex1 = re.compile('(?<=\"P1\": \")[a-zA-Z_\- ]+(?=\")') rex2 = rex1.findall(JSON) print(rex2) #['ss', 'cccc', 'aaa']
I don’t think there’s any way of finding all values associated with P1 without iterating over the whole structure. Here’s a recursive way to do it that first deserializes the JSON object into an equivalent Python object. To simplify things most of the work is done via a recursive private nested function.
import json try: STRING_TYPE = basestring except NameError: STRING_TYPE = str # Python 3 def find_values(id, obj): results = [] def _find_values(id, obj): try: for key, value in obj.items(): # dict? if key == id: results.append(value) elif not isinstance(value, STRING_TYPE): _find_values(id, value) except AttributeError: pass try: for item in obj: # iterable? if not isinstance(item, STRING_TYPE): _find_values(id, item) except TypeError: pass if not isinstance(obj, STRING_TYPE): _find_values(id, obj) return results json_repr="{"P1": "ss", "Id": 1234, "P2": {"P1": "cccc"}, "P3": [{"P1": "aaa"}]}" obj = json.loads(json_repr) print(find_values('P1', obj))
You could also use a generator to search the object after json.load().
Code example from my answer here:
def item_generator(json_input, lookup_key): if isinstance(json_input, dict): for k, v in json_input.iteritems(): if k == lookup_key: yield v else: for child_val in item_generator(v, lookup_key): yield child_val elif isinstance(json_input, list): for item in json_input: for item_val in item_generator(item, lookup_key): yield item_val
| https://techstalking.com/programming/python/how-to-find-a-particular-json-value-by-key/ | CC-MAIN-2022-40 | en | refinedweb |
Hello,
i want to control the relay expansion board with a self written python script. Therefore i followed this instructions:
Consequently i installed the pyOnionI2C module and the "Omega Expansion" folder including the OnionI2C.so file are placed in the package path.
But when i try to run a python script including this line:
from OmegaExpansion import onionI2C
I get the following error message:
Traceback (most recent call last):
File "testi2c.py", line 1 in <module>
from OmegaExpansion import onionI2C
ImportError: Error relocating /usr/lib/python2.7/OmegaExpansion/onionI2C.so: i2c_writeBufferRaw: symbol not found
The firmware is up to date and I am using the omega 2.
Can anybody help me to handle this error or what modules do you use to communicate with I2C devicese?
Thank you,
Max | https://community.onion.io/user/zwiebelmax | CC-MAIN-2022-40 | en | refinedweb |
commit aa50f45332f17e8d6308b996d890d3e83748a1a5
Author: Dario Faggioli <dfaggioli@xxxxxxxx>
AuthorDate: Fri Mar 12 17:02:47 2021 +0100
Commit: Jan Beulich <jbeulich@xxxxxxxx>
CommitDate: Fri Mar 12 17:02:47 2021 +0100
xen: fix for_each_cpu when NR_CPUS=1
When running an hypervisor build with NR_CPUS=1 for_each_cpu does not
take into account whether the bit of the CPU is set or not in the
provided mask.
This means that whatever we have in the bodies of these loops is always
done once, even if the mask was empty and it should never be done. This
is clearly a bug and was in fact causing an assert to trigger in credit2
code.
Removing the special casing of NR_CPUS == 1 makes things work again.
Reported-by: Roger Pau Monné <roger.pau@xxxxxxxxxx>
Signed-off-by: Dario Faggioli <dfaggioli@xxxxxxxx>
Reviewed-by: Jan Beulich <jbeulich@xxxxxxxx>
Release-Acked-by: Ian Jackson <iwj@xxxxxxxxxxxxxx>
---
xen/include/xen/cpumask.h | 5 -----
1 file changed, 5 deletions(-)
diff --git a/xen/include/xen/cpumask.h b/xen/include/xen/cpumask.h
index 256b60b106..e69589fc08 100644
--- a/xen/include/xen/cpumask.h
+++ b/xen/include/xen/cpumask.h
@@ -368,15 +368,10 @@ static inline void free_cpumask_var(cpumask_var_t mask)
#define FREE_CPUMASK_VAR(m) free_cpumask_var(m)
#endif
-#if NR_CPUS > 1
#define for_each_cpu(cpu, mask) \
for ((cpu) = cpumask_first(mask); \
(cpu) < nr_cpu_ids; \
(cpu) = cpumask_next(cpu, mask))
-#else /* NR_CPUS == 1 */
-#define for_each_cpu(cpu, mask) \
- for ((cpu) = 0; (cpu) < 1; (cpu)++, (void)(mask))
-#endif /* NR_CPUS */
/*
* The following particular system cpumasks and operations manage
--. | https://lists.xenproject.org/archives/html/xen-changelog/2021-03/msg00143.html | CC-MAIN-2022-40 | en | refinedweb |
table of contents
NAME¶
rtcSetDeviceMemoryMonitorFunction - registers a callback function to track memory consumption
SYNOPSIS¶
#include <embree3/rtcore.h> typedef bool (*RTCMemoryMonitorFunction)( void* userPtr, ssize_t bytes, bool post ); void rtcSetDeviceMemoryMonitorFunction( RTCDevice device, RTCMemoryMonitorFunction memoryMonitor, void* userPtr );
DESCRIPTION¶
Using the rtcSetDeviceMemoryMonitorFunction call, it is possible to register a callback function (memoryMonitor argument) with payload (userPtr argument) for a device (device argument), which is called whenever internal memory is allocated or deallocated by objects of that device. Using this memory monitor callback mechanism, the application can track the memory consumption of an Embree device, and optionally terminate API calls that consume too much memory.
Only a single callback function can be registered per device, and further invocations overwrite the previously set callback function. Passing NULL as function pointer disables the registered callback function.
Once registered, the Embree device will invoke the memory monitor callback function before or after it allocates or frees important memory blocks. The callback function gets passed the payload as specified at registration time (userPtr argument), the number of bytes allocated or deallocated (bytes argument), and whether the callback is invoked after the allocation or deallocation took place (post argument). The callback function might get called from multiple threads concurrently.
The application can track the current memory usage of the Embree device by atomically accumulating the bytes input parameter provided to the callback function. This parameter will be >0 for allocations and <0 for deallocations.
Embree will continue its operation normally when returning true from the callback function. If false is returned, Embree will cancel the current operation with the RTC_ERROR_OUT_OF_MEMORY error code. Issuing multiple cancel requests from different threads is allowed. Canceling will only happen when the callback was called for allocations (bytes > 0), otherwise the cancel request will be ignored.
If a callback to cancel was invoked before the allocation happens (post == false), then the bytes parameter should not be accumulated, as the allocation will never happen. If the callback to cancel was invoked after the allocation happened (post == true), then the bytes parameter should be accumulated, as the allocation properly happened and a deallocation will later free that data block.
EXIT STATUS¶
On failure an error code is set that can be queried using rtcGetDeviceError.
SEE ALSO¶
[rtcNewDevice] | https://manpages.debian.org/bullseye/libembree-dev/rtcSetDeviceMemoryMonitorFunction.3.en.html | CC-MAIN-2022-40 | en | refinedweb |
How to Make Your Code More Readable
When I was in high school, I had a tendency to procrastinate when it came to assignments and, well, pretty much everything in life. I think that this is sort of a staple of the teenage condition. As a result, I’d often stay up late writing some paper the night before it was due and turn it in.
Working my way through life, I became less of a procrastinator and started to complete tasks on or ahead of schedule and without heroic all-night efforts at the 11th hour. This gave rise to a situation in which I’d frequently have something finished but not turned in for days or even weeks. And I discovered an interesting consequence of this situation–re-reading a paper or presentation with some time had elapsed allowed me to read the paper almost as if someone else had written it. To put it a more computer-science-y way, it nudged me off of the happy path of thinking “of course all of this phrasing makes sense exactly as is, or I wouldn’t have written it.”
Of late, I’ve been steadily working two or three projects and dividing my time up on a per-day basis to still allow myself to get in “the flow.” That is, I spend Monday on project A, Tuesday on project B, Wednesday back on A, and Thursday on C, for instance. The actual number of days and motivation for switching varies, but you get the idea. And like my improved work ethic in school as I grew up, I’ve noticed an interesting consequence: more readable code.
What seems to happen is that I get into a sweet spot between unconscious familiarity and complete lack of insight with the code. Enough time has elapsed since I last looked at it that I don’t simply take it for granted and see without looking, but not enough time has elapsed that I have no idea what’s going on. To illustrate what I mean, consider the following gist (modified from actual code that I was writing for the sake of anonymizing):
public class SomeClass { private readonly List
_cusotomers = new List (); public void AddToQueue(CustomerModel cm) { if (cm.IsActive && !_cusotomers.Any(c => c.Name == cm.Name)) _cusotomers.Add(new Customer() { Name = cm.Name }); } }
As I write code these days, I rely increasingly on various refactorings during the course of TDD: extract method, extract local variable, add to new class, declare type, etc. In this case, during a refactor cycle, I had extracted the method “AddToQueue” from another method where the “CustomerModel” argument had been a very tightly scoped local variable, such as the “c” variable in the “Any()” call. The result is a method that’s nicely short in scope, but suffers from some naming and semantics that tend to hide a bit about what this method is actually doing. If I’m going to put my money where my mouth is in my various posts deriding comments, I need to do better when it comes to making code self-documenting.
What could be improved here? Well, for starters, the name of the method is a little misleading since the result isn’t always an add. Secondly, what is “cm”? And, if you’ll notice, there’s a typo in the “customers” field–not particularly important, but sloppy. In short, this could use a bit of tightening up–a bit of editing for readability, if you will. How about this:
public class SomeClass { private readonly List
_customers = new List (); public void AddCustomerForModelIfValid(CustomerModel modelOfCustomer) { if (IsModelValidForAdding(modelOfCustomer)) AddCustomerForModel(modelOfCustomer); } private bool IsModelValidForAdding(CustomerModel modelOfCustomer) { return modelOfCustomer.IsActive && !_customers.Any(c => c.Name == modelOfCustomer.Name); } private void AddCustomerForModel(CustomerModel modelOfCustomer) { var customerBasedOnModel = new Customer() { Name = modelOfCustomer.Name }; _customers.Add(customerBasedOnModel); } }
I don’t know about you, but I’d say the latter version is a lot clearer. In fact, I think it’s so clear with the naming of variables and methods that adding comments would just be awkward. While the first one wasn’t terrible (it’s hard to be too confusing with methods that short), it definitely left something to be desired in the “self-documenting” category. The latter, I’d say, gets there.
The “sweet spot” that I mentioned earlier is the best time to make that kind of thing happen. It’s a little cumbersome in the middle of a refactoring to stop and say, “okay, let’s focus on naming and spelling.” That’s sure to interrupt your flow. But let that code sit for, say, four to seven days, and then give it another look. If you find yourself mumbling things like “what’s cm… oh, that’s right,” then you can be pretty sure others will mumble that as well, but without the “that’s right.” Don’t let that moment slip away–it’s an opportunity that only happens when you read your code a few days after the fact. Use it to fix the code right then and there when you’re reading for understanding instead of creating. You won’t regret it, and maintainers of your code will thank you. | https://daedtech.com/tag/readability/ | CC-MAIN-2022-40 | en | refinedweb |
table of contents
NAME¶
fileno - obtain file descriptor of a stdio stream
SYNOPSIS¶
#include <stdio.h>
int fileno(FILE *stream);
fileno():
_POSIX_C_SOURCE
DESCRIPTION¶
The function fileno() examines the argument stream and returns the integer file descriptor used to implement this stream. The file descriptor is still owned by stream and will be closed when fclose(3) is called. Duplicate the file descriptor with dup(2) before passing it to code that might close it.
For the nonlocking counterpart, see unlocked_stdio(3).
RETURN VALUE¶
On success, fileno() returns the file descriptor associated with stream. On failure, -1 is returned and errno is set to indicate the error.
ERRORS¶
ATTRIBUTES¶
For an explanation of the terms used in this section, see attributes(7).
CONFORMING TO¶
The function fileno() conforms to POSIX.1-2001 and POSIX.1-2008.
SEE ALSO¶
open(2), fdopen(3), stdio(3), unlocked_stdio(3)
COLOPHON¶
This page is part of release 5.13 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://dyn.manpages.debian.org/unstable/manpages-dev/fileno.3.en.html | CC-MAIN-2022-40 | en | refinedweb |
Upgrading documents from previous versions
If you have documents created in QuickTest, Service Test, or previous versions of UFT One, you can upgrade them for UFT One.
Upgrading QuickTest tests or components
Files last saved in QuickTest 9.5
UFT One will open the asset in read-only mode.
Files last saved in QuickTest earlier than 9.5
An error message is displayed in the UFT One Error Pane.
If the asset is saved in the file system, you must first open it in QuickTest 10.00 or 11.00 to upgrade it.
If the asset is saved in Quality Center or ALM, you must use the QuickTest Asset Upgrade Tool for ALM (available with the QuickTest Professional 10.00 or 11.00 DVD).
Files saved in QuickTest 10.00 or later
Assets last saved in QuickTest 10.00 or later can be opened in UFT One.
QuickTest components
Sharing values between components in a BPT test cannot be done using user-defined environment variables.
Instead, use user-defined run-time settings that you create using the Setting.Add method.
If your QuickTest components used any user-defined environment variables, you must change them to use run-time settings when you upgrade to UFT One.
QuickTest 11.00 and Chrome
If you previously had QuickTest 11.00 installed on your computer and you installed one of the patches or hotfixes that added support for working with the Google Chrome browser (QPTWEB00088 or another Chrome-related patch or hotfix), you must delete your user profile in the Chrome browser before you can use UFT One to test applications in Chrome.
To do this, open the Chrome Settings window in your Chrome browser. In the Users section, click the Delete this user button.
RunScript methods
If you previously used the Frame.RunScript, Frame.RunScriptFromFile, Page.RunScript, or Page.RunScriptFromFile methods in your tests of a Web site or Web application, you should update the RunScript argument to use either an eval function or an anonymous function.
For example, if you used this syntax previously:
Browser("MySearchEngine").Page("MySearchEngine").Frame("Web Search").RunScript "var remove = document.getElementById('logo'); remove.parentNode.removeChild(remove)"
you should update this to:
Browser("MySearchEngine").Page("MySearchEngine").Frame("Web Search").RunScript "eval(var remove = document.getElementById('logo'); remove.parentNode.removeChild(remove););"
OR
Browser("MySearchEngine").Page("MySearchEngine").Frame("Web Search").RunScript "(function(){var remove = document.getElementById('logo'); remove.parentNode.removeChild(remove);})();"
For Service Test tests or components
UFT One 2021-2022 provides a Batch Upgrader command line tool, STBatchUpgrader.exe, located in the <UFT One installation folder>/bin folder.
This tool lets you run a batch file to upgrade tests last saved in Service Test, version 11.10 or 11.20, making them compatible for UFT One2021-2022.
If you do not upgrade your tests with the Batch Upgrader tool, when you open a test created in version 11.10 or 11.20, it prompts you to upgrade the test.
For tests and components created in Service Test 11.00, you must first open and save them in Service Test 11.10, before you can upgrade them to UFT One2021-2022.
Upgrade a test last saved in Service Test version 11.10 or 11.20
Make sure that UFT One is not running.
If you ran the upgrader tool once while UFT One was running, the logs may become corrupted. Backup and delete all of the existing logs in the <UFT One installation folder>\bin\logs folder before proceeding.
If desired, create a backup copy of the older tests.
In the command line, enter the location of the STBatchUpgrader.exe file in the <UFT One installation folder>/bin sub-folder.
Add the relevant command line options as described in Upgrading QuickTest tests or components.
Use the following syntax:
STBatchUpgrader.exe source [destination] [/ALM url domain project] [/login username password] [/log logfile] [/report reportfile]
For example, the following string runs the upgrade on all tests in the ST_11_1 folder on the ALM server, pumpkin, for the TEST1 project in the AUTOMATION domain. It places the report in c:\logs\MyLogfile.log.
STBatchUpgrader.exe Subject\ST11_1 /ALM AUTOMATION TEST1 /login user password /log c:\logs\MyLogfile.log.
Run the command. Verify the validity of the tests in the destination folder.
The following table describes the command line options:
If the UFT One API test upgrade was unable to upgrade the test, you may need to modify the event handler code to make it compatible with the current version:
Change the user code file to TestUserCode.cs.
Change the namespace at the beginning of the file to Script.
Change the class definition to public class TestUserCode : TestEntities
For example:
<![CDATA[ ]]>namespace Script { using System; using System.Xml; using System.Xml.Schema; using HP.ST.Ext.BasicActivities; using HP.ST.Fwk.RunTimeFWK; using HP.ST.Fwk.RunTimeFWK.ActivityFWK; using HP.ST.Fwk.RunTimeFWK.Utilities; using HP.ST.Fwk.RunTimeFWK.CompositeActivities; using System.Windows.Forms; using HP.ST.Ext.FTPActivities; [Serializable()] public class TestUserCode : TestEntities ...
Known issues with Service Test tests | https://admhelp.microfocus.com/uft/en/2021-2022/UFT_Help/Content/User_Guide/Upgrade_Tests.htm | CC-MAIN-2022-40 | en | refinedweb |
The ® allows you to access the Google Play Games
API through Unity's social interface.
The plugin provides support for the
following features of the Google Play Games API:
- friends
- unlock/reveal/increment achievement
- post score to leaderboard
- cloud save read/write
- show built-in achievement/leaderboards UI
- events
- video recording of gameplay
- nearby connections.
Features:
- easy GUI-oriented project setup (integrated into the Unity GUI)
- no need to override/customize the player Activity
- no need to override/customize AndroidManifest.xml
System requirements:
Unity® 5 or above.
To deploy on Android:
- Android SDK
- Android v4.0 or higher
- Google Play Services library, version 11.6 or above. Be particularly careful when entering your package name and your certificate fingerprints, since mistakes on those screens can be difficult to recover from..
Then click the "Android section". backend for your game and need a server auth code to be exchanged for an access token by the backend server, or if you need an id token for the player to make other, non-game, API calls.
Events allow you to track user actions in your game and report on them with Analytics. Read more about how to configure and use Events on Game Concepts - Events.
Note: If you are using a web application or backend server with your game, you can link the web application to the game to enable getting the player's id token and/or email address. To do this, link a web application to the game in the Google Play Developer Console, and enter the client id for the web application into the setup dialog. connections or require access to a player's Google+ social graph, the default configuration needs to be replaced with a custom configuration. To do this use the PlayGamesClientConfiguration. If your game does not use these features, then there is no need to
using GooglePlayGames; using GooglePlayGames.BasicApi; using UnityEngine.SocialPlatforms; PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder() // enables saving game progress. .EnableSavedGames() // requests the email address of the player be available. // Will bring up a prompt for consent. .RequestEmail() // requests a server auth code be generated so it can be passed to an // associated back end server application and exchanged for an OAuth token. .RequestServerAuthCode(false) // requests an ID token be generated. This OAuth token can be used to // identify the player to other services such as Firebase. .RequestIdToken() PlayGamesPlatform.Instance.Authenticate, with a SignInInteractivity enum. Using the enum CanPromptOnce follows the best sign-in practices and it should be used when your game starts. It will:
- Always attempt to silent sign-in
- If silent sign-in fails, check if the user has previously declined to sign in.
- If the user hasn’t previously declined to sign in, then check the internet connection and prompt interactive sign-in if internet is available
- If the interactive sign-in is cancelled by the user, to remember this as a ‘decline’ for the 2nd step of the next sign-in attempt.
Additionally, you should put a sign-in / sign-out button control for Play Games somewhere that makes sense for your game, and where your users can easily find it. For this button, you should use the enum CanPromptAlways.
The full list of enums for PlayGamesPlatform.Instance.Authenticate are: CanPromptOnce will help users have a seamless sign-in experience, by automatically signing them in when your game starts. If automatic sign-in is not successful, they will be prompted to sign in manually with an interactive sign-in screen. If the user does not sign in using the interactive screen, they will not be asked to sign in interactively again. Use this when your game starts up. CanPromptAlways when used, interactive sign-in will be started, if silent sign-in fails and the user will see always see UIs (this does not count the number of declines). Use this for your in-game PGS sign-in button. NoPrompt when used, silent sign-in will be attempted but no UIs will be shown to the user if silent sign-in fails.
using GooglePlayGames; using UnityEngine.SocialPlatforms; ... // authenticate user: PlayGamesPlatform.Instance.Authenticate(SignInInteractivity.CanPromptOnce, (result) =>{ // handle results });
The result code is an enum, which gives you different failure reasons that will help you understand sign-in failures better.
Interactive sign-in.
Incremental authorization
As opposed to asking all scopes you need in advance, you can start with the most basic ones and then ask for new scopes when you need them as it’s suggested in the quality checklist. This will allow silent sign-in to succeed, because silent sign-in will always fail if you ask for more than GAMES_LITE and, if you use Saved Games, DRIVE.APP_DATA. Asking for scopes at the time you need them will also help users understand why you are asking for a scope and make them more likely to give permissions. To learn if you already have a permission for a scope and to ask for a new one, you can use the code snippets below.
PlayGamesPlatform.Instance.HasPermission("email")
PlayGamesPlatform.Instance.RequestPermission("email", result => { // handle results });
Friends
Play Games Friends allows players to create and maintain a cross-games friends list. You can request access to this friends list to help your players play your game with their friends. See the Friends concept page for more details on the friends system.
To enable Friends, use the following functions:
- View friends: Request access to a player’s friends list, so you can add their play games friends to your in-game friends list
- View a player profile: Let a player view the Play Games profile of another player. This is essential so a player knows who their friends are, and can connect to other Play Games players in your game. This will need to be tied to a UI element to trigger the popup. See the friends guidelines for details.
See the best practices guidelines for instructions on how best to implement these APIs.
Note: To use Friends, you need to update your PGS SDK to version 20.0.0
View friends
There are two ways to load friends, either using the
ISocial framework or directly with
PlayGamesPlatform.
Social.localUser.LoadFriends((success) => { Debug.Log("Friends loaded OK: " + ok)); foreach(IUserProfile p in Social.localUser.friends) { Debug.Log(p.userName + " is a friend"); }
However, this call will fail if the current player has not yet granted permission to the game to access this information. Use
GetLastLoadFriendsStatus to check if
LoadFriends failed due to missing consent.
PlayGamesPlatform.Instance.GetLastLoadFriendsStatus((status) => { // Check for consent if (status == LoadFriendsStatus.ResolutionRequired) { // Ask for resolution. } });
A game can ask the current player to share the friends list by calling
AskForLoadFriendsResolution.
PlayGamesPlatform.Instance.AskForLoadFriendsResolution((result) => { if (result == UIStatus.Valid) { // User agreed to share friends with the game. Reload friends. } else { // User doesn’t agree to share the friends list. } });
This function will show the appropriate platform-specific friends sharing UI. This UI asks the player if they want to share their friends with the game.
Another way of loading friends is to use
LoadFriends and
LoadMoreFriends:
PlayGamesPlatform.Instance.LoadFriends(pageSize, forceReload, (status) => { // Check if the call is successful and if there are more friends to load. }); PlayGamesPlatform.Instance.LoadMoreFriends(pageSize, (status) => { // Check if there are more friends to load. });
The
pageSize param represents the number of entries to request for this page. Note that if cached data already exists, the returned buffer may contain more than this size. The buffer is guaranteed to contain at least this many entries if the collection contains enough records. If
forceReload is set to
true, this call will clear any locally-cached data and attempt to fetch the latest data from the server. This would commonly be used for actions like a user-initiated refresh. Normally, this should be set to
false to gain the advantages of data caching.
If the callback returns
LoadFriendsStatus.LoadMore, then there are more friends to load.
LoadFriendsStatus.ResolutionRequired signals that the user has not shared the friends list and you can directly call
PlayGamesPlatform.Instance.AskForLoadFriendsResolution.
Determining friends list visibility
Use
PlayGamesPlatform.Instance.GetFriendsListVisibility to check if the user has shared the friends list with the game. Possible return statuses are:
FriendsListVisibilityStatus.RequestRequiredindicates you must ask for consent.
FriendsListVisibilityStatus.Visibleindicates that loading the friends list should succeed.
FriendsListVisibilityStatus.Unknowngenerally shouldn't happen. You can set
forceReloadto true to refresh the data.
PlayGamesPlatform.Instance.GetFriendsListVisibility(forceReload, (friendsListVisibilityStatus) => {});
View a player profile
To add or remove a player as a friend, use the show and compare profile function. This function triggers a bottom sheet dialog showing the Play Games profile of the user; call the function with the player Id of the requested player. If the player and friend have in-game nicknames, use them in the call to add more context to the profile UI:
PlayGamesPlatform.Instance.ShowCompareProfileWithAlternativeNameHintsUI( mFirstFriendId, /* otherPlayerInGameName= */ null, /* currentPlayerInGameName= */ null, (result) => { // Profile comparison view has closed. });"); } });
Setting popup gravity
You can set the gravity used by popups when showing game services elements such as achievement notifications. The default is TOP. This can only be set after authentication. For example:
Social.localUser.Authenticate((bool success) => { if (success) { ((GooglePlayGames.PlayGamesPlatform)Social.Active).SetGravityForPopups(Gravity.BOTTOM); } });; }); }
This call may fail when trying to load friends with
ResponseCode.ResolutionRequired if the user has not shared their friends list with the game. In this case, use
AskForLoadFriendsResolution to request access.() { uint Server Auth code:
- Configure the web client Id of the web application linked to your game in the Play Game Console.
- Call
PlayGamesClientConfiguration.Builder.RequestServerAuthCode(false)when creating the configuration.
- Call
PlayGamesPlatform.Instance.GetServerAuthCode()once the player is authenticated.
- Pass this code to your server application.
Getting another server auth code after exchanging the first code
If your back end server interactions requires you to send a server auth code
more than once per authenticated session, you can call
PlayGamesPlatform.Instance.GetAnotherServerAuthCode(Action<string> callback)
This method requires the player to be aready authenticated and correctly configured to
request server auth codes on this client. This method is implemented by calling
Google Sign-in silently which returns a new server auth code when already signed in.
Retrieving player's email
In order to access the player's email address:
- Call
PlayGamesClientConfiguration.Builder.RequestEmail()when creating the configuration.
- Access the email property
((PlayGamesLocalUser) Social.localUser).Emailafter the player is authenticated.
Note: If all that is needed is a persistent unique identifier for the player, then you should use the player's id. This is a unique ID specific to that player and is the same value all the time.
// call this from Update() Debug.Log("Local user's email is " + ((PlayGamesLocalUser)Social.localUser).Email);
Retrieving player's ID Token
To get the player's OAuth ID token:
- Call
PlayGamesClientConfiguration.Builder.RequestIdToken()when creating the configuration.
- Access the idtoken property
((PlayGamesLocalUser) Social.localUser).GetIdToken()after the player is authenticated.
Note: The ID Token can be used to identify the real player identity. As a result requesting the ID Token will cause a consent screen to be presented to the user during login.
Video Recording
If you wish to integrate the Play Games video capture functionality into your game, you can use the following features.
Get Video Capture Capabilities
You can access the video capture capabilities of a device, including if the camera, mic, or write storage can be used, as well as the capture modes (save as a file or live stream) and quality levels (SD, HD, etc.).
PlayGamesPlatform.Instance.Video.GetCaptureCapabilities( (status, capabilities) => { bool isSuccess = CommonTypesUtil.StatusIsSuccess(status); if (isSuccess) { if (capabilities.IsCameraSupported && capabilities.IsMicSupported && capabilities.IsWriteStorageSupported && capabilities.SupportsCaptureMode(VideoCaptureMode.File) && capabilities.SupportsQualityLevel(VideoQualityLevel.SD)) { Debug.Log("All requested capabilities are present."); } else { Debug.Log("Not all requested capabilities are present!"); } } else { Debug.Log("Error: " + status.ToString()); } });
Launch the Video Capture Overlay
Before activating the video capture overlay, be sure to check that it can be launched with IsCaptureSupported and IsCaptureAvailable.
if (PlayGamesPlatform.Instance.Video.IsCaptureSupported()) { PlayGamesPlatform.Instance.Video.IsCaptureAvailable(VideoCaptureMode.File, (status, isAvailable) => { bool isSuccess = CommonTypesUtil.StatusIsSuccess(status); if (isSuccess) { if (isAvailable) { PlayGamesPlatform.Instance.Video.ShowCaptureOverlay(); } else { Debug.Log("Video capture is unavailable. Is the overlay already open?"); } } else { Debug.Log("Error: " + status.ToString()); } }); }
Get the Current Video Capture State
When required, you can access the current state of the video capture overlay, including whether or not it is recording, and what mode and resolution it is recording in.
PlayGamesPlatform.Instance.Video.GetCaptureState( (status, state) => { bool isSuccess = CommonTypesUtil.StatusIsSuccess(status); if (isSuccess) { if (state.IsCapturing) { Debug.Log("Currently capturing to " + state.CaptureMode.ToString() + " in " + state.QualityLevel.ToString()); } else { Debug.Log("Not currently capturing."); } } else { Debug.Log("Error: " + status.ToString()); } });
Setup a Listener for Live Updates to the Capture State
To receive an update whenever the status of the video capture overlay changes, use RegisterCaptureOverlayStateChangedListener. Only one listener can be registered at a time, subsequent calls will replace the previous listener. The listener can be unregistered with UnregisterCaptureOverlayStateChangedListener.
PlayGamesPlatform.Instance.Video.RegisterCaptureOverlayStateChangedListener(this);
The object passed to RegisterCaptureOverlayStateChangedListener must implement CaptureOverlayStateListener from GooglePlayGames.BasicApi.Video. The OnCaptureOverlayStateChanged in that object will be called when the state changes.
public void OnCaptureOverlayStateChanged(VideoCaptureOverlayState overlayState) { Debug.Log("Overlay State is now " + overlayState.ToString()); }
Sign out
To sign the user out, use the PlayGamesPlatform.SignOut method.
using GooglePlayGames; using UnityEngine.SocialPlatforms; // sign out PlayGamesPlatform.Instance.SignOut();
After signing out, no further API calls can be made until the user authenticates again.
Decreasing apk size.
Additionally, it is possible to reduce the size of the entire Unity project using Unity’s Managed Code Stripping, which will compress your entire project. This can be used in conjunction with Proguard.
Play Games Services Proguard configuration
- Go to
File > Build Settings > Player Settingsand click
Publishing Settingssection. Choose
Proguardfor
Minify > Release. Then, enable
User Proguard File. If you want the plugin to be proguarded for debug apks as well, you can choose
Proguardfor
Minify > Debug.
- Copy the content of the proguard configuration into
Assets/Plugins/Android/proguard-user.txt.
. | https://curatedcsharp.com/p/google-play-playgameservices-play-games-plugin-for-unity/index.html | CC-MAIN-2022-40 | en | refinedweb |
@Generated(value="OracleSDKGenerator", comments="API Version: 20200630") public class ListApmDomainsRequest extends BmcRequest<Void>
getBody$, getInvocationCallback, getRetryConfiguration, setInvocationCallback, setRetryConfiguration, supportsExpect100Continue
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
public ListApmDomainsRequest()
public String getCompartmentId()
The ID of the compartment in which to list resources.
public String getDisplayName()
A filter to return only resources that match the entire display name given.
public LifecycleStates getLifecycleState()
A filter to return only resources that match the given life-cycle state.ApmDomainsApmDomainsRequest.Builder toBuilder()
Return an instance of
ListApmDomainsRequest.Builder that allows you to modify request properties.
ListApmDomainsRequest.Builderthat allows you to modify request properties.
public static ListApmDomains> | https://docs.oracle.com/en-us/iaas/tools/java/2.44.0/com/oracle/bmc/apmcontrolplane/requests/ListApmDomainsRequest.html | CC-MAIN-2022-40 | en | refinedweb |
Summary In this chapter, I've touched upon the high-level characteristics of programs written in C#.. However, as with most engineering trade-offs, there are other aspects (read: complications) of memory and resource management that the GC can introduce in certain situations. Using the venerable "Hello World!" example, I was able to quickly show the usefulness of namespaces as well as the fact that C# is devoid of any kind of inclusion syntax as available in C++. Instead, all other external types are brought into the compilation unit via metadata, which is a rich description format of the types contained within an assembly. Therefore, the metadata and the compiled types are always contained in one neat package. Generics open up such a huge area of development that you'll probably still be learning handy tricks of applying them over the next several years. Some of those tricks can be borrowed from the C++ template world, but not all of them, since the two concepts are fundamentally different. Iterators and anonymous methods offer a concise way of expressing common idioms such as enumeration and callback methods, while support for partial type declarations within C# makes it easier to work with tool-generated code. C# 3.0 offers many new and exciting features that allow one to employ functional programming techniques very easily with little overhead. Some of the new features add convenience to programming in C#. LINQ provides a seamless mechanism to bridge to the data storage world from the object-oriented world. In the next chapter, I'll briefly cover more details regarding the JIT compilation process. Additionally, I'll dig into assemblies and their contained metadata a bit more. Assemblies are the basic building blocks of C# applications, analogous to DLLs in the native Windows world. | http://www.c-sharpcorner.com/UploadFile/FreeBookArticles/apress/2009Jan08004344AM/csharppreview/5.aspx | crawl-003 | en | refinedweb |
LDEXP(3) BSD Programmer's Manual LDEXP(3)
ldexp - multiply floating-point number by integral power of 2
#include <math.h> double ldexp(double x, int exp);
The ldexp() function multiplies a floating-point number by an integral power of 2.
The ldexp() function returns the value of x times 2 raised to the power exp. If the resultant value would cause an overflow, the global variable errno is set to ERANGE and the value HUGE is returned.
frexp(3), math(3), modf(3)
The ldexp() function conforms to ANSI X3.159-1989 ("ANSI C").. | http://mirbsd.mirsolutions.de/htman/sparc/man3/ldexp.htm | crawl-003 | en | refinedweb |
python-sld 1.0.8
A simple python library that enables dynamic SLD creation and manipulation.
Downloads ↓ | Package Documentation.
import sld mysld = StyledLayerDescriptor()
You may also read an existing SLD document in by passing it as a parameter:
import sld mysld = StyledLayerDescriptor('mys:
rule1 = fts.Rules[0] print len(fts.Rules) fts.Rules[0] = rule1
Filter objects are pythonic, and when combined with the '+' operator, they become ogc:And filters. When combined with the '|' operator, they become ogc:Or filters.
filter_1 = Filter(rule) # set filter 1 properties
filter_2 = Filter(rule) # set filter 2 properties
rule.Filter = filter_1 + filter_2
You may also construct a filter from an expression when using the create_filter method on the Rule object:
filter = rule.create_filter('population', '>', '100')
Support
If you have any problems or questions, please visit the python-sld project on github:
- Author: David Zwarg
- Documentation: python-sld package documentation
- Keywords: ogc sld geo geoserver mapserver osgeo
- License: Apache 2.0
- Requires lxml
- Categories
- Package Index Owner: dzwarg
- DOAP record: python-sld-1.0.8.xml | http://pypi.python.org/pypi/python-sld | crawl-003 | en | refinedweb |
sst 0.1
- note: xvfb is only needed if you want to run SST in headless mode
Example SST test script
a sample test case in SST:
from sst.actions import * go_to('') assert_title_contains('Ubuntu homepage')
Running a test with SST
Create a Python script (.py) file, and add your test code.
Then call your test script from the command line, using sst-run:
$ sst-run mytest
- note: you don't add the .py extension to your test invocation
API '.py' at the end of the filename.
- You may optionally create a data file for data-driven testing. Create a '^' delimited txt data file with the same name as the test, plus the '.csv' extension. This will run a test using each row in the data file (1st row of data file is variable name mapping)
Options:
-h, --help show this help message and exit -d DIR_NAME directory of test case files -r REPORT_FORMAT results report format (html, xml, console) -b BROWSER_TYPE select webdriver (Firefox, Chrome, InternetExplorer, etc) -j disable javascript in browser -m SHARED_MODULES directory for shared modules -q output less debugging info during test run -V print version info and exit -s save screenshots on failures --failfast stop test execution after first failure --debug drop into debugger on test fail or error --test run selftests -x run tests in headless xserver, install requirements, and run self-tests/examples from the branch:
$ sudo apt-get install bzr python-pip xvfb $ bzr branch lp:selenium-simple-test $ cd selenium-simple-test $ sudo pip install -U -r requirements.txt $ ./sst-run --test -x $ ./sst-run -d examples
-
Browse the Source (Trunk)
To manually setup dependencies, SST uses the following non-stdlib packages:
- selenium
- unittest2
- junitxml
- pyvirtualdisplay
- ISD Team
- Keywords: selenium,webdriver,test,testing,web,automation
- Categories
- Development Status :: 3 - Alpha
-.1.0.xml | http://pypi.python.org/pypi/sst/0.1.0 | crawl-003 | en | refinedweb |
ILOGB(3) BSD Programmer's Manual ILOGB(3)
ilogb, ilogbf, ilogbl - an unbiased exponent
libm
#include <math.h> int ilogb(double x); int ilogbf(float x); int ilogbl(long double x);
The ilogb(), ilogbf(), and ilogbl() functions return the exponent of the non-zero real floating-point number x as a signed integer value. Formally the return value is the integral part of log_r | x , where r is the radix of the machine's floating-point arithmetic defined by the FLT_RADIX constant in #include <float.h>.
ilog2(3), logb(3), math(3)
The described functions conform to ISO/IEC 9899:1999 ("ISO C99").
Neither FP_ILOGB0 nor FP_ILOGBNAN is defined currently in NetBSD. MirOS BSD #10-current July. | http://mirbsd.mirsolutions.de/htman/sparc/man3/ilogbl.htm | crawl-003 | en | refinedweb |
The.
Mike,Great article! What an excellent resource and tutorial for folks interested in embedding the Flash player within a windows app. I have had a lot of success embedding the player within Visual Basic apps. Now I am excited to start working with .NET as well.Keep up the great work! And congrats on getting DRK4 out the door, looks like quite a collection!Rob
Thank you for the article,Just a theoretical question. Instead of passing data to the player as String, would it be ideal to pass data as an AMF package (e.g. using classes in System.Runtime.Serialization namespace). For example a DataSet can be passed to the interpreter and it can be deserialized as native ActionScript datatypes. Would this be possible without making use of the proxy used in Remoting for .NET?
Hey Mike,Great article! Now … all we need is someone to show us how to embed Flash into an OS X application using Objective C and Project Builder (or X Code when it comes out for Panther).cheers,Jon
>Instead of passing data to the player as String, would it be ideal to pass data as an AMF packageThat is a good question. The only way that I think this would be possible is the have the windows app and flash movie talk to each other via Flash Remoting.Even then, yo uwuold have to figure out how to use the Flash Remoting server side DLL in your code. (which is not document).It is also a potential secruity issue as your app essentially becomes a web server.However, that does not mean it is not possible in a better way, but I just dont know.hope that helps…mike chambersmesh@macromedia.com
Thanks for the article. Good stuff!How about passing data from Flash to C#? FSCommand? …or are there cleaner ways of doing it?
Yes. You would use FSCommand, which would then trigger an event in C#.It is not that difficult, and perhaps if i have time, I will write another article on it, or post some info on my weblog.mike chambersmesh@macromedia.com
Hi mike,it is possible to Listen when the FlashPlayer Crash over the 200.000 actions ?Of I have 2000 line of code in C# ,I don’t would the ALL of my code was compromised by the Stupid Crash of FlashPlayer over the 200.000 actions …Mark
Mike,It’s good to hear that we can embedd Flashpaper into windows application.But, it’s bad we can’t embedd Flashpaper just into another Flash application.Is making Flashpaper as a popup from a Flash file a only way to work with another Flash application? Did we thought about it?
hi, great article! i was just wondering if anyone has any ideas about applying any of this to an ASP.NET web form as opposed to a windows form – specifically if there is some way to use ActiveXObject.SetVariable in C# as this would solve the problems i’m currently having! (javascript’s .setVariable command DOES NOT WORK in an ASPX page).
Hi Mike,Great article. It was all a little forign since I’m not familiar with C#, but informative nevertheless. I actually found this by searching the net for a solution to add the ActiveX Shockwave Flash Object into a C++ MFC app. Unfortunately, there’s no documentation on such an animal, but I’m going to tackle this and figure it out anyway, so I’ll write an article in the process. I’ve been thinking of a good subject to write about anyway.
I’m developing an RSS News Aggregator and after a lot of investigation, it appears that Flash is the best solution for the News Ticker, as it has a nice smooth scrolling appearance and requires minimal system resources.The movie and all of the RSS/XML stuff’s done and it plays fine on my dialog, but I have one little problem. I’m hoping you or someone else reading this can help. I need the background to be transparent but if I simply change the WMode to “Transparent”, the entire movie dissapears. Of course, it wouldn’t be that easy. Any ideas? Or do you know where I can find some half-way decent documentation on the properties of the control?Again, thanks for the info!Don
Congratulations to your fantastic Site. Thanks
Thanks for the pointer! i was about to start asking questions about that.
Hi Mike,I have to make a C# application which can play .swf files. The problem is I need an event to tell me when the playing of the movie is complete which the Shockwave Flash Object doesn’t seem to provide. Am I missing something?Any help in this matter will be very apreciated.BTW: Great article.
Mike,How can I embed a Flash Player into a C++ application?Thanks,Chuck
I re-echo an earlier question, and hope you can supply me with the answer. How would you add a flash player (to play swf files) in a web app made with C# ?Thank you.
>I re-echo an earlier question, and hope you can supply me with the answer. How would you add a flash player (to play swf files) in a web app made with C# ? chambersmesh@macromedia.com
Hi,I have used this setvariable function in Flash MX 2004 Pro. but it is giving problem in Flash MX
what should I do? Is there any way to use this function which will work in Flash MX also…Thanx
Hi Mike,I have used this setvariable function in Flash MX 2004 Pro. but it is giving problem in Flash MX
what should I do? Is there any way to use this function which will work in Flash MX also…Thanx
Does anybody have any info on the best way to detect if the user has Flash installed or not, before the flash object is loaded into the form?I’m guessing there must be some info out there on where on each OS the player is installed to, and the form could do a check to see if the file exists or not? Or is there an easier way…?
Great atrical, I am very much happy to use the C# with Flash. This a great exitement to me to use the C#……………..
Great atrical, I am very much happy to use the C# with Flash. This a great exitement to me to use the C#……………..
Hi Mke,Great work!!!, I am also intreated in using C# and Flash. Please help me, how to read the srteam details of a user from Communication app inspector – Flash communication server?is it possible?regards,Vinu
I have the same question as Aashi.What is the best way to detect if the user has Flash installed or not, before the flash object is loaded into the form?anybody can help?thx.
Mike, thank you for your informative and well written article. I am developing a c# app that utilizes flash and it needs to be strongly named to support updating code that I have written (and because it is good practice). The AxShockwaveFlashInteropObjects or whatever dlls are not strongly named when generated at compile time, which throws a whole bunch of problems into my application. How would I resolve this?
connected to flash with window application
i have Embedding Flash into C# is finish, but all control on Flash is not use. why ? | http://blogs.adobe.com/mesh/2003/07/embedding_flash.html | crawl-003 | en | refinedweb |
You’ve seen in previous Windows Phone Mini-tutorials
that all tasks have the same basic structure:
- Instantiate the task
- Add any specifying data
- Show the task
The Bing Maps Task is no different. In fact, it is so simple to use I hesitate to dedicate a mini-tutorial to it. This will be brief.
To find a specific location using Bing Maps, all you need do is create a new Windows Phone application. Set the Page and Application title and create a new row into which you’ll place a button (all of this is optional, but it makes the program easier to work with).
Name the new button FindSiteButton and give it an event handler on its click event, as shown here:
<StackPanel x: <TextBlock x: <TextBlock x: </StackPanel> <!--ContentPanel - place additional content here--> <Grid x: <Grid.RowDefinitions> <RowDefinition Height="96*" /> <RowDefinition Height="511*" /> </Grid.RowDefinitions> <Button Name="FindSiteButton" Content="Find" HorizontalAlignment="Center" VerticalAlignment="Center" Click="FindSiteButton_Click" /> </Grid>
Since you put the event handler into the Xaml, you’ll find a stub for that method in the code behind. Switching to MainPage.xaml.cs, let’s fill in that event handler.
We do so by adding an instance of BingMapsTask (which you’ll need to add the using statement,
using Microsoft.Phone.Tasks;
Set the SearchTerm property of this task to a famous location and then, as with all tasks, call show:
private void FindSiteButton_Click( object sender, RoutedEventArgs e ) { BingMapsTask bmt = new BingMapsTask(); bmt.SearchTerm = "Statue of Liberty"; bmt.Show(); }
Now run the emulator, click the button and you will see that Bing Maps instantly displays a map with the Statue of Liberty pin-pointed.
The computer thinks these might be related:
Hi , Thanks for tutorial , is was great . i want to ask , How can i send my lat. and log. to a server and a service that store it and other client can receive it , ?
Great new feature. This definitely makes working with the mapping api much easier for simple tasks. | http://jesseliberty.com/2011/08/04/bing-maps-task/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+JesseLiberty-SilverlightGeek+%28Jesse+Liberty+-+Silverlight+Geek%29 | crawl-003 | en | refinedweb |
Introducing Indigo: An Early Look
David Chappell
Chappell & Associates
February 2005
Summary: Provides an architectural overview of "Ind. (24 printed pages)
Note This article is based on a prerelease version of Indigo's first Community Technology Preview (CTP). Be aware that features and implementation details are subject to change as Indigo progresses through the product cycle.
Contents
What Is Indigo?
What Indigo Provides
Creating an Indigo Service
Creating an Indigo Client
Other Aspects of Indigo
Coexistence and Migration
Conclusions
About the Author
What Is Indigo?.
The figure above shows a simple view of an Indigo client and service. Indigo provides a foundation, implemented primarily as a set of classes running on the Common Language Runtime (CLR), for creating services that are accessed by clients. A client and service interact via SOAP, Indigo's native protocol, and so even though the figure shows both parties built on Indigo, this certainly isn't required.
Indigo is built on and extends the .NET Framework 2.0, which is scheduled for release in 2005. Indigo itself will ship as part of the Windows release code-named Longhorn, scheduled for 2006, and it will also be made available on Windows XP and Windows Server 2003. This description is based on a pre-release version of Indigo's first Community Technology Preview. Be aware that some changes are likely (almost certain, in fact) before the final version ships.
What Indigo Provides
Many people at Microsoft have devoted years of their lives to creating Indigo. This level of effort wouldn't have been necessary if the problems it solved were simple or if their solutions were obvious. Accordingly, Indigo is a substantial piece of technology. Three things stand out, however, as Indigo's most important aspects: its unification of several existing Microsoft technologies, its support for cross-vendor interoperability, and its explicit service-orientation. This section looks at each of these.
Unification of Microsoft's Distributed Computing Technologies
The initial releases of the .NET Framework included several different technologies for creating distributed applications. The figure below lists each one, along with the primary reason why a developer would typically use that technology. To build basic interoperable Web services, for example, the best choice was ASP.NET Web services, more commonly referred to as ASMX. To connect two .NET Framework-based applications, .NET Remoting was sometimes the right approach. If an application required distributed transactions and other more advanced services, its creator was likely to use Enterprise Services, the .NET Framework's successor to COM+. To exploit the latest Web services specifications, such as WS-Addressing and WS-Security, a developer could build applications that used Web Services Enhancements (WSE), Microsoft's initial implementation of these emerging specifications. And to create queued, message-based applications, a Windows-based developer would use Microsoft Message Queuing (MSMQ).
All of these options had value, yet the diversity was certainly confusing to developers. Why have so many choices? A better solution would be to have one technology that addresses all of these problems. With the arrival of Indigo, that technology has appeared. Rather than forcing developers to choose one of several possibilities, Indigo lets them create distributed applications that address all of the problems solved by the technologies it subsumes. While Microsoft will still support these earlier technologies, most new applications that would previously have used any of them will instead be built on Indigo.
Interoperability with Non-Microsoft Applications
Making life easier for Windows developers by unifying disparate technologies is a good thing. But with the universal agreement among vendors on Web services, the long-standing problem of application interoperability can also be solved. Because Indigo's fundamental communication mechanism is SOAP, Indigo applications can communicate with other software running in a variety of contexts. As shown in the figure below, an application built on Indigo can interact with all of the following:
- Indigo applications running in a different process on the same Windows machine.
- Indigo.
Indigo applications can also interoperate with applications built on some of the .NET Framework technologies that preceded Indigo, such as ASMX, as described later.
To allow more than just basic communication, Indigo implements a group of newer Web services technologies collectively referred to as the WS-* specifications. These documents define multi-vendor ways to add reliable messaging, security, transactions, and more to SOAP-based Web services. All of these specs were originally defined by Microsoft, IBM, and other vendors working together. As they become stable, ownership often passes to standards bodies such as the Organization for the Advancement of Structured Information Standards (OASIS). The Web services specs supported in Indigo's first release include WS-Addressing, WS-Policy, WS-MetadataExchange, WS-ReliableMessaging, WS-Security, WS-Trust, WS-SecureConversation, WS-Coordination, WS-AtomicTransaction, and the SOAP Message Transmission Optimization Mechanism (MTOM).
When an Indigo application communicates with an application running on a non-Windows system, the protocol used is standard SOAP (perhaps with some WS-* extensions), represented on the wire in its usual text-based XML encoding. When one Indigo-based application communicates with another Indigo-based app, however, it makes sense to optimize this communication. All of the same features are provided, including reliable messaging, security, and transactions, but the wire encoding used is an optimized binary version of SOAP. Messages still conform to the data structure of a SOAP message, referred to as its Infoset, but their encoding uses a binary representation of that Infoset rather than the standard angle-brackets-and-text format of XML.
Explicit Support for Service-Oriented Development
Thinking of an application as providing and consuming services is hardly a new idea. What is new is a clear focus on services as distinct from objects. Toward this end, Indigo's creators kept four tenets in mind during the design of this technology:
- Share schema, not class: unlike older distributed object technologies, services interact with their clients only through a well-defined XML interface. Behaviors such as passing complete classes, methods and all, across service boundaries aren't allowed.
- Services are autonomous: a service and its clients agree on the interface between them, but are otherwise independent. They may be written in different languages, use different runtime environments, such as the CLR and the Java Virtual Machine, execute on different operating systems, and differ in other ways.
- Boundaries are explicit: a goal of distributed object technologies such as Distributed COM (DCOM) was to make remote objects look as much as possible like local objects. While this approach simplified development in some ways by providing a common programming model, it also hid the inescapable differences between local objects and remote objects. Services avoid this problem by making interactions between services and their clients more explicit. Hiding distribution is not a goal.
-.
Creating an Indigo Service
As the figure below shows, every Indigo service is constructed from three things:
- A service class, implemented in C# or VB.NET or another CLR-based language, that implements one or more methods;
- A host environment—an application domain and process—in which the service runs;
- One or more endpoints that allow clients to access the service.
All communication with an Indigo service happens via the service's endpoints. Each endpoint specifies a contract that identifies which methods are accessible via this endpoint, a binding that determines how a client can communicate with this endpoint, and an address that indicates where this endpoint can be found.
Understanding Indigo requires grasping all of these concepts. This section describes each one, beginning with service classes.
Creating a Service Class
An Indigo service class is a class like any other, but it has a few additions. These additions allow the class's creator to define one or more contracts that this class implements. Each Indigo service class implements at least one service contract, which defines the operations this service exposes. A service class might also explicitly implement a data contract, which defines the data those operations convey. This section looks at both, beginning with service contracts.
Defining Service Contracts
Every Indigo service class implements methods for its clients to use. The creator of a service class determines which of its methods are exposed as client-callable operations by including them in a service contract. Defining service contracts—in fact, working explicitly with services in general—is largely a new idea for the .NET world. Indigo's creators needed to find a way to graft this idea on top of the CLR and the programming languages built on it. Fortunately, the CLR's creators anticipated the need for extensions like this, and so they provided support for attributes. As seen by a developer, attributes are character strings, perhaps with associated properties, that can appear before a class definition, a method definition, and in other places. Wherever an attribute appears, it changes some aspect of the behavior of the thing it's associated with.
The .NET Framework has used attributes for various things since its initial release. For example, to mark a method as a SOAP-callable web service in the Framework's ASMX technology, that method is preceded by the
WebMethod attribute. Similarly, Enterprise Services uses the
Transaction attribute to indicate that a method requires a transaction. Indigo applies this idea to services, defining a range of attributes to define and control services.
The most fundamental attribute in Indigo is
ServiceContract. In fact, an Indigo service class is just a class that is either itself marked with the
ServiceContract attribute or that implements an interface marked with this attribute. Here's a simple C# example that uses the first approach:
The
ServiceContract attribute and all of the other attributes that Indigo uses are defined in the
System.
ServiceModel namespace, and so this example begins with a
using statement that references this namespace. Each method in a service class that can be invoked by a client must be marked with another attribute named
OperationContract. All of the methods in a service class that are preceded by the
OperationContract attribute are automatically exposed by Indigo as SOAP-callable operations. In this example,
Add and
Subtract are both marked with this attribute, and so both are exposed to clients of this service. Any methods in a service class that aren't marked with
OperationContract, such as
Multiply in the example above, aren't included in the service contract, and so can't be called by clients of this Indigo service.
Two quite separate abstractions, services and objects, come together in Indigo. It's important to understand that both rely on contracts, either explicitly or implicitly, to define what they expose to the outside world. An object, specified by some class, effectively defines a contract that determines which of its methods can be invoked by another object in the same application. Access to these methods is controlled by language keywords such as
public and
private. In the class
Calculator shown above, for example, other objects in the same application can call
Subtract and
Multiply, this class's two public methods. The object contract this class exposes contains only these two methods.
Using Indigo's attributes,
Calculator also defines a service contract, as just described. This contract also has two methods, but they aren't the same as those in its object contract. Whether a method can be invoked by a client of this Indigo service is controlled by the
OperationContract attribute, not the
public and
private keywords. Because this attribute appears only on
Add and
Subtract, only these two methods can be called by clients. The object contract and service contract are completely distinct from one another, which is why a method such as
Add can be
private while still carrying the
OperationContract attribute.
The example just shown illustrates the simplest way to create an Indigo service class: marking a class directly with
ServiceContract. When this is done, the class's service contract is implicitly defined to consist of all methods in that class that are marked with
OperationContract. It's also possible (and probably better in most cases) to specify service contracts explicitly using a language's
interface type. With this approach, the
Calculator class might look like this:
using System.ServiceModel; [ServiceContract] interface ICalculator { [OperationContract] int Add(int a, int b); [OperationContract] int Subtract(int a, int b); } class Calculator : ICalculator { public int Add(int a, int b) // private methods aren't { // allowed in interfaces return a + b; } public int Subtract(int a, int b) { return a - b; } public int Multiply(int a, int b) { return a * b; } }
In this example, the
ServiceContract and
OperationContract attributes are assigned to the
ICalculator interface and the methods it contains rather than to the
Calculator class itself. The result is the same, however, and so this version of the service exposes the same service contract as the previous one. Using explicit interfaces like this is slightly more complicated, but it also allows more flexibility. For example, a class can implement more than one interface, which means that it can also implement more than one service contract. By exposing multiple endpoints, each with a different service contract, a class can present different groups of services to different clients.
One final point: marking a service class with
ServiceContract and
OperationContract also allows automatically generating service contract definitions in the Web Services Description Language (WSDL). Accordingly, the externally visible definition of every Indigo service contract can be accessed as a standard WSDL document specifying the operations in that contract. And although it's not described here, it's also possible to create an Indigo service class directly from a WSDL document, an approach that's especially useful for implementing externally defined WSDL interfaces.
Defining Data Contracts
An Indigo service class specifies a service contract that defines which of its methods are exposed to service clients. Each of those operations will typically convey some data, which means that a service contract also implies some kind of data contract describing the information that will be exchanged. In some cases, this data contract is defined implicitly as part of the service contract. For example, in the
Calculator classes shown above, each method takes two input parameters, both integers, and returns a single integer. These parameters define all of the data exchanged by this service, and so they comprise the service's data contract. For services like this one, where every operation uses only simple types, it makes sense to define the data aspects of its contract implicitly within the service contract. There's an Indigo. Here's a simple example:
When an instance of this
Customer type is passed as a parameter in a method marked with
OperationContract, only the fields marked with the
DataMember attribute—
Name and
CreditRating—will be passed.
Whether a field is labeled as
public or
private has no effect on whether that field is serialized. Just as with methods, the
public and
private keywords are part of the contract defining how this type can be accessed by other objects in the same application.
DataMember, like
OperationContract, defines how the type can be accessed by clients of the service this class implements. Once again, the two are completely distinct.
One final point worth emphasizing about Indigo contracts is that nothing becomes part of either a service contract or a data contract by default. Instead, a developer must explicitly use the
ServiceContract and
DataContract attributes to indicate which types have Indigo-defined contracts, then explicitly specify which parts of those types are exposed to clients of this service using the
OperationContract and
DataMember attributes. One of the tenets of its designers was that services should have explicit boundaries, and so Indigo is an opt-in technology. Everything a service makes available to its clients is expressly specified in the code.
Contracts and the attributes that define them are a major aspect of Indigo, and this short description covers only the highlights. The
OperationContract attribute can be used to define one-way operations, for example, where a call to a service has no reply. It's also possible to define interactions where both sides can act as client and service, each invoking operations and exposing operations that the other invokes, by creating what are called duplex contracts. The
DataContract attribute has several more options as well, and it's even possible to work directly with SOAP messages natively using an attribute called
MessageContract. Contracts are used to express much of what Indigo provides, and so they're one of its most fundamental concepts.
Selecting a Host
A class implementing an Indigo service is typically compiled into a library. By definition, all libraries need a host application domain and Windows process to run in. Indigo provides two options for hosting libraries that implement services. One is to use a host app domain and process provided by the Windows Activation Service (WAS), while the other allows a service to be hosted in any app domain running in an arbitrary process. This section describes both, beginning with WAS.
Hosting a Service Using the Windows Activation Service
The simplest way to host an Indigo service is to rely on WAS. (Note that WAS isn't supported in Indigo's first Community Technology Preview. Instead, Indigo services can be hosted in Internet Information Server on Windows Server 2003 and Windows XP, although only SOAP over HTTP is supported in this configuration.) Using WAS is much like using the hosting mechanism provided by IIS for ASMX. Among other things, both rely on the notion of a virtual directory, which is just a shorter alias for an actual directory path in the Windows file system.
To see how WAS hosting works, suppose either of the
Calculator classes shown earlier was compiled into a library called calc.dll, then placed in the virtual directory calculator on a system running Windows Server 2003. To indicate that the Indigo service implemented in calc.dll should be hosted by WAS, a developer creates a file in the calculator virtual directory with the extension .svc (which stands, of course, for "service"). For our simple example, this file might be called calc.svc, and its entire contents could be:
Once this has been done and an endpoint has been defined as shown in the next section, a request from a client to one of the
Calculator service's methods will automatically create an instance of this class to execute the specified operation. That instance will run in an application domain created within the standard process that WAS provides.
Hosting a Service in an Arbitrary Process
Relying on WAS to provide a process for hosting an Indigo service is certainly the simplest choice. Yet applications often need to expose services from their own process rather than relying on one provided by Windows. Fortunately, this isn't hard to do. The following example shows how to create a process that hosts either of the
Calculator classes defined earlier:
Since the class
CalculatorHost includes a
Main method, it will run as a distinct process. To host the example
Calculator service, this method must create a new instance of the class
ServiceHost<T>, passing in the
Calculator class. (Note that this standard Indigo class is a generic, indicated by the
< and
> that enclose its parameter. Generics are a new language feature in version 2.0 of C#, Visual Basic .NET, and other languages based on version 2.0 of the .NET Framework.) Once an instance of this class is created, the only thing required to make the service available is to call the
Open method on that instance. Indigo will now automatically direct requests from clients to the appropriate methods in the
Calculator class.
To allow an Indigo service to process requests from its clients, the process that hosts it must remain running. This isn't an issue with WAS-hosted services, since the standard process WAS provides ensures this. A hosting application must solve this problem on its own, however. In this simple example, the process is kept running through the straightforward mechanism of waiting for input from a console user.
Defining Endpoints
Along with defining operations in an Indigo service class and specifying a host process to run those operations, an Indigo service must also expose one or more endpoints. Every endpoint specifies the following three things:
- A contract name indicating which service contract this Indigo service class exposes via this endpoint. A class marked with
ServiceContractthat implements no explicit interfaces, such as
Calculatorin the first example shown earlier, can expose only one service contract. In this case, all of its endpoints will expose the same contract. If a class explicitly implements two or more interfaces marked with
ServiceContract, however, different endpoints can expose different contracts.
-. Suppose, for instance, that a service's creator wishes to allow clients to access that service using either SOAP over HTTP or SOAP over TCP. Each of these is a distinct binding, and so the service would need to expose two endpoints, one with a SOAP-over-HTTP binding and the other with a SOAP-over-TCP binding.
Bindings are a critical part of how communication is accomplished. To make them easier to use, Indigo includes a set of predefined bindings, each of which specifies a particular group of options. This set includes:
- BasicProfileHttpBinding: conforms to the Web services Interoperability Organization (WS-I) Basic Profile 1.0, which specifies SOAP over HTTP. This is an endpoint's default binding if none is explicitly specified.
- BasicProfileHttpsBinding: conforms to the WS-I Basic Security Profile 1.0, which specifies SOAP over HTTPS.
- WsHttpBinding: supports reliable message transfer with WS-ReliableMessaging, security with WS-Security, and transactions with WS-AtomicTransaction. This binding allows interoperability with other Web services implementations that also support these specifications.
- WsDualHttpBinding: like WsHttpBinding, but also supports interaction using duplex contracts. Using this binding, both services and clients can receive and send messages.
- NetTcpBinding: sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. This binding can only be used for Indigo-to-Indigo communication.
- NetNamedPipeBinding: sends binary-encoded SOAP over named pipes. This binding is only usable for Indigo-to-Indigo communication between processes on the same Windows machine.
- NetMsmqBinding: sends binary-encoded SOAP over MSMQ, as described later. This binding can only be used for Indigo-to-Indigo communication.
The figure above shows example values for each of the three elements in an endpoint for the first
Calculator service shown earlier. The name of the service's contract is
Calculator, which is the name of the class that implements this service, and the binding is
BasicProfileHttpBinding. Assuming this service is hosted using WAS, installed in the virtual directory calculator as described earlier, and running on a machine named qwickbank.com, its address might be.
Unlike contracts, endpoints aren't defined using attributes. While it is possible to create endpoints programmatically, the most common approach will probably be to use a configuration file associated with the service. WAS-hosted services use the web.config file, while those hosted independently using the configuration file associated with the application they're running in (commonly referred to as app.config, although the actual filename varies). If used solely for the first
Calculator service class shown earlier, this configuration file might look like this:
The configuration information for all services an Indigo application implements is contained within the
system.serviceModel element. This element contains a
services element that can contain one or more
service elements. This simple example has only a single service, so there's just one occurrence of
service. The
serviceType attribute of the
service element identifies the service class that implements the service this configuration applies to, which in this case is
Calculator. Each
service element can contain one or more
endpoint elements, each of which specifies a particular endpoint through which this Indigo service can be accessed. In this example, the service exposes only a single endpoint, and so only one
endpoint element appears. The name of the endpoint's contract is
Calculator, which is the name of the class that implements it. If this configuration file were for the second
Calculator service class shown earlier, which defined its service contract using an explicit interface, the value of the
serviceType attribute would remain the same, but the value of
contractType would instead be
ICalculator, the name of this explicit interface. The binding specified here is
basicProfileHttpBinding, although since this is the default, it could have been omitted. And assuming
Calculator is a WAS-hosted service, an address is created automatically, so there's no need to specify one in this config file.
Creating an Indigo Client
Creating a basic Indigo service isn't especially complicated. Creating an Indigo client is even simpler. All that's required is to create a local stand-in for the service, called a proxy, that's connected to a particular endpoint on the target service, then invoke the service's operations via this proxy. The figure below shows how this looks.
Creating a proxy requires knowing exactly what contract is exposed by the target endpoint, then using this contract's definition to generate the proxy. In Indigo, this process is performed by a tool called svcutil. If the service is implemented using Indigo, svcutil can access the service's DLL to learn about the contract and generate a proxy. If only the service's WSDL definition is available, svcutil can read this to produce a proxy. If only the service itself is available, svcutil can access it directly using either WS-MetadataExchange or a simple HTTP GET to acquire the service's WSDL interface definition, then generate the proxy.
However it's generated, the client can create a new instance of the proxy, then invoke the service's methods using it. Here's a simple example of a client for the
Calculator class:
using System.ServiceModel; using Indigo.Example; // namespace for generated proxy class public class CalculatorClient { public static void Main() { CalculatorProxy p = new CalculatorProxy(); Console.WriteLine("7 + 2 = {0}", p.Add(7, 2)); Console.WriteLine("7 - 2 = {0}", p.Subtract(7, 2)); p.Close(); } }
One more thing remains to be specified by the client: the exact endpoint it wishes to invoke operations on. Like a service, the client must specify the endpoint's contract, its binding, and its address, and this is typically done in a config file. In fact, if enough information is available, svcutil will automatically generate an appropriate client configuration file for the target service.
Other Aspects of Indigo
The basics of services and clients are fundamental to every Indigo application. Yet most of those applications will also use other aspects of this technology. This section takes a look at some of the additional features that Indigo provides for applications built on it.
Controlling Local Behavior
Many aspects of Indigo, such as contracts, bindings, and more, are related to communication between a service and its clients. Yet there are also parts of a service's behavior that are essentially local. How is a service instance's lifetime controlled, for example, and how is concurrent access to that instance managed? To allow developers to control behaviors like these, Indigo defines two primary attributes, both of which have a number of properties. One of these attributes,
ServiceBehavior, can be applied to classes that are also marked with the
ServiceContract attribute. The other,
OperationBehavior, can be applied to methods in a service class that are also marked with the
OperationContract attribute.
The
ServiceBehavior attribute has various properties that affect the behavior of the service as a whole. For example, a property called
ConcurrencyMode can be used to control concurrent access to the service. If set to
Single, Indigo will deliver only one client request at a time to this service, i.e., the service will be single-threaded. If this property is set to
Multiple, Indigo will deliver more than one client request at a time to the service, each running on a different thread. Similarly,
ServiceBehavior's
InstanceMode property can be used to control how instances of a service are created and destroyed. If
InstanceMode is set to
PerCall, a new instance of the service will be created to handle each client request, then destroyed when the request is completed. If it's set to
PrivateSession, however, the same instance of the service will be used to handle all requests from a particular client.
Suppose, for example, that its creator decided that the
Calculator class should be multi-threaded and use the same instance for each call from a particular client. The class's definition would then look like this:
Similarly, properties on the
OperationBehavior attribute allow controlling the impersonation behavior of the method that implements this operation, its transactional requirements (described later), and other things.
Messaging Options
The simple examples shown in this article assume a synchronous remote procedure call (RPC) approach to client/service interaction. Indigo supports this option, but it's not the only choice. SOAP is a message-oriented protocol, which means that it can support a variety of programming models. In fact, Indigo supports several possibilities, including the following:
- Traditional RPC, with blocking calls carrying lists of typed parameters;
- Asynchronous RPC, with non-blocking calls carrying lists of typed parameters;
- Traditional messaging, with non-blocking calls carrying a single message parameter;
- Message-based RPC, with blocking calls carrying a single message parameter.
And even though the great majority of distributed applications require it, the SOAP specification says nothing about reliability. One common way to ensure reliability is to use SOAP only in point-to-point scenarios, relying on TCP to guarantee delivery of requests and responses. This is sufficient in some cases, and it's what's done when the BasicProfileHttpBinding is used.
Yet there are plenty of cases for which this isn't enough. What if a service is accessed through multiple SOAP intermediaries, for example? The reliability guarantees provided by TCP aren't enough in this case to ensure end-to-end reliability. To address this problem, Indigo implements the WS-ReliableMessaging specification. By choosing a binding such as WsHttpBinding, which uses WS-ReliableMessaging, a service and its client can guarantee reliable end-to-end communication even through multiple SOAP intermediaries.
Security
Exposing services on a network, even an internal network, usually requires some kind of security. How can the service be certain of its client's identity? How can messages sent to and from a service be kept safe from malicious changes and prying eyes? And how can access to a service be limited to only those authorized to use it? Without some solution to these problems, it's too dangerous to expose many kinds of services. Yet building secure applications can get complicated. Ideally, there should be straightforward ways to address common security scenarios, along with more fine-grained control for applications that need it.
To achieve this, Indigo provides the core security functions of authentication, message integrity, message confidentiality, and authorization. Indigo's approach to the first three of these relies primarily on bindings, and a developer's choices include the following:
- Choose a standard binding that supports security. Applications that need only transport-based security, for example, can use a binding such as BasicProfileHttpsBinding. This approach is sufficient for requests that go directly from a client to a service without traversing any intermediaries, such as HTTP proxies or other SOAP nodes. Applications that require end-to-end security for messages that go through multiple SOAP intermediaries can instead use a binding that supports WS-Security, such as WsHttpBinding.
- Choose a standard binding that supports security, then customize it by changing one or more of its default values. For example, the authentication mechanism used by a binding such as WsHttpBinding can be changed if desired.
- Create a custom binding that provides exactly the security features a developer needs. Doing this isn't for the faint of heart, but it can be the right solution for some advanced scenarios.
- Choose a standard binding that provides no support for security, such as BasicProfileHttpBinding. While using no security is generally a risky thing to do, it can still be the best option in some situations.
An Indigo service can also control which clients are authorized to use its services. For the most part, Indigo just supports existing authorization mechanisms in the .NET Framework. A service can use the standard
PrincipalPermission attribute, for example, to define who is allowed to access it.
Letting developers build secure applications without exposing them to overwhelming complexity has proven to be challenging in the past. By providing both a straightforward approach for the most common cases and fine-grained control for more complex situations, Indigo aims at hitting this target in a usable and effective way.
Transactions
Handling transactions is an important aspect of building many kinds of business logic. Yet using transactions in a service-oriented world can be problematic. Distributed transactions assume a high level of trust among the participants, and so it often isn't appropriate for a transaction to span a service boundary. Still, there are situations where combining transactions and services makes good sense, and so Indigo includes support for this important aspect of application design.
Transactions in the .NET Framework 2.0
The transaction support in Indigo builds on enhancements provided in version 2.0 of the .NET Framework. This forthcoming release includes System.Transactions, a new namespace focused solely on controlling transactional behaviors. Developers will most often use the services of System.Transactions in concert with an execution context, a construct that's new in version 2.0 of the .NET Framework. An execution context allows specifying common information, such as a transaction, that applies to all code contained within a defined scope. Here's an example of how an application can use this approach to group a set of operations into a single transaction:
Required for the new
TransactionScope, as this example does, means that this code will always run as part of a transaction: joining its caller's transaction if one exists, creating a new one if it doesn't. As in Enterprise Services, other options can also be specified, including
RequiresNew,
Supported, and
NotSupported.
Unlike Enterprise Services and its predecessors MTS and COM+, Systems.Transactions is focused entirely on controlling transactional behavior. There's no required connection between a transaction and the internal state of an object, for example. While Enterprise Services requires an object to be deactivated when it ends a transaction, Systems.Transactions makes no such demand. Since Indigo builds on Systems.Transaction, Indigo applications are also free to manage transactions and object state independently.
Transactions in Indigo
Indigo applications can use System.Transactions explicitly, or they can control transactions using attributes that rely on System.Transactions under the covers. One option is for a method inside a class marked with the
ServiceContract attribute to wrap its work in a transaction using
TransactionScope, as just described. For example, this method might include a
using statement that establishes a transaction scope, then update two independent databases within that transaction.
A service's methods can also control transactional behavior using an attribute. Rather than explicitly using System.Transactions, a service can use the
OperationBehavior attribute described earlier. Here's an example:
using System.ServiceModel; [ServiceContract] class XactOperations { [OperationContract] public int Add(int value1, int value2) { return value1 + value2; } [OperationContract] [OperationBehavior(RequireTransaction=true, AutoCompleteTransaction=true)] int Update(int value1, int value2) { // Insert value1 and value2 into // two different databases } }
The first method in this example,
Add, doesn't use a transaction, and so its simple operation will happen just as before. But the second method,
Update, is preceded by the
OperationBehavior attribute with the
RequireTransaction property set to true. Because of this, all work done within this method will happen inside a transaction, just as if it were inside the transaction scope of the
using block shown earlier. And because the
AutoCompleteTransaction property is also specified, the transaction will automatically vote to commit if no exception is raised.
If the client invoking this method is not running inside a transaction, the
Update method will run in its own transaction—there's no other choice. But suppose the client is already part of an existing transaction when it calls
Update. Will the work done by the
Update method join the client's transaction, or will it still run inside its own independent transaction? The answer depends on whether this service can accept a transaction context passed by the client, an option controlled using the
TransactionFlowAllowed property of the
OperationContract attribute. If
TransactionFlowAllowed is not attached to a method in the service, as in the example shown above, work done within this method can never join an existing transaction. If this attribute is present, however, a method is able to join the transaction of its client.
It's also worth emphasizing that applications built on Indigo can participate in transactions that include applications running on non-Indigo platforms. For example, an Indigo application might start a transaction, update a record in a local SQL Server database, then invoke a web service implemented on a J2EE application server that updates a record in another database. If this service is transactional and the platform it's running on supports the WS-AtomicTransaction specification, both database updates can be part of the same transaction. Like security and reliable messaging, Indigo transactions work in the heterogeneous world that Web services make possible.
Queuing
Using a binding such as WsHttpBinding, an Indigo application can communicate reliably with another application built on Indigo or any other Web services platform that implements WS-ReliableMessaging. But while the technology this specification defines guarantees reliable end-to-end delivery of a SOAP message, it doesn't address message queuing. With queuing, an application sends a message to a queue rather than directly to another application. When the receiving application is ready, it can read the message from the queue and process it. Allowing this kind of interaction is useful, for example, when the sender of a message and its receiver might not be running at the same time.
Accordingly, Indigo provides support for message queuing. This support is built on top of MSMQ, which means that unlike most other aspects of Indigo, such as reliable messaging, security, and transactions, Indigo queuing doesn't interoperate directly across vendor boundaries (although an MSMQ-MQSeries bridge is available).
To use Indigo queuing, a developer creates a standard Indigo service class, marked as usual with
ServiceContract. The operations in this class's service contract have some limitations, however. In particular, they must all be marked as one-way, which means that no response is returned. This isn't surprising, since invoking a queued operation sends a message into a queue rather than to its ultimate receiver, and so waiting for an immediate response wouldn't make much sense. And like any other service class, queued Indigo applications expose endpoints. These endpoints use bindings such as NetMsmqBinding, which allows communication with other queued Indigo applications, or MsmqIntegrationBinding, which allows a queued Indigo application to interoperate with a standard MSMQ application that doesn't use Indigo. Indigo queuing also supports other traditional features of queued environments, such as dead letter queues and handling of poison messages.
Queuing is the right approach for a significant set of distributed applications. Indigo's support for this communication style allows developers to build queued applications without learning an entirely separate queuing technology.
Coexistence and Migration
Indigo represents a modern approach to creating distributed applications in the era of reliable, secure, and transactional services. A key point to understand, however, is that installing Indigo will not break any existing applications. Current code running on ASMX, .NET Remoting, and the other technologies whose functionality is subsumed by Indigo will continue to run, and so there's no requirement to move to Indigo. But for organizations with investments in current Microsoft technologies, an obvious question remains: what happens to existing code written using the technologies that preceded Indigo?
For each of the current technologies whose future is deeply affected by the advent of Indigo, developers need to understand two things: whether applications built on this technology will interoperate with applications built on Indigo, and how much work it will be to port applications from this technology to the Indigo environment. Here's a short description of how each technology addresses these issues:
- ASP.NET Web services (ASMX): Web services built with ASMX will interoperate with Indigo applications. Since ASP.NET Web services and Indigo both support standard SOAP, this shouldn't be surprising. Moving existing ASP.NET Web services code to Indigo will require some mechanical work, but should still be straightforward. The basic structure of the two technologies is quite similar, so for the most part only attributes and configuration files will need to be changed. More advanced features, however, such as SOAP Extensions, will not be directly portable to Indigo. Instead, they'll need to be re-written using the extensibility options that Indigo provides.
- .NET Remoting: applications built on .NET Remoting will not interoperate with applications built on Indigo—their wire protocols aren't compatible. Moving existing .NET Remoting code to Indigo will require some effort, but it will be possible. Anyone who's built custom .NET Remoting extensions, however, such as channels and sinks, will find that this code won't port to the new world. Similar extensions are possible in Indigo, but the interfaces for doing it don't match those in .NET Remoting.
- Enterprise Services: to allow an existing Enterprise Services application to interoperate with Indigo clients (or other web services-based software), a developer can identify exactly which interfaces in that application should be exposed. Using an Indigo-supplied tool, service contracts can then be automatically created for those interfaces and exposed via Indigo. For existing clients of Enterprise Services applications that aren't built on the .NET Framework (and for other purely COM-based clients), an Indigo moniker is provided to allow straightforward access to web services. The effort required to port existing Enterprise Services applications to run directly on Indigo will be similar to what's required to port ASMX applications. Much of the work, although not all of it, will be straightforward mechanical changes to attributes and namespaces.
- Web services Enhancements (WSE): WSE is Microsoft's tactical solution for implementing Web services applications that require some or all of the functions provided by the WS-* specs. Applications built using WSE 1.0 and WSE 2.0 won't interoperate with applications built on Indigo. Applications built on WSE 3.0, which will be shipped before Indigo is released, will interoperate with Indigo applications, however. For portability, the story is similar to the technologies already described: some amount of effort will be required to move existing code from WSE to Indigo, although this effort will be minimized for applications that use the final WSE version.
- MSMQ: because Indigo's queuing functions are built on MSMQ, queued applications built on Indigo can interoperate with queued applications built directly on MSMQ. Porting applications from the System.Messaging namespace provided with the original .NET Framework will require some work, since this earlier interface is different from what Indigo provides. Once Indigo ships, developers should use it rather than System.Messaging to create most MSMQ-based queuing applications.
Before Indigo is available, the best technology choice for distributed .NET applications that don't need queuing is probably ASMX. It's simple to use, and it also provides the smoothest migration path to Indigo. Enterprise Services can also make sense for applications that need the things it provides, such as distributed transactions, while MSMQ remains the right choice for queued applications. .NET Remoting, however, should be used primarily for communication between two application domains in the same process. ASMX is a better choice for direct application-to-application communication in most other cases.
Introducing new software always has an impact on what already exists. By providing a common foundation for building service-oriented applications, Indigo offers a simpler, more consistent platform for developers. While this change incurs some pain, the goal of Indigo's creators is to make the transition as smooth and as simple as possible.
Conclusions
Indigo represents an important evolution in how developers create software. As service-oriented applications become the norm, Indigo will be a mainstream technology for Windows software developers. Other Microsoft products will also change to take advantage of what Indigo offers. BizTalk Server, for example, will add support for Indigo as a communication option sometime following the release of BizTalk Server 2006. Because Indigo provides a standard foundation for service-oriented software, it will be the basis for a large fraction of Windows communication.
The impact of this technology will not be small. Anyone who builds distributed applications on Windows, especially applications that must interoperate with those on other platforms, should pay close attention. Indigo will significantly change their world.
About the AuthorAbout the Author
David Chappell is Principal of Chappell & Associates () in San Francisco, California. This article is drawn from his forthcoming book on Indigo, to be published by Addison-Wesley. | http://msdn.microsoft.com/library/aa480188 | crawl-003 | en | refinedweb |
The Future of ASP.NET Web Services in the Context of the Windows Communication Foundation
Craig McMurtry
Technical Evangelist
Microsoft Corporation
July 2006
Applies to:
Microsoft ASP.NET 2.0
Windows Communication Foundation
Internet Information Services (IIS)
Web services specifications
Contents
The Decision Maker's Perspective
Comparing the Technologies: Purpose
Comparing the Technologies: Standards
Comparing the Technologies: Development
Internal Architecture
Anticipating Adopting the Windows Communication Foundation: Easing Future Integration
Anticipating Adopting the Windows Communication Foundation: Easing Future Migration
Adopting the Windows Communication Foundation
Summary
Summary: This article compares ASP.NET Web services to the Windows Communication Foundation and explains what to do about existing and planned ASP.NET Web services now that the Windows Communication Foundation is soon to be released. (47 printed pages)
ASP.NET provides .NET Framework class libraries and tools for building Web services, as well as facilities for hosting those services within Internet Information Services (IIS). The Windows Communication Foundation, which was code-named Indigo, provides .NET class libraries, tools and hosting facilities for enabling software entities to communicate using any protocols, including those used by Web services. So, what are the prospects for ASP.NET Web services now that a newer, more general technology for building Web services is coming?
This paper compares the two technologies. It describes how ASP.NET Web service applications can be used together with Windows Communication Foundation applications. The paper also explains both how to prepare for migrating ASP.NET Web services to the Windows Communication Foundation, and how to actually do that migration.
For the purposes of this paper, the facilities that ASP.NET provides for building Web services are considered separately from the Web Services Enhancements for Microsoft .NET (WSE). The prospects for applications developed using WSE will be examined elsewhere.
The Decision Maker's Perspective
The Windows Communication Foundation is scheduled to be released in the second half of 2006. It has several important advantages relative to ASP.NET Web services that any organization using that earlier technology needs to consider.
Whereas the ASP.NET Web services tools are solely for building Web services, the Windows Communication Foundation provides tools for use in any circumstance where software entities must be made to communicate with one another. That should reduce the number of technologies that developers are required to know in order to accommodate different software communication scenarios, which should in turn reduce the cost of software development resources, as well as the time to complete software development projects.
Even for Web service development projects, the Windows Communication Foundation supports more Web service protocols than ASP.NET Web services support. Those protocols provide for more sophisticated solutions involving, amongst other things, reliable sessions and transactions.
The Windows Communication Foundation supports more protocols for transporting messages than the ASP.NET Web services support. ASP.NET Web services only support sending messages via the Hypertext Transfer Protocol (HTTP). The Windows Communication Foundation supports sending messages via HTTP, as well as the Transmission Control Protocol (TCP), named pipes, and Microsoft Message Queuing (MSMQ). More important, the Windows Communication Foundation can be readily extended to support additional transport protocols. Therefore, software developed using the Windows Communication Foundation can be readily adapted to work together with a wider variety of other software, thereby increasing the potential return on the investment in it.
The Windows Communication Foundation provides much richer facilities for deploying and managing applications than ASP.NET Web services provides. In addition to a configuration system, which ASP.NET also has, the Windows Communication Foundation offers a configuration editor, activity tracing from senders to receivers and back via any number of intermediaries, a trace viewer, message logging, a vast number of performance counters, and support for Windows Management Instrumentation. This rich set of administrative tools should serve to reduce operational costs, the risk of failures, and actual downtime.
Given these potential benefits of the Windows Communication Foundation relative to ASP.NET Web services, organizations that are using, or are considering using ASP.NET Web services have several options:
- Simply continue to use ASP.NET Web services, and forego the benefits proffered by the Windows Communication Foundation. Under Microsoft's current support lifecycle policy, mainstream support for ASP.NET Web services will be provided until at least the year 2011, and extended support will be provided until at least 2016. So, there is no great risk in continuing to use ASP.NET Web services.
- Keep using ASP.NET Web services with the intention of adopting the Windows Communication Foundation at some time in the future. This paper will explain how to maximize the prospects for being able to use new ASP.NET Web service applications together with future Windows Communication Foundation applications. It will also explain how to build new ASP.NET Web services so as to make it easier to migrate them to the Windows Communication Foundation. However, if securing the services is important, or reliability or transaction assurances are required, or if it appears that custom management facilities will have to be constructed, then the decision to defer adopting the Windows Communication Foundation is probably mistaken. It is designed for precisely such scenarios, and production licenses for the technology are already available.
- Adopt the Windows Communication Foundation for new development, while continuing to maintain their existing ASP.NET Web service applications. This choice is very likely the optimal one. It yields the benefits of the Windows Communication Foundation, while sparing the cost of modifying the existing applications to use it. In this scenario, new Windows Communication Foundation applications can co-exist with existing ASP.NET applications. Also, new Windows Communication Foundation applications will be able to use existing ASP.NET Web services, and the Windows Communication Foundation can even be used to program new operational capabilities into existing ASP.NET applications by virtue of the Windows Communication Foundation's ASP.NET compatibility mode.
- Adopt the Windows Communication Foundation and migrate existing ASP.NET Web service applications to the Windows Communication Foundation. An organization might choose this option in order to eliminate any requirement for their developers to know about ASP.NET Web services. That would not be a good reason for this choice, though, because the prospect of eliminating support for any technologies other than the latest ones is probably chimerical. The only good reasons for migrating would be to enhance the existing applications with features provided by the Windows Communication Foundation, or to reproduce the functionality of existing ASP.NET Web services within new, more powerful Windows Communication Foundation applications. This paper will explain how to accomplish the migration.
Comparing the Technologies: Purpose
The ASP.NET Web services technology was developed for building applications that send and receive messages via the Simple Object Access Protocol (SOAP) over HTTP. The structure of the messages can be defined using XML Schema, and a tool is provided to facilitate serializing the messages to and from .NET objects. The technology can automatically generate metadata to describe Web services in the Web Services Description Language (WSDL), and a second tool is provided for generating clients for Web services from the WSDL.
The Windows Communication Foundation is for enabling .NET applications to exchange messages with other software entities. SOAP is used by default, but the messages can be in any format, and conveyed via any transport protocol. The structure of the messages can be defined using XML Schema, and there are various options for serializing the messages to and from .NET objects. The Windows Communication Foundation can automatically generate metadata to describe applications built using the technology in WSDL, and it also provides a tool for generating clients for those applications from the WSDL.
Comparing the Technologies: Standards
For a list of the standards supported by ASP.NET Web services, see XML Web Services Created Using ASP.NET.
See Web Services Protocols Supported in WCF for a more extensive list of standards supported by the Windows Communication Foundation.
Comparing the Technologies: Development
ASP.NET Compatibility Mode
The Windows Communication Foundation has an ASP.NET compatibility mode option by which certain Windows Communication Foundation applications can be programmed and configured like ASP.NET Web services, and will mimic their behavior. How to opt for ASP.NET compatibility mode is explained below, and details of the exact effects of that option will be provided.
Data Representation
The development of a Web service with ASP.NET typically begins with defining any complex data types the service is to use. ASP.NET relies on the System.Xml.Serialization.XmlSerializer to translate data represented by .NET objects into XML for transmission to or from a service, and to translate data received as XML into .NET objects. So, defining the complex data types that an ASP.NET service is to use requires the definition of .NET classes that the System.Xml.Serialization.XmlSerializer can serialize to and from XML. Such classes can be written manually, of course, or generated from definitions of the types in XML Schema using the command-line XML Schemas/Data Types Support Utility, xsd.exe.
These are the key things to know about defining .NET classes that the System.Xml.Serialization.XmlSerializer will be able to serialize to and from XML:
- Only the public fields and properties of .NET objects will be translated into XML.
- Instances of collection classes can be serialized into XML only if the classes implement either the IEnumerable or ICollection interface.
- As a corollary, classes that implement the System.Collections.IDictionary interface, like System.Collections.Hashtable, cannot be serialized into XML.
- The great many attribute types in the System.Xml.Serialization namespace can be added to a .NET class and its members to control exactly how instances of the class are represented in XML.
Windows Communication Foundation application development usually also begins with the definition of complex types. The Windows Communication Foundation can be made to use the same .NET types as ASP.NET Web services. It offers a better alternative, though.
The System.Runtime.Serialization.DataContract and System.Runtime.Serialization.DataMember attributes of the Windows Communication Foundation's System.Runtime.Serialization assembly can be added to .NET types to indicate that instances of the type are to be serialized into XML, and which particular fields or properties of the type are to be serialized. All three of the following examples are valid:
/ System.Runtime.Serialization.DataContract attribute signifies that zero or more of a type's fields or properties are to be serialized, while the System.Runtime.Serialization.DataMember attribute indicates that a particular field or property is to be serialized. The System.Runtime.Serialization.DataContract attribute can be applied to a class or struct. The System.Runtime.Serialization.DataMember attribute can be applied to a field or a property, and the fields and properties to which the attribute is applied can be either public or private. Instances of types that have System.Runtime.Serialization.DataContract attributes are referred to as data contracts in the argot of the Windows Communication Foundation. They are serialized into XML using the Windows Communication Foundation's System.Runtime.Serialization.DataContractFormatter.
How do the System.Runtime.Serialization.DataContractFormatter and the System.Runtime.Serialization.DataContract and System.Runtime.Serialization.DataMember attributes differ from the System.Xml.Serialization.XmlSerializer and the various attributes of the System.Xml.Serialization namespace? There are many important differences.
- The System.Xml.Serialization.XmlSerializer and the attributes of the System.Xml.Serialization namespace are designed to allow one to map .NET types to any valid type defined in XML Schema, and so they provide for very precise control over how a .NET type is represented in XML. The System.Runtime.Serialization.DataContractFormatter and the System.Runtime.Serialization.DataContract and System.Runtime.Serialization.DataMember attributes provide very little control over how a .NET type is represented in XML. One can only specify the namespaces and names used to represent the type and its fields or properties in the XML, and the sequence in which the fields and properties appear in the XML:
[DataContract( Namespace="urn:Woodgrove System.Runtime.Serialization.DataContractFormatter.
- By not permitting much control over how a .NET type is to be represented in XML, the serialization process becomes highly predictable for the System.Runtime.Serialization.DataContractFormatter, and, thereby, more amenable to optimization. So, a practical benefit of the design of the System.Runtime.Serialization.DataContractFormatter is better performance, approximately ten percent better performance.
- Compare the following type, which has attributes for serialization with the System.Xml.Serialization.XmlSerializer,
with this version, which has attributes for use with the System.Runtime.Serialization.DataContractFormatter:
The attributes for use with the System.Xml.Serialization.XmlSerializer do not indicate which fields or properties of the type will be serialized into XML, whereas the System.Runtime.Serialization.DataMember attribute for use with the System.Runtime.Serialization.DataContractFormatter shows explicitly which fields or properties will be serialized. Therefore, one can say that data contracts are explicit contracts about the structure of the data that an application is to send and receive.
- Whereas the System.Xml.Serialization.XmlSerializer can only translate the public members of a .NET object into XML, the System.Runtime.Serialization.DataContractFormatter can translate the members of .NET objects into XML regardless of the access modifiers of those members.
- Partly as a consequence of being able to serialize the non-public members of types into XML, the System.Runtime.Serialization.DataContractFormatter has fewer restrictions on the variety of .NET types that it can serialize into XML. In particular, it can translate into XML types like System.Collections.Hashtable that implement the Systems.Collections.IDictionary interface. Generally, the System.Runtime.Serialization.DataContractFormatter is much more likely to be able to serialize the instances of any pre-existing .NET type into XML without one having to either modify the definition of the type or develop a wrapper for it.
- However, another consequence of the System.Runtime.Serialization.DataContractFormatter being able to access the non-public members of a type is that it requires full trust, whereas the System.Xml.Serialization.XmlSerializer does not.
- The System.Runtime.Serialization.DataContractFormatter incorporates some support for versioning.
- The System.Runtime.Serialization.DataMember attribute System.Runtime.Serialization.IExtensibleDataObject interface, one can allow the System.Runtime.Serialization.DataContractFormatter to pass members defined in newer versions of a data contract through applications with earlier versions of the contract.
Despite all of those differences,, this class, which has attributes for use with both of the serializers, will be translated into semantically identical XML by the System.Xml.Serialization.XmlSerializer and by the System.RuntimeSerialization.DataContractFormatter:
The software development kit that accompanies the Windows Communication Foundation includes a command-line tool called the Service Model Metadata Tool, svcutil.exe. Like the xsd.exe tool used with ASP.NET Web services, svcutil.exe can generate definitions of .NET data types from XML Schema. Those .NET data types will be data contracts if the System.Runtime.Serialization.DataContractFormatter can emit XML in the format defined by the XML Schema; otherwise, they will be intended for serialization using the System.Xml.Serialization.XmlSerializer. The tool, svcutil.exe, can also be made to generate XML Schema from data contracts using its /dataContractOnly switch.
Note that although ASP.NET Web services use the System.Xml.Serialization.XmlSerializer, and the Windows Communication Foundation's ASP.NET compatibility mode makes Windows Communication Foundation services mimic the behavior of ASP.NET Web services, the ASP.NET compatibility option does not restrict one to using the System.Xml.Serialization.XmlSerializer. One can still use the System.Runtime.Serialization.DataContractFormatter with services running in the ASP.NET compatibility mode.
Service Development
To develop a service using ASP.NET, it has been customary to simply add the System.Web.Services.WebService attribute to a class, and the System.Web.Services.WebMethod attribute to any of that class' methods that are to be operations of the service:
ASP.NET 2.0 introduced the option of adding the System.Web.Services.WebService and System.Web.Services.WebMethod attributes to an interface rather than to a class, and writing a class to implement the interface:
Using this option is to be preferred, because the interface with the System.Web.Services.WebService attribute constitutes a contract for the operations performed by the service that can be reused with various classes that might implement that same contract in different ways..
The service contract is usually defined first, by adding System.ServiceModel.ServiceContract and System.ServiceModel.OperationContract attributes to a .NET interface:
The System.ServiceModel.ServiceContract attribute specifies that the interface defines a Windows Communication Foundation service contract, and the System.ServiceModel.OperationContract attribute indicates which, if any, of the methods of the interface define operations of the service contract.
Once a service contract has been defined, it is implemented in a class, simply by having the class implement the interface by which the service contract is defined:
A class that implements a service contract is referred to as a service type in the argot of the Windows Communication Foundation.
The next step is to associate an address and a binding with a service type. That is typically done in a configuration file, either by editing the file directly, or by using a configuration editor provided with the Windows Communication Foundation. Here is an example of a configuration file.
The binding specifies the set of protocols for communicating with the application. There are a number of predefined bindings that represent common options:
The predefined binding, System.ServiceModel.BasicHttpBinding, incorporates the set of protocols supported by ASP.NET Web services.
Custom bindings for Windows Communication Foundation applications are easily defined as collections of the binding element classes that the Windows Communication Foundation uses to implement individual protocols. New binding elements can be written to represent additional protocols.
The internal behavior of service types can be adjusted using the properties of a family of classes called behaviors. Here, the System.ServiceModel.ServiceBehavior class is used to specify that the service type is to be multithreaded:
Some behaviors, the ones with properties that programmers would want to set, like System.ServiceModel.ServiceBehavior, are attributes. Others, the ones with properties that administrators would want to set, can be modified in the configuration of an application.
In programming service types, frequent use is made of the System.ServiceModel.OperationContext class. Its static Current property provides access to information about the context in which an operation is executing. Thus, System.ServiceModel.OperationContext is similar to both the System.Web.HttpContext and System.EnterpriseServices.ContextUtil classes.
Hosting
ASP.NET Web services are compiled into a class library assembly. A file called the service file is provided that has the extension .asmx and contains an @ WebService directive identifying the class containing the code for the service, and the assembly in which it is located:
The service file is copied into an ASP.NET application root in IIS, and the assembly is copied into the \bin subdirectory of that application root. The application is then accessible via the uniform resource locator (URL) of the service file in the application root.
Aaron Skonnard has explained how to use the HttpListener class provided by the .NET Framework 2.0 to host ASP.NET Web services outside of IIS, in any .NET application. However, Skonnard himself describes the effort involved as "non-trivial."
Windows Communication Foundation services can readily be hosted within IIS 5.1 or 6.0, the Windows Activation Service (WAS) that is to be provided as part of IIS 7, and within any .NET application. To host a service in IIS 5.1 or 6.0, the service must use HTTP as the communications transport protocol.
To host a service within IIS 5.1 or 6.0, or within WAS one follows these steps:
- Compile the service type into a class library assembly.
- Create a service file with a .svc extension with an @ ServiceHost directive to identify the service type:
- Copy the service file into a virtual directory, and the assembly into the \bin subdirectory of that virtual directory.
- Copy the configuration file into the virtual directory, and name it Web.config.
The application is then accessible via the URL of the service file in the application root.
To host a Windows Communication Foundation service within a .NET application, compile the service type into a class library assembly referenced by the application, and program the application to host the service using the Windows Communication Foundation's System.ServiceModel.ServiceHost class. Here is an example of the simple Windows Communication Foundation System.ServiceModel.ServiceHost. These addresses are referred to as base addresses.
The address provided for any endpoint of a Windows Communication Foundation service is an address relative to a base address of the endpoint's host. The host can have one base address per communication transport protocol. The address of an endpoint is relative to whichever of the base addresses of the host is the base address for the communication transport protocol of the endpoint. In the example of a configuration file shown above, the System.ServiceModel.BasicHttpBinding selected for the endpoint uses HTTP as the transport protocol, so the address of the endpoint, EchoService, is relative to the host's HTTP base address. In the case of the host in the example above, the Windows Communication Foundation's ASP.NET compatibility mode option. Turning that option on requires two steps.
- The programmer must add the System.ServiceModel.AspNetCompatbilityRequirements attribute to the service type, specifying that ASP.NET compatibility mode is either allowed or required:
- The administrator must configure the application to use the ASP.NET compatibility mode:
Windows Communication Foundation one from having to modify clients that have been configured to use the URLs of .asmx service files when modifying a service to use the Windows Communication Foundation.
Client Development
Clients for ASP.NET Web services are generated using the command-line tool, wsdl.exe, providing the URL of the .asmx file as input. The corresponding tool provided by the Windows Communication Foundation is svcutil.exe. It generates a code module with the definition of the service contract and the definition of a proxy svcutil.exe tool can provide for either pattern. It provides for the synchronous pattern by default. If the tool is executed with the /async switch, then the generated code provides for the asynchronous pattern.
There is no guarantee that names in the proxy classes generated by ASP.NET's wsdl.exe tool will, by default, match the names in proxy classes generated by the Windows Communication Foundation's svcutil.exe tool. In particular, the names of the properties of classes that have to be serialized using the System.Xml.Serialization.XmlSerializer are, by default, given the suffix Property in the code generated by the svcutil.exe tool, which was not the case with the wsdl.exe tool.
Message Representation
The headers of the SOAP messages sent and received by ASP.NET Web services can be customized. A class is derived from System.Web.Services.Protocols to define the structure of the header, and then the System.Web.Services.SoapHeader attribute Windows Communication Foundation provides the attributes, System.ServiceModel.MessageContract, System.ServiceModel.MessageHeader, and System.ServiceModel.MessageBody merely implied by the code of an ASP.NET Web service. Also, in the ASP.NET syntax, message headers are represented as properties of the service, such as the ProtocolHeader property in the example above, whereas in the Windows Communication Foundation syntax, they are more accurately represented as properties of messages. Also, the Windows Communication Foundation allows message headers to be added to the configuration of endpoints:
That option allows one to avoid any reference to infrastructural protocol headers in the code for a client or service: the headers get added to messages simply by virtue of how the endpoint is configured.
Service Description
Issuing an HTTP GET request for the .asmx file of an ASP.NET Web service with the query wsdl causes ASP.NET to generate WSDL to describe the service. It will return System.Web.Services.WebServiceBinding attribute:
The WSDL that ASP.NET generates for a service can be customized. Customizations are made by creating a subclass of System.Web.Services.Description.ServiceDescriptionFormatExtension to add items to the WSDL.
Issuing an HTTP GET request with the query wsdl for the .svc file of a Windows Communication Foundation service with an HTTP endpoint hosted within IIS 51, 6.0 or WAS will cause the Windows Communication Foundation to respond with WSDL to describe the service. Issuing an HTTP GET request with the query wsdl to the HTTP base address of a service hosted within a .NET application will have the same effect.
However, the Windows Communication Foundation will also respond to WS-MetadataExchange requests with WSDL that it generates to describe a service. ASP.NET Web services do not have built-in support for WS-MetadataExchange requests.
The WSDL that the Windows Communication Foundation generates can be extensively customized. The System.ServiceModel.ServiceMetadataBehavior class provides some facilities for customizing the WSDL, and one can develop implementations of System.ServiceModel.Design.IWsdlExporter to take complete control. The Windows Communication Foundation can also be configured to not generate WSDL, but rather to use a static WSDL file at a given URL:
Exception Handling
In ASP.NET Web services, unhandled exceptions are returned to clients as SOAP faults. One can also explicitly throw instances of the System.Web.Services.Protocols.SoapException class, and thereby have more control over the content of the SOAP fault that gets transmitted to the client.
In Windows Communication Foundation services, unhandled exceptions are not returned to clients as SOAP faults to prevent sensitive information being inadvertently exposed through the exceptions. A configuration setting is provided to have unhandled exceptions returned to clients for the purpose of debugging.
To deliberately return SOAP faults to clients, Windows Communication Foundation programmers can throw instances of the generic type, System.ServiceModel.FaultException<T>, where T should be a data contract. The programmers can also add System.ServiceModel.FaultContract attributes to operations to specify the faults that an operation might yield:
Doing so will result in the possible faults being advertised in the WSDL for the service, allowing client programmers to anticipate precisely which faults could result from an operation, and write the appropriate catch statements:
State Management
The class used to implement an ASP.NET Web service may be derived from System.Web.Services.WebService:
In that case, the class can be programmed to use the System.Web.Services.WebService base class' Context property to access a System.Web.HttpContext object. The System.Web.HttpContext object can be used to update and retrieve application state information via its Application property, and can be used to update and retrieve session state information via its Session property.
ASP.NET provides considerable control over where the session state information accessed via the Session property of the System.Web.HttpContext is actually stored. It may be stored in cookies, in a database, in the memory of the current server, or in the memory of a designated server. The choice is made in the service's configuration file.
The Windows Communication Foundation provides extensible objects for state management. Extensible objects are objects that implement System.ServiceModel.IExtensibleObject<T>. The most important extensible objects are System.ServiceModel.ServiceHostBase and System.ServiceModel.InstanceContext. The former allows one to maintain state that all of the instances of all of the service types on the same host can access, while the latter allows one to maintain state that can be accessed by any code executing within the same instance of a service type.
Here, the service type, TradingSystem, has a System.ServiceModel.ServiceBehavior attribute that specifies that all calls from the same proxy instance will be routed to the same instance of the service type.
The class, DealData, defines state that can be accessed by any code executing in the same instance of a service type:
In the code of the service type that implements one of the operations of the service contract, a DealData state object is added to the state of the current instance of the service type:
That state object can then be retrieved and modified by the code implementing another of the service contract's operations:
Whereas ASP.NET provides considerable control over where state information in the System.Web.HttpContext class is actually stored, the Windows Communication Foundation, at least in its initial version, provides no control over where extensible objects are stored. That constitutes the very best reason for selecting the ASP.NET compatibility mode for a Windows Communication Foundation service. If configurarable state mangement is imperative, then opting for the ASP.NET compatibility mode will allow one to use the facilities of the System.Web.HttpContext class exactly as they are used in ASP.NET, and also to configure where state information managed via the System.Web.HttpContext class is stored.
Security
The options for securing ASP.NET Web services are mostly just those for securing any IIS application. Because Windows Communication Foundation applications can be hosted not only within IIS but also within any .NET executable, the options for securing Windows Communication Foundation applications had to be made independent from the facilities of IIS. However, the facilities provided for ASP.NET Web services are also available for Windows Communication Foundation services running in ASP.NET compatibility mode.
Security: Authentication
IIS provides facilities for controlling access to applications by which one can select either anonymous access or a variety of modes of authentication: Windows Authentication, Digest Authentication, Basic Authentication, and .NET Passport Authentication. The Windows Authentication option can be used to control access to ASP.NET Web services. However, when Windows Communication Foundation applications are hosted within IIS, IIS must be configured to permit anonymous access to the application, so that authentication can be managed by the Windows Communication Foundation itself, which does support Windows authentication among various other options. The other options that are built-in include username tokens, X.509 certificates, SAML tokens, and InfoCard, but custom authentication mechanisms can also be defined.
In ASP.NET 2.0, the System.Web.HttpContext class has a Profile property by which information about the authenticated user can be automatically retrieved from a store via a System.Web.Profile.Provider class that knows how to read that information from a particular kind of store. This ASP.NET 2.0 mechanism is not supported in the Windows Communication Foundation except in ASP.NET compatibility mode, although a custom behavior could certainly use System.Web.Profile.Provider classes to retrieve profile information.
Security: Impersonation
ASP.NET provides an identity element by which an ASP.NET Web service can be made to impersonate a particular user or whichever user's credentials were provided with the current request. That element can be used to configure impersonation in Windows Communication Foundation applications running in ASP.NET compatibility mode.
The Windows Communication Foundation's configuration system provides its own identity element for designating a particular user to impersonate. Also, Windows Communication Foundation clients and services can be independently configured for impersonation. Clients can be configured to impersonate the current user when they transmit requests:
Service operations can be configured to impersonate whichever user's credentials were provided with the current request:
Security: Authorization using Access Control Lists
Access Control Lists (ACLs) can be used to restrict access to .asmx files. However, ACLs on Windows Communication Foundation simple Windows Communication Foundation application. Here is a sample configuration for a Windows Communication Foundation application that shows how the use of an ASP.NET Role Provider is an option selected by means of the System.ServiceModel.ServiceAuthorization behavior:
<system.serviceModel> <services> <service name="Service.ResourceAccessServiceType" behaviorConfiguration="ServiceBehavior"> <endpoint address="ResourceAccessService" binding="wsHttpBinding" contract="Service.IResourceAccessContract"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceAuthorization principalPermissionMode="UseAspNetRoles"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
Security: Claims-based Authorization
One of the most important innovations of the Windows Communication Foundation is its thorough support for authorizing access to protected resources based on claims. Claims consist of a type, a right and a value. Consider simply possession: the driver possesses that date of birth but cannot, for example, alter it. Claims-based authorization subsumes role-based authorization, because roles are simply a type of claim.
Authorization based on claims is accomplished by comparing a set of claims to the access requirements of the operation, and, depending on the outcome of that comparison, granting or denying access to the operation. In the Windows Communication Foundation, one can specify a class to use to execute claims-based authorization, once again by assigning a value to the ServiceAuthorizationManager property of System.ServiceModel.Description.ServiceAuthorizationBehavior:
Classes used to execute claims-based authorization must derive from System.ServiceModel.ServiceAuthorizationManager, which has just one method to override, AccessCheck(). The Windows Communication Foundation calls that method whenever an operation of the service is invoked, providing a System.ServiceModel.OperationContext object, which has the claims for the user in its ServiceSecurityContext.AuthorizationContext property. Thus, the Windows Communication Foundation will have already done the work of assembling claims about the user from whatever security token the user provided for authentication, leaving the simple of task of evaluating whether those claims suffice for the operation in question.
That the Windows Communication Foundation will automatically assemble Windows Communication Foundation applications hosted within IIS. However, Windows Communication Foundation applications hosted outside of IIS can also be configured to use a secure transport protocol. More important, Windows Communication Foundation one to specify the culture for individual services. The Windows Communication Foundation does not support that configuration setting except in ASP.NET compatibility mode. To localize a Windows Communication Foundation service that does not use ASP.NET compatibility mode, one would compile the service type into culture-specific assemblies, and have separate culture-specific endpoints for each culture-specific assembly.
Internal Architecture
ASP.NET Web Services
In the most recent implementation of ASP.NET, an HTTP request is received in the form of a System.Web.HttpWorkerRequest object from an implementation of HTTP in the Windows kernel that is called http.sys. The System.Web.HttpWorkerRequest object is received by a System.Web.HttpRuntime object that populates the System.Web.HttpContext object from the data in the System.Web.HttpWorkerRequest object. The request is incorporated in the System.Web.HttpContext object as its Request property, which is a System.Web.HttpRequest object.
By default, a System.Web.HttpRequest object that represents a HTTP POST request addressed to an .asmx file is passed to an object that implements the System.Web.IHttpHandler interface (Skonnard 2003, 2004). That object is created using the System.Web.Services.Protocols.WebServiceHandlerFactory class, and may be referred to as the ASP.NET Web service request handler. When the Windows Communication Foundation is configured for ASP.NET compatibility mode, it provides an implementation of the System.Web.IHttpHandler that mimics the behavior of the ASP.NET Web service request handler.
The ASP.NET Web service request handler must do at least four things. First, it must pass any SOAP message incorporated in the HTTP request to instances of any SOAP E\extensions provided by the developer (Meier, Vasireddy, Babbar, and Mackman 2004). Second, it has to determine which method of the class referred to in the .asmx file is to be invoked to process the request. Third, it must have the request de-serialized into instances of the types that the method expects as parameters. Fourth, it has to actually invoke the method, passing it the parameters it has de-serialized from the request.
SOAP extensions are types derived from System.Web.Services.Protocols.SoapExtension. They are used to access or modify SOAP messages in requests before the messages are passed on to any method of the class referred to in the .asmx file for processing. They can also access and modify response messages, and can be deployed not only on servers but also on clients. A common use for SOAP extensions is to log messages. Another is for encrypting them. SOAP extensions can be applied to all of the services deployed on a machine, or to individual services, or, by using a custom System.Web.Services.SoapExtension attribute, to particular operations of a service.
To determine which method of a class to invoke to process a request, the ASP.NET Web service request handler uses, by default, the SOAPAction header in the request. By default, the request handler expects the SOAPAction HTTP header to consist of the namespace of the service followed by the name of the operation. The default namespace of a service is, and the default name for an operation is the name of the method that defines it. So, in processing this HTTP request,
POST /asmxservice/service.asmx HTTP/1.1 User-Agent: Mozilla/4.0 Content-Type: text/xml; charset=utf-8 SOAPAction: "" Host: localhost Content-Length: 314 Expect: 100-continue Connection: Keep-Alive <?xml version="1.0" encoding="UTF-8" ?> <soap:Envelope xmlns: <soap:Body> <Echo xmlns=""> <input>Hello, World </input> </Echo> </soap:Body> </soap:Envelope>
the request handler expects that the class referred to by the @_WebService directive in the file located at defines a service with the default namespace that has an operation called Echo. It also expects, by default, that the operation is implemented by a method of the class that is called Echo, and the handler will attempt to invoke that method to process the request. All of this behavior can be customized:
One can have the request handler not use the SOAPAction HTTP header, but rather use the fully-qualified element name of the body element of the SOAP message to identify which method to invoke. In the foregoing example of an HTTP request, the body element is,
and its fully-qualified element name is. Since that name is the same as the SOAPAction HTTP header, it should be apparent how the ASP.NET Web service request handler would use the name to determine how to route the message. To have the request handler use the fully-qualified name of the body element of the SOAP message rather than the SOAPAction HTTP header, one applies the System.Web.Services.Protocols.SoapDocumentService attribute to the class that implements the service, and specifies RequestElement as the routing style, thus:
Also, one can use the RequestElementName parameter of the System.Web.Services.Protocols.SoapDocumentMethod attribute to make the local name of the body element of the SOAP message different from the name of the method:
Then the ASP.NET Web service request handler will match the local name of the body element of the SOAP message to the value provided for the RequestElementName parameter of the System.Web.Services.Protocols.SoapDocumentMethod attribute applied to the method, rather than matching the local name of the body element directly to the name of the method.
The namespace of the service can be modified from the default using the Namespace parameter of the System.Web.Services.WebService attribute:
Although the value of this parameter is shown here being modified for a System.Web.Services.WebService attribute applied to an interface, regrettably, due to a bug, altering the value of the parameter actually has no effect when the attribute is applied to an interface rather than a class.
The name of an operation can be made different from the name of the method that implements it. That is done by specifying a value for the MessageName parameter of the System.Web.Services.WebMethod attribute:
This facility can be used to distinguish polymorphic methods for the ASP.NET Web service request handler:
One can add the System.Web.Services.Protocols.SoapDocumentMethod attribute to a method and provide a value for the Action parameter of the attribute, like so:
For any such method, the ASP.NET Web service request handler will simply match the SOAPAction HTTP header to the value specified for the Action parameter of the SoapDocumentMethod attribute, rather than attempting to identify the target method by decomposing the SOAPAction header into the namespace of the service together and the operation name.
Once the ASP.NET Web service request handler has identified which method of the class referred to in the .asmx file is to be invoked to process the request, the request must be de-serialized into instances of the types the method expects as parameters. It uses the System.Xml.Serialization.XmlSerializer to do that.
By default, the request handler assumes that the SOAP message incorporated in the request conforms to what the WSDL 1.1 specification calls the document style. A message in that style has the elements of its body structured in accordance with arbitrary schemas, and the request handler relies on the System.Xml.Serialization.XmlSerializer to de-serialize those elements into .NET types. In the case of this operation,
the ASP.NET Web service request handler would anticipate document-style SOAP messages like this one,
<?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns: <soap:Body> <tns:PlaceOrders> <s1:PurchaseOrder> <s1:Date>2006-01-31</s1:Date> <s1:LineItems> <s1:LineItem> <s1:ItemNumber>1</s1:ItemNumber> <s1:Quantity>1</s1:Quantity> <s1:UnitPrice>50.00</s1:UnitPrice> </s1:LineItem> </s1:LineItems> <s1:Total>50.00</s1:Total> </s1:PurchaseOrder> </tns:PlaceOrders> </soap:Body> </soap:Envelope>
wherein the names of the elements identify the names of the types into which they are to be de-serialized. This mechanism can also be customized:
- How the names of types are mapped to constituents of the SOAP message can be customized by applying the attributes, System.Xml.XmlElement and System.Xml.XmlAttribute, to the parameters of a method. The System.Xml.XmlElement attribute controls the name of the XML element that the ASP.NET Web service request handler will expect to de-serialize a type:
If the attribute, System.Xml.XmlAttribute, has been added to a parameter, then the request handler will be expecting to deserialize that parameter from an XML attribute rather than an XML element.
- One can alter the ASP.NET Web service request handler's default expectation that the SOAP message incorporated in the request conforms to the document style, and instead have it expect the message to be in what the WSDL 1.1 specification refers to as the RPC style. That can be done for an entire service using the SoapRpcService attribute, or for individual methods using the SoapRpcMethod attribute. Use of these options is not recommended, however, because using the RPC style is not included in the WS-I Basic Profile 1.1, and thereby diminishes the prospects for interoperability.
Windows Communication Foundation
The proxy class for a service used in a Windows Communication Foundation client serializes parameters passed to any of its methods into a System.ServiceModel.Channels.Message object. That object is then passed through a series of channels, the number and nature of which are determined by the selected binding. Those channels will typically add System.ServiceModel.Channels.MessageHeader objects to the Headers collection of the System.ServiceModel.Channels.Message object in accordance with a protocol that the channel implements. The last channel in the series is always a transport channel. That channel will use an encoder, the nature of which is also determined by the binding, to serialize the System.ServiceModel.Channels.Message object into a stream of bytes which the transport channel transmits to the server. A listener on the server receives the stream of bytes and uses an encoder to de-serialize the stream of bytes into a System.ServiceModel.Channels.Message object. That object is then passed through a series of channels that will usually correspond to the series of channels on the client. Then the System.ServiceModel.Channels.Message object is passed to a System.ServiceModel.Dispatcher.DispatchRuntime object. The System.ServiceModel.Dispatcher.DispatchRuntime object determines which method of the service type is to be invoked, de-serializes data from the System.ServiceModel.Channels.Message object into instances of the types the method expects as parameters, and invokes the method.
Not only can the selection and operation of the channels through which data transmissions pass within the Windows Communication Foundation be customized via the binding of a service, custom channels can readily be added. Also, the operation of any proxy and the System.ServiceModel.Dispatcher.DispatchRuntime can be adjusted or entirely customized via the behaviors. Thus, whereas ASP.NET provides a number of attributes for controlling its Web service request handler, the Windows Communication Foundation not only offers a similar set of attributes, but also the option of swapping in custom code to control a proxy and the System.ServiceModel.Dispatcher.DispatchRuntime.
In determining which method of a service type is to be invoked to process a request, the System.ServiceModel.Dispatcher.DispatchRuntime relies on the SOAPAction header. By default, the SOAPAction header for a Windows Communication Foundation operation consists of the namespace of the service, followed by the name of the service contract, followed by the name of the operation. The default namespace for a service contract is. The default name for a service contract is the name of the interface or class used to define it, and the default name of an operation is the name of the method that implements it. So, in the case of this operation,
the SOAPAction header will be. Namespaces and names for service contracts can be altered from their defaults using the Namespace and Name parameters of the System.ServiceModel.ServiceContract attribute, and the names of operations can be altered from their defaults using the Name parameter of the System.ServiceModel.OperationContract attribute:
In de-serializing data from a System.ServiceModel.Message object, the System.ServiceModel.Dispatcher.DispatchRuntime uses the System.Runtime.Serialization.DataContractFormatter by default. The mechanism of the Namespace and Name parameters of the System.ServiceModel.DataContract and System.ServiceModel.DataMember attributes for matching the names of XML elements to the classes into which they are to be de-serialized has already been mentioned.
The System.ServiceModel.Dispatcher.DispatchRuntime can be made to use the System.Xml.Serialization.XmlSerializer by applying the System.ServiceModel.XmlSerializerFormat attribute:
That attribute can also be applied to the individual operations of a service.
If the System.Runtime.Serialization.DataContractFormatter is being used for de-serialization, then whether the data is expected to be in document style or the RPC style can be controlled using the System.ServiceModel.DataContractFormat attribute. That attribute can be applied either to a service contract, or to individual operations of a service contract:
Anticipating Adopting the Windows Communication Foundation: Easing Future Integration
If one uses ASP.NET today, and anticipates using the Windows Communication Foundation in future, then here is guidance to follow to ensure that new ASP.NET Web services will work well together with Windows Communication Foundation applications.
General Recommendations
Adopt ASP.NET 2.0 for any new services. Doing so will of course provide access to the improvements and enhancements of the new version. However, it will also allow for the possibility of using ASP.NET 2.0 components together with Windows Communication Foundation components in the same application.
Protocols
Use ASP.NET 2.0's new facility for validating conformity to the WS-I Basic Profile 1.1:
ASP.NET Web services that conform to that profile are more interoperable generally, and will certainly be interoperable with Windows Communication Foundation clients via the Windows Communication Foundation's predefined binding, System.ServiceModel.BasicHttpBinding.
Service Development
Avoid using the System.Web.Services.Protocols.SoapDocumentService attribute to have messages dispatched to methods based on the fully-qualified name of the body element of the SOAP message rather than the SOAPAction HTTP header. The Windows Communication Foundation uses the SOAPAction HTTP header for dispatching messages to methods.
Data Representation
Recall that, in defining a data type for use with ASP.NET Web services today while anticipating adopting the Windows Communication Foundation in the future, do the following:
- Define the type using .NET classes rather than XML Schema.
- Add only the System.Serializable attribute and the System.Xml.Serialization.XmlRoot attribute to the class, using the latter to explicitly define the namespace for the type. Refrain from adding additional attributes from the System.Xml.Serialization namespace to control how the .NET class is to be translated into XML.
By adopting this approach, one should be able to later make the .NET classes into data contracts with the addition of the System.Runtime.Serialization.DataContract and System.Runtime.Serialization.DataMember attributes without significantly altering the XML into which those classes are serialized for transmission. Then the same types used in messages by ASP.NET Web services will be able to be processed as data contracts by Windows Communication Foundation applications, yielding, amongst other benefits, better performance in the Windows Communication Foundation applications.
Security
Avoid using IIS' authentication options. Windows Communication Foundation clients do not support them. If a service needs to be secured, then one should adopt the Windows Communication Foundation right away, because it has richer options based on standard protocols.
Anticipating Adopting the Windows Communication Foundation: Easing Future Migration
To ensure an easier future migration of new ASP.NET applications to the Windows Communication Foundation, follow the preceding recommendations as well as these:
Protocols
Disable ASP.NET 2.0 support for SOAP 1.2:
Doing so is advisable because the Windows Communication Foundation requires messages conforming to different protocols, like SOAP 1.1 and SOAP 1.2, to go via different endpoints. If an ASP.NET 2.0 Web service is configured to support both SOAP 1.1 and SOAP 1.2, which is the default configuration, then it could not be migrated forward to a single Windows Communication Foundation endpoint at the original address that would be certainly be compatible with all of the ASP.NET Web service's existing clients.
Service Development
- The Windows Communication Foundation allows one to define service contracts by applying the System.ServiceModel.ServiceContract attribute either to interfaces or to classes. It is recommended to apply the attribute to an interface rather than to a class, because doing yields a definition of a contract that can be variously implemented by any number of classes. ASP.NET 2.0 supports the option of applying the System.Web.Services.WebService attribute to interfaces as well as classes. However, as mentioned already, there is a defect in ASP.NET 2.0, by which the Namespace parameter of the System.Web.Services.WebService attribute has no effect when that attribute is applied to an interface rather than a class. Since it is generally generally advisable to modify the namespace of a service from the default value,, using the Namespace parameter of the System.Web.Services.WebService attribute, one should continue defining ASP.NET Web Services by applying the System.ServiceModel.ServiceContract attribute either to interfaces or to classes.
- Have as little code as possible in the methods by which those interfaces are defined. Have them delegate their work to other classes. New Windows Communication Foundation service types could then also simply delegate their substantive work to those classes.
- Provide explicit names for the operations of a service using the MessageName parameter of the System.Web.Services.WebMethod attribute.
Doing so is important, because the default names for operations in ASP.NET are different from the default names supplied by the Windows Communication Foundation. By providing explicit names, one avoids relying on the default ones.
- Do not implement ASP.NET Web service operations with polymorphic methods, because the Windows Communication Foundation does not support implementing operations with polymorphic methods.
- Use the System.Web.Services.Protocols.SoapDocumentMethod attribute to provide explicit values for the SOAPAction HTTP headers by which HTTP requests will be routed to methods.
- Again, taking this approach will circumvent having to rely on the default SOAPAction values used by ASP.NET and the Windows Communication Foundation being the same.
- Avoid using SOAP extensions. If SOAP extensions are required, then determine whether the purpose for which they are being considered is a feature that is already provided by the Windows Communication Foundation. If that is indeed the case, then reconsider the choice to not adopt the Windows Communication Foundation right away.
State Management
Avoid having to maintain state in services. Not only does maintaining state tend to compromise the scalability of an application, but the state management mechanisms of ASP.NET and the Windows Communication Foundation are very different, although the Windows Communication Foundation does support the ASP.NET mechanisms in ASP.NET compatibility mode.
Exception Handling
In designing the structures of the data types to be sent and received by a service, also design structures to represent the various types of exceptions that might occur within a service that one might wish to convey to a client.
[Serializable] [XmlRoot( Namespace="ExplicitNamespace", IsNullable=true)] public partial class AnticipatedException { private string anticipatedExceptionInformationField; public string AnticipatedExceptionInformation { get { return this.anticipatedExceptionInformationField; } set { this.anticipatedExceptionInformationField = value; } } }
Give those classes the ability to serialize themselves to XML:
public XmlNode ToXML() { XmlSerializer serializer = new XmlSerializer( typeof(AnticipatedException)); MemoryStream memoryStream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter( memoryStream, UnicodeEncoding.UTF8); serializer.Serialize(writer, this); XmlDocument document = new XmlDocument(); document.LoadXml(new string( UnicodeEncoding.UTF8.GetChars( memoryStream.GetBuffer())).Trim()); return document.DocumentElement; }
Those classes can then be used to provide the details for explicitly thrown System.Web.Services.Protocols.SoapException instances:
These exception classes will be readily reusable with the Windows Communication Foundation's System.ServiceModel.FaultContract<T>:
Security
- Avoid using ASP.NET 2.0 Profiles.
- Avoid using ACLs to control access to services.
- Do consider using ASP.NET 2.0 Role Providers for authorizing access to the resources of a service.
Adopting the Windows Communication Foundation
Co-existence with ASP.NET Web Services
One can opt to use the Windows Communication Foundation for new development, while continuing to maintain existing applications developed using ASP.NET. Because the Windows Communication Foundation is intended to be the most suitable choice for facilitating communication with .NET applications in any scenario, it can indeed serve as a standard tool for solving a wide variety of software communications problems in a way that ASP.NET never could.
New Windows Communication Foundation applications can be deployed on the same machines as existing ASP.NET Web services. If those ASP.NET Web services use a version of .NET prior to version 2.0, then one would use the ASP.NET IIS Registration Tool to selectively deploy the .NET Framework 2.0 to IIS applications in which new Windows Communication Foundation applications are to be hosted. See the documentation for ASP.NET IIS Registration Tool (Aspnet_regiis.exe). The tool has an intuitive user interface built into the IIS 6 management console.
The Windows Communication Foundation can be used to add new features to existing ASP.NET Web services by adding Windows Communication Foundation services configured to run in ASP.NET compatibility mode to existing ASP.NET Web service applications in IIS. By virtue of ASP.NET compatibility mode, the code for the new Windows Communication Foundation services will actually be able to access and update the same application state information as the pre-existing ASP.NET code, via the System.Web.HttpContext class. They will also be able to share the same class libraries.
Migrating ASP.NET Web Services and Clients to the Windows Communication Foundation
Windows Communication Foundation clients can use ASP.NET Web services. Windows Communication Foundation services that are configured with the System.ServiceModel.BasicHttpBinding can be used by ASP.NET Web service clients. ASP.NET Web services can co-exist with Windows Communication Foundation applications, and the Windows Communication Foundation can even be used to add features to existing ASP.NET Web services. Given all of these ways in which the Windows Communication Foundation and ASP.NET Web services can be used together, there are few compelling reasons for migrating ASP.NET Web services to the Windows Communication Foundation.
Even in the few cases where it is deemed to be necessary, carefully consider that simply migrating code from one technology to another is seldom the right approach. The reason for adopting the new technology would be to meet new requirements that could not be met with the earlier technology, and, in that case, the right thing to do is to design a new solution to meet the newly-expanded set of requirements. The new design would benefit from one's experience with the existing system and from wisdom gained since that system was designed. The new design would also take into account the full capabilities of the new technologies rather than simply reproducing the old design on the new platform. After prototyping key elements of the new design, it generally becomes quite obvious how to re-use code from the existing system within the new one.
For the few cases where a simple port from ASP.NET Web services to the Windows Communication Foundation is deemed to be the right solution, some guidance follows on how to proceed. There is advice on how to migrate services, and how to migrate clients.
Migrating an ASP.NET Web Service to the Windows Communication Foundation
- Ensure that a comprehensive suite of tests exist for the service.
- Generate the WSDL for the service, and save a copy in the same folder as the service's .asmx file.
- Upgrade the ASP.NET Web service to use .NET 2.0. Do so by first deploying the .NET Framework 2.0 to the application in IIS, and then by using Visual Studio 2005 to automate the code conversion process, as documented here:. Execute the suite of tests.
- Provide explicit values for the Namespace and Name parameters of the System.Web.Services.WebService attributes if they are not provided already. Do the same for the MessageName parameter of the System.Web.Services.WebMethod attributes. Also, if explicit values are not already provided for the SOAPAction HTTP headers by which requests are routed to methods, then explicitly specify the default value of the Action parameter with a System.Web.Services.Protocols.SoapDocumentMethod attribute:
[WebService(Namespace = "", Name = "Adder")] public class Adder { [WebMethod(MessageName = "Add")] [SoapDocumentMethod(Action = "")] public double Add(SumInput input) { double sum = 0.00; foreach (double inputValue in input.Input) { sum += inputValue; } return sum; } }
- Execute the suite of tests.
- Move any substantive code in the bodies of the methods of the class to a separate class that the original class is made to use.
[WebService(Namespace = "", Name = "Adder")] public class Adder { [WebMethod(MessageName = "Add")] [SoapDocumentMethod(Action = "")] public double Add(SumInput input) { return new ActualAdder().Add(input); } } internal class ActualAdder { internal double Add(SumInput input) { double sum = 0.00; foreach (double inputValue in input.Input) { sum += inputValue; } return sum; } }
- Execute the suite of tests.
- Add references to the Windows Communication Foundation assemblies System.ServiceModel and System.Runtime.Serialization to the ASP.NET Web service project.
- Execute the Windows Communication Foundation's svcutil.exe tool to generate a Windows Communication Foundation proxy class from the WSDL. Add the generated class module to the solution.
- The class module generated in the preceding step will contain the definition of an interface.
[System.ServiceModel.ServiceContractAttribute()] public interface AdderSoap { [System.ServiceModel.OperationContractAttribute( Action="", ReplyAction="")] AddResponse Add(AddRequest request); } Modify the definition of the ASP.NET Web service class so that the class is defined as implementing that interface: [WebService(Namespace = "", Name = "Adder")] public class Adder: AdderSoap { [WebMethod(MessageName = "Add")] [SoapDocumentMethod(Action = "")] public double Add(SumInput input) { return new ActualAdder().Add(input); } public AddResponse Add(AddRequest request) { return new AddResponse( new AddResponseBody( this.Add(request.Body.input))); } }
- Compile the project. There may be some errors due to the code generated in step nine duplicating some type definitions. Repair those errors, usually by deleting the pre-existing definitions of the types. Execute the suite of tests.
- Remove the ASP.NET-specific attributes, such as the System.Web.Services.WebService, System.Web.Services.WebMethod, and System.Web.Services.Protocols.SoapDocumentMethod attributes:
- Configure the class, which will now be a Windows Communication Foundation service type, to require the Windows Communication Foundation's ASP.NET compatibility mode if the ASP.NET Web service relied on any of the following:
- the System.Web.Services.HttpContext class
- the ASP.NET Profiles
- ACLs on .asmx files
- IIS authentication options
- ASP.NET impersonation options
- ASP.NET globalization
- Rename the original .asmx file to .asmx.old.
- Create a Windows Communication Foundation service file for the service, give it the extension, .asmx, and save it into the application root in IIS.
- Add a Windows Communication Foundation configuration for the service to its Web.config file. Configure the service to use the BasicHttpBinding, to use the service file with the .asmx extension created in the preceding steps, and to not generate WSDL for itself, but rather to use the WSDL from step two, above. Also configure it to use ASP.NET compatibility mode if that was determined to be necessary in step ten, above.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <compilation> <buildProviders> <remove extension=".asmx" /> <add extension=".asmx" type= "System.ServiceModel.ServiceBuildProvider, System.ServiceModel, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </buildProviders> </compilation> </system.web> <system.serviceModel> <services> <service name="MyOrganization.Adder " behaviorConfiguration="AdderBehavior"> <endpoint address="" binding="basicHttpBinding" contract="AdderSoap "/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="AdderBehavior"> <metadataPublishing enableMetadataExchange="true" enableGetWsdl="true" enableHelpPage="true" metadataLocation= ""/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled ="true"/> </system.serviceModel> </configuration>
- Save the configuration.
- Compile the project.
- Execute the suite of tests.
Migrating ASP.NET Web Service Clients to the Windows Communication Foundation
- Ensure that a comprehensive suite of tests exist for the client.
- Use Visual Studio 2005 to upgrade the client application to .NET 2.0. Execute the suite of tests.
- Remove ASP.NET proxy code from the client project. That code will usually be in modules generated using the wsdl.exe tool.
- Generate Windows Communication Foundation proxy code using the svcutil.exe tool. Add that code to the client project, and merge the configuration output into the client's existing configuration file.
- Compile the application. Repair the compilation errors by replacing references to the former ASP.NET proxy types with references to the new Windows Communication Foundation proxy types.
- Execute the suite of tests.
Summary
Whereas the ASP.NET Web services tools are solely for building Web services, the Windows Communication Foundation provides tools for use in any circumstance where software entities must be made to communicate with one another. Even for Web service development projects, the Windows Communication Foundation supports more Web service protocols than ASP.NET Web services support. Those protocols provide for more sophisticated solutions involving, amongst other things, reliable sessions and transactions. The recommended course of action in most cases is to adopt the Windows Communication Foundation for new development, while continuing to maintain existing ASP.NET Web service applications. That course of action yields the benefits of the Windows Communication Foundation, while sparing the cost of migrating existing applications. New Windows Communication Foundation applications will be able to use existing ASP.NET Web services, and can co-exist with existing ASP.NET applications. The Windows Communication Foundation can even be used to program new operational capabilities into existing ASP.NET applications by virtue of the Windows Communication Foundation's ASP.NET compatibility mode. | http://msdn.microsoft.com/library/aa480155 | crawl-003 | en | refinedweb |
Deploying Microsoft .NET Framework Version 3.0
Annie Wang
Microsoft Corporation
June 2006
Applies to
Microsoft .NET Framework version 3.0 (formerly known as WinFX)
Microsoft .NET Framework 2.0
Microsoft Windows Vista
Summary: The. (18 printed pages)
Contents
Introduction
About Microsoft .NET Framework 3.0
How .NET Framework 3.0 Relates to .NET Framework 2.0 and Earlier
Servicing Policy for the .NET Framework 3.0
Roadmap for Future .NET Framework Releases
Installing the .NET Framework 3.0
Version Numbers for .NET Framework Assemblies
Deploying .NET Framework 3.0
Software Requirements
Hardware Requirements
Redistribution Rights for the .NET Framework
IT Administrator Tools for Deploying the .NET Framework 3.0
Redistributing the .NET Framework with Your Application
Detecting .NET Framework 3.0 and Earlier Releases
Reading a Registry Key
Reading the User-Agent String in Internet Explorer
Command Line Options for the .NET Framework 3.0 Redistributable
Error Codes for the .NET Framework 3.0 Redistributable
Appendix A: Detecting .NET Framework Language Packs
Appendix B: Sample Script for Detecting the .NET Framework 3.0 Using Internet Explorer
Introduction
This section provides an overview of the .NET Framework 3.0.
About Microsoft .NET Framework 3.0
The Microsoft .NET Framework version 3.0 (formerly known as WinFX) is the new managed-code programming model for Windows. It combines the power of .NET Framework 2.0 with new technologies for building applications that have a visually compelling user experience, seamless communication across technology boundaries, and support for a wide range of business processes. Microsoft plans to ship .NET Framework 3.0 as part of Windows Vista. At the same time, Microsoft will make .NET Framework available for Windows XP Service Pack 2 and Windows Server 2003 Service Pack 1.
The following table lists some of the technologies included with .NET Framework 3.0.
All of the classes that represent the new components (WPF, WF, WCF, and CardSpace) are part of the System namespace. The core classes of the .NET platform, such as the common language runtime (CLR) and base class libraries (BCL) remain as they are in .NET Framework 2.0.
The following diagram illustrates the structure of .NET Framework 3.0.
Figure 1. .NET Framework 3.0
How .NET Framework 3.0 Relates to .NET Framework 2.0 and Earlier.).
If you are moving to .NET Framework 3.0 from .NET Framework 1.1 or 1.0, you should perform impact analysis and run compatibility testing prior to deployment. While we have worked to make .NET Framework releases compatible, there are a small number of known incompatibles due to security and significant functionality additions. For more information, see the page Breaking Changes in .NET Framework 2.0 on the Microsoft .NET Developer Center Web site.
Servicing Policy for the .NET Framework 3.0
Microsoft will continue to service .NET Framework 2.0 release in accordance with the standard support policy for the platforms it is supported on. Users who currently rely on .NET Framework 2.0 have the option of remaining on that version of the .NET Framework and receiving software updates as they become available.
Any component that ships as part of .NET Framework 3.0 will be serviced on the platforms it is supported on. For more information, see the Software Update Technology page on the Microsoft Visual Studio Developer Center Web site.
Roadmap for Future .NET Framework Releases
In general, any new version of the .NET Framework is designed to provide backward compatibility with the previous version. If a new release introduces breaking changes due to security issues or other reasons, Microsoft will enable you to install the new release side by side with the existing version.
For more information about future releases of the .NET Framework, see the Microsoft .NET Framework Developer Center Web site.
Installing the .NET Framework 3.0
The .NET Framework 3.0 is installed by default on Microsoft Windows Vista. On Microsoft Windows Server code-named "Longhorn", you can install the .NET Framework as a Windows Feature using Roles Management tools.
On Windows XP and Windows Server 2003, installing .NET Framework 3.0 also adds any .NET Framework 2.0 components that are not already installed. If .NET Framework 2.0 is already installed, the .NET Framework 3.0 installer adds only the files for Windows Presentation Foundation (WPF), Windows Workflow Foundation (WF), Windows Communication Foundation (WCF), and Windows CardSpace.
Components shared with .NET Framework 2.0 are installed in the following location:
Components that are new to .NET Framework 3.0 are installed in the following location:
All components of the .NET Framework 3.0 reference assemblies are installed in the following location:
Uninstalling .NET Framework 3.0 will not remove the components shared with .NET Framework 2.0. To remove those components, you must first uninstall .NET Framework 3.0 and then separately uninstall .NET Framework 2.0. (You can uninstall the .NET Framework using the Add or Remove Programs item in Windows Control Panel.)
Version Numbers for .NET Framework Assemblies
The .NET Framework 3.0 shares many components with .NET Framework 2.0, and the common language runtime (CLR) and base class libraries are the same as those in .NET Framework 2.0. Therefore, these shared components stay at version 2.0. The version number 3.0 applies to all runtime and reference assemblies for Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), Windows Workflow Foundation (WF), and Windows CardSpace.
Deploying .NET Framework 3.0
This section provides information about deploying the .NET Framework 3.0 for use with your applications.
Software Requirements
To install .NET Framework 3.0, you must have one of the following operating systems installed on the target computer:
- Microsoft Windows XP Home or Microsoft Windows XP Home Professional, with Service Pack 2 or later.
- Microsoft Windows Server 2003 family with Service Pack 1 or later.
Note .NET Framework 2.0 continues to be supported on its target platforms. For more information, see the .NET Framework 2.0 Redistributable Prerequisites page on the MSDN Web site.
.NET Framework 3.0 is installed by default with Microsoft Windows Vista. On Microsoft Windows Server "Longhorn", the .NET Framework 3.0 is a Windows feature that can be installed using Roles Management tools.
Note Microsoft Windows Server "Longhorn" IA64 Edition is the only IA64 platform that the .NET Framework 3.0 supports.
Hardware Requirements
The following table lists the hardware requirements for running .NET Framework 3.0.
Redistribution Rights for the .NET Framework
Microsoft strongly supports customers in deploying the .NET Framework within their organizations and as part of their software solutions. Distributing the .NET Framework 3.0 runtime requires you to accept license terms. For information about redistributing the .NET Framework 3.0 with your application or to a third party, review the page The ISV Guide for Redistributing the .NET Framework and Other Runtime Components page on the MSDN Web site.
Note The redistributable right is reserved only for the official released version of the Microsoft .NET Framework 3.0. You may not redistribute the pre-released version of Microsoft .NET Framework 3.0 with your application.
IT Administrator Tools for Deploying the .NET Framework 3.0
The .NET Framework 3.0 offers two ways for IT administrators to deploy to field clients: administrator-mode setup and Active Directory deployment.
Administrator-mode Setup
Administrator-mode setup enables IT administrators to deploy the .NET Framework through Microsoft Systems Management Server (SMS) or other software distribution tools. The IT administrator runs the Framework setup in silent mode. If errors occur, setup quits silently and logs an error code.
Active Directory Deployment
In Active Directory deployment, the administrator must add individual .msi files from the .NET Framework 3.0 installation package into the group policy in the order in which the .msi files should be deployed. After the group policy is enabled, any clients that are part of this group policy will automatically install the components when they boot and reconnect to the network. If errors occur, setup quits silently and logs an error code.
For more information about administrative deployment instructions, see the Administrators Deployment Guide Web page.
Redistributing the .NET Framework with Your Application
The .NET Framework 3.0 redistributable package is available as a stand-alone executable file. The name of the file depends on the type.
When you distribute the .NET Framework 3.0 redistributable package with your application, you must agree to the license terms, which give you specific distribution rights.
You can manually launch and install the redistributable on a computer, or it can be launched and installed as part of the setup program for a .NET Framework 3.0 application.
Note Administrator privileges are required to install the .NET Framework 3.0.
For more information, see the Microsoft .NET Framework 3.0 Deployment Guide Web page.
Detecting .NET Framework 3.0 and Earlier Releases
You can detect if the .NET Framework 3.0 is installed by reading a registry key and by querying the user-agent string in Internet Explorer.
Reading a Registry Key
You can look for a specified registry key value to detect whether the .NET Framework is installed on a computer. The following table lists the registry keys and values that you can test to determine whether specific versions of the .NET Framework are installed.
Note For more information about detecting previously released service packs for .NET Framework 1.0 and 1.1 , see article 318785, "How to determine which versions of the .NET Framework are installed and whether service packs have been applied" in the Microsoft Knowledge Base.
Reading the User-Agent String in Internet Explorer
For browser-based applications, you can detect whether the .NET Framework 3.0 is installed on a computer by examining the user-agent string using Internet Explorer running on that computer. This will contain the substring "NET CLR" followed by the major and minor version numbers. A sample user-agent string looks like the following:
Appendix B: Sample Script for Detecting the .NET Framework 3.0 Using Internet Explorer lists a sample JavaScript program that runs in a browser and displays information about the current .NET Framework version number.
The user-agent string that is sent in browser headers is stored in the registry of the server computer, as listed in the following table.
Command Line Options for the .NET Framework 3.0 Redistributable
The following table lists options that you can include when you run the .NET Framework 3.0 Redistributable installation program (Dotnetfx3.exe, Dotnetfx3_x64.exe, or Dotnet3setup.exe) from the command line.
Error Codes for the .NET Framework 3.0 Redistributable.
Appendix A: Detecting .NET Framework Language Packs
The following table lists the registry values you can read to detect whether a .NET Framework language pack is installed on a computer. For more information on how to detect localized version of the .NET Framework 1.0, see the page .NET Framework Redistributable Package Technical Reference on the MSDN Web site.
Appendix B: Sample Script for Detecting the .NET Framework 3.0 Using Internet Explorer
The following example shows a JavaScript program that runs in a browser detects whether .NET Framework 3.0 is running. The script searches the user-agent string and displays a status message based on the results of the search.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <title>Test for NET Framework 3.0</title> <meta http- <script type="text/javascript" language="JavaScript"> <!-- var </body> </html>
If the search for the string ".NET Framework 3.0" version is successful, the following message appears:
This computer has the correct version of the .NET Framework: 3.0.04131.06.
This computer's userAgent string is: Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04131.06).
Otherwise, the following message appears:
This computer does not have the correct version of the .NET Framework.
to get .NET Framework 3.0 now.
This computer's userAgent string is: Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727). | http://msdn.microsoft.com/library/aa480198 | crawl-003 | en | refinedweb |
MBSRTOWCS(3) BSD Programmer's Manual MBSRTOWCS(3)
mbsrtowcs, mbsnrtowcs, mbsnrtowcsvis - convert a multibyte character string to a wide character
#include <wchar.h> size_t mbsrtowcs(wchar_t * restrict pwcs, const char ** restrict s, size_t n, mbstate_t * restrict ps); size_t mbsnrtowcs(wchar_t * restrict pwcs, const char ** restrict s, size_t max, size_t n, mbstate_t * restrict ps); size_t mbsnrtowcsvis(wchar_t * restrict pwcs, const char ** restrict s, size_t max, size_t n, mbstate_t * restrict ps);
mbsrtowcs() converts the multibyte character string indirectly pointed to by s to the corresponding wide character string, and stores it in the ar- ray pointed to by pwcs. mbsnrtowcs() behaves the same, but reads at most max octets from the string indirectly pointed to by s. mbsnrtowcsvis() behaves the same, but automatically converts input octets from 8bit to unicode. The conversion stops due to the following reasons: • The conversion reaches a null byte. In this case, the null byte is also converted. • mbsrtowcs() or mbsnrtowcs() has already stored n wide characters. • The conversion encounters an invalid character. • The mbsnrtowcs() function has already devoured max octets. Each character is converted as if optu8to16(3) is continuously called. In the case of mbsnrtowcsvis(), each character is converted as if optu8to16vis(3) is continuously called; if the max argument is initially set to 0, the remaining state is drained. After conversion, if pwcs is not a NULL pointer, the pointer object pointed to by s is a NULL pointer (if the conversion is stopped due to reaching a null byte) or the first byte of the character just after the last character converted. If pwcs is not a null pointer and the conversion is stopped due to reach- ing a null byte, the mbsrtowcs() and mbsnrtowcs() functions place the state object pointed to by ps to an initial state after the conversion has taken place. The behaviour of the mbsrtowcs() and mbsnrtowcs() functions is affected by the LC_CTYPE category of the current locale. These are the special cases: s == NULL || *s == NULL Undefined (may cause the program to crash). pwcs == NULL The conversion has taken place, but the resultant wide character string was discarded. In this case, the pointer object pointed to by s is not modified and n is ignored. ps == NULL mbsrtowcs() uses its own internal state object to keep the conversion state, instead of ps mentioned in this manual page. mbsnrtowcs() has an own internal state which is dif- ferent from the one of mbsrtowcs(). Calling any other functions in libc never change the inter- nal state of mbsnrtowcs() or mbsrtowcs(), which is initial- ised at startup time of the program.
mbsrtowcs() and mbsnrtowcs() return: 0 or positive The value returned is the number of elements stored in the array pointed to by pwcs, except for a terminating null wide character (if any). If pwcs is not null and the value returned is equal to n, the wide character string pointed to by pwcs is not null terminated. If pwcs is a null pointer, the value returned is the number of elements to contain the whole string converted, except for a terminat- ing null wide character. (size_t)-1 The array indirectly pointed to by s contains a byte se- quence forming invalid character. In this case, mbsrtowcs() and mbsnrtowcs() set errno to indicate the error.
mbsrtowcs() and mbsnrtowcs() may cause an error in the following cases: [EILSEQ] The pointer pointed to by s points to an invalid or incom- plete multibyte character. [EINVAL] ps points to an invalid or uninitialized mbstate_t object.
mbrtowc(3), mbstowcs(3), optu8to16(3), optu8to16vis(3), setlocale(3)
The mbsrtowcs() function conforms to ISO/IEC 9899/AMD1:1995 ("ISO C90, Amendment 1"). The restrict qualifier is added at ISO/IEC 9899/1999 "(ISO C99)". The mbsnrtowcs() function is a GNU extension. The mbsnrtowcsvis() function assumes codepage 1252 and maps holes into distinguishable codepoints. This extended function declares a macro with the same name that can be used to check for its presence.
mbsnrtowcs() first appeared in MirOS #10. mbsnrtowcsvis() first appeared in MirOS #11. MirOS BSD #10-current October. | http://mirbsd.mirsolutions.de/htman/sparc/man3/mbsrtowcs.htm | crawl-003 | en | refinedweb |
MBSINIT(3) BSD Programmer's Manual MBSINIT(3)
mbsinit - determines whether the state object is in initial state
#include <wchar.h> int mbsinit(const mbstate_t *ps);
mbsinit() determines whether the state object pointed to by ps is in ini- tial conversion state, or not. ps may be a NULL pointer. In this case, mbsinit() will always return non-zero.
mbsinit() returns: 0 The current state is not in initial state. non-zero The current state is in initial state or ps is a NULL pointer.
No errors are defined.
The mbsinit() conforms to ISO/IEC 9899/AMD1:1995 ("ISO C90, Amendment. | http://mirbsd.mirsolutions.de/htman/sparc/man3/mbsinit.htm | crawl-003 | en | refinedweb |
Map|Home
Emerald club with budget rental cars
Car dealerships in hillsboro
Free car test drives
Dodge and plymouth clic cars
Federal allowance for car usage
Demlow auto sales
Car new ford dealers
Canfield ohio car show for 2008
Antique and classic auto for sale
Remote control car columbia s c
Lincoln town car models
What does indy car cost
Illinois child car seat
Wire diagrams for dodge cars
disney diecast cars wave 4, free online 3d racing car games,
enterprise car rental dollar rentalccrets comwjac auto, power buster and auto audio, dodge and plymouth clic cars,garage shut car running2 car speakers,
td auto purchase, graco car seat cover, eurp suzuki cars, car polish metal, homwmade hydrogen for cars,
facts about auto window tinting, car that is fun to drive, troubleshooting auto dc power socket car rentals louisville ky, auto hauler shopper,
kevin harvick with his newest carauto radio mp3, cadillac car dealer in sallisaw oklahoma, acrylic personalized car tags,import a smart cargrand theft auto iv cheat code,
yark automotive group used cars, car statistics by make 2008, new castle delaware racetrack mini cars, buy cars cheap cadillacs ohio, car insurance comparison quotes,
a advantage auto transport, auto insurance rate revision, car with 2 steering directions, classic car jackets, assurance auto le havre,
cadillac car dealer in sallisaw oklahoma, hotel flight car beach vacation package
Top offers:
Friend links:
auto repair farmington ct, comstar car security,
auto salavage pricesused cars college station, gone in 60 second cars, used car financing interest,jerky boys car dealerlong island auto air conditioner,
car cheapest en insurance lang sb,
import a smart car, auto glow neon, 1976 chevy nova model car, volkswagen car manufacturer, best used luxury car buys,
2008 car seat regulations, 2 car speakers, car fm amplifier, dodge charger police car pics, importer car wash,
auto insurance speeding, jonesboro car donation network pets car, clasic car retitle minnesota,
car easy insurance onlinefast cars with girls, hotel flight car beach vacation package, car bedroom set,breaking car glass with after effectfront seat lincoln town car,
budget car rental in palma,
auto repair fowler mi, race car ball joints, outboard motor auto steer, cars wii cheats, car floor gets wet,
ups and car show, car customization shops, hawk h5000 car alarm, auto salvage ann arbor michigan, auto hood onaments,
buy car rims for cheap, used auto parts kansas city missouri
how to roll a car crusine car show new mexico discount cars chysler car rentals ford late model cars for sale doty used cars hand car wash in queens cheap car insurance in ontario easter monday cars london assurance auto le havre | http://zezfpmf.exactpages.com/steering-on-a-car.html | CC-MAIN-2020-24 | en | refinedweb |
To track events and data within your Skill we can use logging. If you are new to programming, this is a way to output a message that can tell you the state of your Skill at a particular point in time, details about an error that has occured, or simply noting that a program reached a particular point in the code.
A logger is available through the
MycroftSkill base class. This means that you can use it within a Skill without needing to import the
logging package. You can simply call
self.log from within the class of your Skill.
Here is a quick example of an
info level message used in a Skill. We will learn more about different levels shortly.
from adapt.intent import IntentBuilderfrom mycroft import MycroftSkill, intent_handlerclass")def create_skill():return LoggingSkill()
There are five types of log messages available that are used for different purposes.
self.log.debug
Debug messages are used for information that will help to diagnose problems. These are particularly useful if there is anything that has the potential to break in the future.
By default these messages will not be logged unless the User has explicity turned on debug level logging.
self.log.info
Info messages provide general information when the Skill is running as expected. These messages will always be logged so are useful when actively developing a Skill, but should be used sparingly once a Skill is published for other people to use.
self.log.warning
Warning messages are used to indicate that something has gone wrong, but the Skill will continue to function.
self.log.error
Error messages indicate that a serious problem has occured and the Skill will not be able to function. In the Mycroft CLI these messages are shown in red to make them highly visible.
self.log.exception
Exception messages are an extended form of the
error level message. These messages include a stack trace and should only be called from an exception handler. For example:
try:1/0except ZeroDivisionError as e:self.log.exception("Cannot divide by zero")
Log messages from a Skill are displayed in the Mycroft CLI so that a User can see in real-time what is happening in the Skill. They are also written to the
skills.log file located at:
/var/opt/mycroft/skills.log
By default all info, warning, error and exception level messages will be logged. Debug level messages will be logged if the User explicitly requests it. This can be done by issuing the
:log level debug command in the CLI, or changing the
log_level attribute in the mycroft configuration.
To return to normal logging, you can issue the
:log level info CLI command.
As the logger is provided by the MycroftSkill class, it is only available within that scope. If you need to log messages from outside of this class, you can import the logger manually.
from mycroft.util import LOG
This can then be used outside your Skill's class. Extending our first example:
from adapt.intent import IntentBuilderfrom mycroft import MycroftSkill, intent_handlerfrom mycroft.util import LOGLOG.info("This is a logged info level message outside of the MycroftSkill class scope")def my_special_function():LOG.info("Another usage of LOG.")class")my_special_function()def create_skill():return LoggingSkill() | https://mycroft-ai.gitbook.io/docs/skill-development/skill-structure/logging | CC-MAIN-2020-24 | en | refinedweb |
Get the highlights in your inbox every week.
Open source alternatives to Grammarly for word processing | Opensource.com
Open source alternatives to Grammarly for word processing
Check your writing for spelling, grammar, plagiarism, and style errors using these open source tools.
Subscribe now
Grammarly is popular among many teachers, students, business people, and others who need to write or process a lot of words on a regular basis. It's a useful tool, but you're required to register and log in to use it, and I rarely keep website login data in my cache.
I process words pretty often for writing technical and creative pieces, and ducking out of my text editor to open a web browser, much less to visit a site that requires me to log in, is usually too much a bother for me. Fortunately, with a few open source utilities, I can avoid this distraction.
Grammarly's main benefits are checking for:
- Spelling errors
- English grammar errors
- Plagiarism
- Style
Following are the open source alternatives I use for each of these functions.
Spelling
Spell checking is common in most word processors and even text editors. I use Flyspell in Emacs. Flyspell-mode is a minor mode that provides on-the-fly spell checks. Should I spell a word incorrectly, it's underlined with a red line that prompts me to review it. It also has an option to autocorrect words, and if I didn't deal in technology and fantasy and science fiction so much, I'd probably use it.
You can install Flyspell using Emacs' packages interface. To make it an active mode upon launch, add this to your .emacs file:
(require 'flyspell)
(flyspell-mode +1)
Grammar
For grammatical issues, I use the LanguageTool API. It's an open source website and library funded by the European Union and developed by coders around the world.
You can use LanguageTool as a plugin for LibreOffice or Firefox, Chromium, Brave, Chrome, and other browsers; as a terminal command; or as a graphical application. It even has plugins for proprietary editors like Google Docs and Microsoft Word. If you download it for local use, you must have Java installed.
There's also an Emacs plugin, which essentially is an Elisp connector between Emacs and the LanguageTool Java library. By installing the langtool package in Emacs, LanguageTool checks my grammar without ever having to consciously launch it myself.
Plagiarism checksThe line between research, reporting, and reuse is often a little blurry, and with so much content available on the internet, it gets less clear every day. Typically, I try to limit myself to Creative Commons and open source resources, but even then, it's important to credit those resources either out of legal obligation or as common courtesy (depending on the license). One way to keep influences in check is to verify your final work against what already exists on the internet.
I use a Python script to do my plagiarism checks. It's by no means a good script. I hacked it together as a quick and easy way to guard against obvious copy-paste mistakes or misjudgments. So, while it's not an elegant script (the option parsing is over-complex and inefficient, and there's no adjustable tolerance level to exclude extremely short searches) and there are sure to be lots of false positives, it's an example of how a quick Python script can replace a service that doesn't otherwise fit into your workflow.
Before using it, you must install the Python google module to enable easy Google searches:
$ python3 -m pip install google --user
I specifically use Google and not an open source search engine like YaCy because I want a big pool of data to draw from.
Here's the script:
#!/usr/bin/env python3
# stollen plagiarism checker
# by Seth Kenlon <skenlon@redhat.com>
# random
from pathlib import Path
from googlesearch import search
def Scrub(ARG):
"""
Read lines of file.
"""
f = open(ARG, 'r')
LINES = f.readlines()
Search(LINES)
def Search(LINES):
"""
Search Internet for exact match of LINE.
"""
COUNT=0
for LINE in LINES:
COUNT += 1
PAUSE = random.randrange(1,4)
if VERBOSE:
print("Searching...")
for ITEM in search(LINE, tld="com", num=1, stop=1, pause=PAUSE):
if VERBOSE:
print("WARNING:" + LINE + " → " + ITEM)
else:
print("WARNING: line " + str(COUNT) + " → " + ITEM)
if __name__ == "__main__":
random.seed()
n=1
if sys.argv[1] == "--verbose" or sys.argv[1] == "-v":
VERBOSE = True
# shift 1
n += 1
else:
VERBOSE = False
f = Path(sys.argv[n])
if not f.is_file():
print("Provide a text file to check.")
exit()
else:
Scrub(sys.argv[n])
Here's a simple test file containing a few lines from the public domain work Alice in Wonderland and a line from a copyrighted song, both of which the script caught, and a line of nonsense text that correctly is not flagged by the script:.
acrutchen macpie.
Just when you think you've got more than enough, that's when it all up and flies away
You can test this by saving the Python script into a file called stollen.py (named after the delicious Christmas cake, not the idea that anyone would ever use stolen content), and the contents of the test file into test.txt. The expected results are hits on all but line 5.
$ chmod +x ./stollen.py
$ ./stollen.py test.txt
WARNING: line 1 →
WARNING: line 3 →
WARNING: line 7 →
To safeguard against being blocked by Google, I use a random number of seconds to pause between calls, so the script isn't very fast by design. Then again, if you've ever used Grammarly, you know that its plagiarism checker isn't very fast, either.
Style review
Of all the features provided by automated editors, a style review is least important for me. Even with Grammarly's adjustable tolerance settings for writing styles spanning from formal to casual, I almost never agree with its suggestions, and it rarely catches things I dislike.
Defining an appropriate style, I think, is subjective for both the author and the reader, and in the context of automated editing, I believe it's actually shorthand for how strictly rules are applied. Therefore, what's actually important are breaches of rules, and it's up to the author or reviewer to decide whether the rule ought to be applied or ignored.
The strictest languages of all are constructed languages intended for computers, such as C, Java, Python, and so on. Because these languages are strictly defined, it's possible to check them, stringently and without exception, against the rules that define them. This process is called linting in computer science, and the aim of the proselint project is to bring that process to natural languages.
You can install proselint as a Python module:
$ python3 -m pip install proselint --user
Once it's installed, run it against a text file:
$ prolint myfile.txt
It provides grammar advice and performs some style checks to catch clichés and slang. It's a useful and objective look at prose, and you're free to ignore or follow its advice. Try it out if you're uncertain about the clarity or vibrancy of your writing.
Open source means choice
There are lots of websites out there that don't publish their source code, and we all use them every day. Finding a good open source alternative isn't always about licensing or source code availability. Sometimes, it's about finding a tool that works better for you than what you were using previously.
With open source, you can survey your options and test them out until you find the one closest to your personal preference. If you want style checking, you have several linters and style checkers to choose from. If you want spelling and grammar checkers, you have many applications that let you integrate different dictionaries and interfaces. Non-open applications don't tend to allow that kind of flexibility. If you limit yourself, even if it's only for a few tasks, to software that isn't open, the diversity of possibility can be difficult to see.
Challenge yourself today, whether it's for spell checking or automated style critique or something else entirely: Find an open source alternative, and see if you can turn something routine into something compelling, fun, and effective.
4 Comments
Nice post, and a topic close to my heart and expertise, but you forgot one of the best options of them all… Vale, which combines many of the tools above into one, and does more… We are even creating pre-built rules for it to emulate many of the Grammarly checks.
Thanks for lifting the veil on this one! I had never heard of this tool, but I'll try it out soon.
It took me a while to actually *find* it. I assume this is the correct one?
A really good post. I'm working through some of the options now. Since I write a lot I particularly liked LanguageTool. I'm trialling it in Firefox now as opposed to Grammarly in Chrome. Thanks a bunch for the article.
Andrew
I'm so glad it was helpful, Andrew. This is my own organic workflow. I'd be interested in hearing the open source solutions other people have assembled, too. | https://opensource.com/article/20/3/open-source-writing-tools | CC-MAIN-2020-24 | en | refinedweb |
On Wednesday 21 May 2003 2:48 pm, Luck, Tony wrote: > The #ifdef CONFIG_SMP in the read/write functions seems a little > convoluted, resulting in the weird can't ever happen error message > for the non-SMP case that is trying to read/write from the wrong > cpu. Why not write each in the form: > > #ifdef CONFIG_SMP > if (cpu == smp_processor_id()) > salinfo_log_read_cpu(&info); > else > smp_call_function_single(cpu, salinfo_log_read_cpu, &info, 0, 1); > #else > salinfo_log_read_cpu(&info); > #endif Nice! I copied the original from somewhere (can't remember where ATM), but yours is much better. Thanks! BjornReceived on Thu May 22 14:30:23 2003
This archive was generated by hypermail 2.1.8 : 2005-08-02 09:20:14 EST | http://www.gelato.unsw.edu.au/archives/linux-ia64/0305/5664.html | CC-MAIN-2020-24 | en | refinedweb |
Created on
11-08-2017
04:51 PM
- edited
08-17-2019
10:20 AM
H2O is an open source deep learning technology for data scientists. Sparkling Water allows users to combine the fast, scalable machine learning algorithms of H2O with the capabilities of Spark.
In this tutorial, I will walk you through the steps required to setup H2O Sparkling Water (specifically PySparkling Water) along with Zeppelin in order to execute your machine learning scripts.
Here are a few points to note before I get started:
1.) There is a known issue when running Sparkling Water within Zeppelin. This issue is documented in this Jira (AttributeError: 'Logger' object has no attribute 'isatty'). To bypass this issue, I use Zeppelin combined with Livy Server to execute the Sparkling Water jobs. If you are not familiar with Apache Livy, it is a service that enables easy interaction with a Spark cluster over a REST interface.
2.) Testing was performed within the following environment:
Hortonworks HDP 2.6.2
CentOS Linux release 7.2.1511 (Core)
Python 2.7.5
Spark 2.1.1
Zeppelin 0.7.2
Now, let's walk through the steps:
Step 1: Download Sparkling Water from here, or login to your Spark client node and run:
wget
Step 2: Unzip and move the PySparkling Water dependency to HDFS:
# Unzip Sparkling Water
unzip sparkling-water-2.1.16.zip
# Move the .zip dependency to a location within HDFS (make sure that this location is accessible from Zeppelin/Livy)
hadoop fs -put sparkling-water-2.1.16/py/build/dist/h2o_pysparkling_2.1-2.1.16.zip /tmp/.
Step 3: Ensure that required python libraries are installed on each datanode:
pip install tabulate
pip install future
pip install requests
pip install six
pip install numpy
pip install colorama
pip install --upgrade requests
Step 4: Edit the HDFS configs by adding the two parameters to custom core-site:
hadoop.proxyuser.livy.groups=*
hadoop.proxyuser.livy.hosts=*
Step 5: Add an new directory to HDFS for "admin" or the user(s) issuing Sparkling Water code:
hadoop fs -mkdir /user/admin
hadoop fs -chown admin:hdfs /user/admin
Step 6: Within Zeppelin, edit the Livy Interpreter and add a new parameter called livy.spark.submit.pyFiles (the value of this parameter should be your HDFS path to the PySparking Water .zip file):
Step 7: Within Zeppelin, import libraries, initialize the H2OContext, then run your PySparkling Water Scripts:
%livy2.pyspark
from pysparkling import *
hc = H2OContext.getOrCreate(spark)
import h2o
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from pyspark.sql.types import *
from pyspark.sql.functions import *
loans = h2o.import_file(path="hdfs://dzaratsian0.field.hortonworks.com:8020/tmp/loan_200k.csv", header=0)
loans.head()
df_loans = hc.as_spark_frame(loans,)
df_loans.show(10)<br>
References:
H2O Downloads
Created on
11-14-2017
09:44 PM
- edited
08-17-2019
10:20 AM
Below are the custom properties which would go in hand with H2O Sparkling Water . Use these properties to modify H2O Cluster Nodes, Memory, Cores etc. | https://community.cloudera.com/t5/Community-Articles/Running-H2O-Sparkling-Water-using-Zeppelin-with-Livy/ta-p/247257 | CC-MAIN-2020-24 | en | refinedweb |
Alternative to JUnit Parameterized Classes: junit-dataprovider
Alternative to JUnit Parameterized Classes: junit-dataprovider
Join the DZone community and get the full member experience.Join For Free
We sometimes if you have multiple sets of data for various tests, which all go through the constructor, which would force you to write multiple test classes. TestNG solves this better by allowing you to provide separate data sets to individual test methods using the @DataProvider annotation.
But don’t worry, now you can achieve the same with the junit-dataprovider, available on Github. Pull in the dependency with e.g. Maven.
<dependency> <groupId>com.tngtech.java</groupId> <artifactId>junit-dataprovider</artifactId> <version>1.5.0</version> <scope>test</scope> </dependency>The above example now could be rewritten as:
@RunWith(DataProviderRunner.class) public class StringSortTest { @DataProvider public static Object[][] data() { return new Object[][] { { "abc", "abc" }, { "cba", "abc" }, }; } @Test @UseDataProvider("data") public void testSort(final String input, final String expected) { assertEquals(expected, mySortMethod(input)); } }You’ll see: no constructor. In this example it doesn’t have many benefits, except maybe for less boiler-plate, but now you can create as many @DataProvider-annotated methods which are fed directly to your @UseDataProvider-annotated testmethod(s).
Sidenote for Eclipse: If you’re using that IDE, the JUnit plugin is unable to map the names of the passed/failed testmethods to the ones in the testclass correctly. If a method fails, you’ll have to find it back manually in the testclass (or vote for the patch Andreas Smidt created to get this fixed in Eclipse).
In the mean time, if you’re stuck with JUnit and you’d love to use this feature you’re so accustomed to using with TestNG, go ahead and try the junit-dataprovider now.
Published at DZone with permission of Ted Vinke . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/alternative-junit | CC-MAIN-2020-24 | en | refinedweb |
The Changelog – Episode #389
Securing the web with Let's Encrypt
featuring Josh Aas
Transcript
Securing the internet is obviously a big deal. Back in May of 2013 you thought so as well, and you started the Internet Security Research Group… But since then, Let’s Encrypt has issued (in all caps) one billion certificates, and that’s a big deal. That was an announcement you made February 27th. Talk about that moment for you. What was that like, to pin that post?
I still pretty clearly remember sitting around, debating with our staff whether we’ve issued one million certs in the first year or not. When we started, we had no idea what the scope of this would turn into. A billion is a big number, and it’s amazing to get here. So many ideas never turn out to what you wish they would turn into, and it’s pretty exciting that this team has built something that turned into what we wanted to be, which is serving so many websites around the internet. We’re getting close to around 200 million now, and that’s fantastic.
It’s often interesting because you can take for granted what’s right there in front of you today… So I kind of look at it like, new developers coming into the scene in the last two years - let’s say since the inception of Let’s Encrypt - and just the idea that it’s there and it’s fairly easy now to request a free certificate… We’re in a day now where I suppose the security of the internet is much more important as we all become more dependent on it, and it’s more prevalent in our everyday lives, especially in a day where right now we’re using a Zoom chat, so we’re assuming that this is encrypted… I’m not sure we’re seeing anything that’s concerned…
Well, we’re recording it ourselves, so maybe it’s not too private…
Right. The point is that not all the Zoom calls are ones you want to put onto the internet.
Yeah.
Obviously, security is a pretty interesting thing, but we came from a day where SSL certificates were very difficult to get, generally expensive, and just the process was very cumbersome. Now it’s a fairly easy process. People take that for granted.
Yeah. On the one hand, we want to be in a position where people can take us for granted, because we want the service to just happen for people. Ideally, you could just set up web servers and not even know that you have an SSL certificate, let alone where or how you got it. We’re all about automation and removing humans from the loop, so people have to do less.
[00:04:22.12] We’d love to get to a world where every time you spin up a server, it’s just got the certs you need in the background, it installs them correctly, and everything just work; people don’t need to know about us.
On the flipside, we do want people to know about us, because we’re a non-profit, and we need people to know about the great work that we do, and help fund our work. So yeah, every day we go out and try to put ourselves in the position where people can take us for granted, but… It does have some negative consequences.
Kind of a catch-22… What are your plans around that?
We continue doing what we’ve been doing - providing great service, building things that people can rely on, and make the internet more secure. On the technical side, it just happens… But we’ve got great communications people, and they go out and talk about what we do, talk to potential funders, and so far it’s working out great.
I always think about Wikipedia and their opportunity to throw Jimmy Wales’ note up there once a year, usually in December, and say “Hey, we’re a valuable resource. Send us your money.” And I was thinking like “What’s the Let’s Encrypt equivalent of that?” It’s probably a bad idea… You’ve got 200 million sites, but you don’t exactly wanna be injecting anything into that experience. Like you said, you wanna be as seamless as possible. So do you beat the drum mostly on the blog, or are there campaigns? What do you guys do to let people know what you’re up to?
We certainly don’t wanna go out there and inject messages into systems that people depend on. [laughter]
That’s a very bad idea.
Yeah… I didn’t think so.
We’ve got a social media presence, a blog, we also have a lot of contacts and people who understand what we do and support us, and we meet with them all the time. We go to companies, explain what we’re doing, “We’re here for you.” We talk to open source projects… Anywhere that we think understanding what we do can help. It’s just a lot of work for you to go out there and do.
Sometimes the media picks up good things, like a billion certificates. That’s really helpful, to get press coverage. Unfortunately, sometimes people find out about us when there’s a problem, like when you have a service that so many people depend on. When things go wrong, that’s when people notice. That’s when they stop taking you for granted. That’s not obviously something that we strive for. We’d prefer that that never happened. But software is complicated, systems are complicated. Every system has problems once in a while.
Some people learn about us when we have problems, and that sort of doesn’t inject the message into their life… Which hopefully is like “Look, this is something I depend on”, and when there’s an issue, you realize how much you depend on it. And the best way to help out is to support us.
What are some of the bigger problems you’ve had to mitigate over the years?
It mostly just comes down to normal software bugs. We have a software stack called Boulder, that is sort of the core of the certificate authority. It’s written in Go; it’s non-trivial in size, although it’s mostly been developed by an average of three engineers over five years.
So it’s fairly complex, and it’s non-trivial in size, and like all software, every once in a while there’s a bug there… And those bugs can cause either stability, or compliance, or security issues. We haven’t had too many security issues, but we have had some stability and compliance issues. When a bug pops up, usually we’re very quick to fix it, but when you’re serving 200 million websites…
[00:08:03.05] …any little thing becomes sort of a big thing. But I’m really proud of our track record here. We have a great track record for stability and reliability in security. And when incidents do come up, I’m particularly proud of how well we deal with them. We typically fix issues in a couple of hours max, then we go out and talk about it with public reports, and detailed public information, and lots of transparency very quickly. On most within a few hours. We really work hard to follow up and make sure that that type of problem doesn’t happen again; we use those things as a learning experience.
Well, given the opportunity, and potentially even by design, the ability for people to take Let’s Encrypt for granted – for the uninitiated, how do you describe Let’s Encrypt? What’s Let’s Encrypt today?
You mean how do I describe it to people who don’t really understand what SSL certificates are?
No, let’s take it from a developer’s point of view. Somebody who kind of gets it, but doesn’t – they’ve heard of Let’s Encrypt, but they don’t know all the bits and bobs; they don’t know all the details of what Let’s Encrypt is. What do you do?
Yeah, so if you’re a developer and you wanna set up an HTTPS site, you’re gonna need a certificate. Normally, without Let’s Encrypt in the world, you’d have to go find some place to buy a certificate and decide what kind of certificate you want, decide how much you wanna pay… You’d probably have to create some sort of certificate sign in request, or fill out some form containing a bunch of details about what exactly you want in your certificate… It can be a pretty time-consuming, costly and complicated process, and it’s frankly just really confusing. I think it’s the biggest reason that people didn’t deploy HTTPS prior to the existence of Let’s Encrypt.
So Let’s Encrypt really just tries to do away with all that. We try to make things as simple as possible. We have an API, you just submit a request using some API client software; you don’t need to write it yourself or know how it works. You just download some software for whatever platform you wanna use. That software knows how to talk to Let’s Encrypt. You just tell it what domains you want certificates for. Typically, the software will just go out and get the domains, complete the challenges, do what you need to do to get the cert, and then sometimes it’ll even install it for you.
All this doesn’t require you to know anything about how certificates work, or how you get them, or what’s in them. It doesn’t require any payment. One of the most important things about not requiring payment is that’s not necessarily just about the amount of money involved. It’s not free just because free equals zero dollars. It’s free because if you’re sitting in some big company and you wanna set up a site really quickly, and you wanna use best practices and deploy HTTPS, if you’ve gotta go to accounting and get a credit card and get approval to spend money, and set up recurring charges, and things like that…
It’s not gonna happen.
…even if you’re charging 10 cents a month, it’s a pretty big friction for you. You’re just gonna say “I’m not gonna go through this whole silly process. I’m just gonna set up the site without HTTPS.” And now you’ve got another insecure site on the web.
So not charging money is about not creating friction in the process, and not requiring humans to be involved any more than necessary. So yeah, Let’s Encrypt is a really automated, easy to use, free way to get a certificate.
We first covered Let’s Encrypt on the Changelog back in March of 2017, episode 243. We had Jacob Hoffman-Andrews from the EFF on the show. Probably a fun episode to go back and listen to in light of the success you’ll have had… Because that was very much near or shortly after the kick-off. So from there to a billion in under three years is pretty amazing. I think free is a huge aspect to that, but I’m just curious, from your perspective, what did all get right, in addition to making it free, which is a big aspect, of course? …to get the spread on. You spread like crazy, which is amazing. What did you do right to get here?
[00:12:20.05] First of all, let me recommend going back to that episode to anybody who wants to. Jacob is our lead software engineer, and he is brilliant. You’ll never regret listening to him.
Yeah, he was a great guest.
Like most things in cryptography adoption, it’s all about ease of use. You can come up with the most brilliant security or cryptography mechanism you want, but if it’s not easy enough to use, it’s not gonna see deployment. Not at scale anyway. So from the beginning, it’s been all about ease of use. For us, that really means automation and really just making it so people don’t really have to do anything.
In order to automate, you just wanna have computers do the work. On the Let’s Encrypt site we’ve got a bunch of computers that do the work on our side. It’s a little more complicated than that, but you know, computers do most of the work… And then on the client side, for people requesting certificates, we needed client software that works for everybody. And people use a lot of different stacks out there. Some people are on Linux, some people are on Windows, BSDs, and people are using Apache, NGINX… Whatever.
There’s a lot of different deployment environments out there, and there’s no way that we could write client software for all of those environments ourselves. It’s just not possible. But we came up with a really well-documented and standardized protocol, and then our community - it’s just amazing - has gone out and written hundreds of clients that work with this protocol. So now, no matter what your application stack is or your software stack, there’s almost certainly a Let’s Encrypt client out there for you to use, and all you need to do is just find that client, install it, and it will do most of the work for you. That’s something we really couldn’t have pulled off without our community.
Did you bootstrap any of that? Did you say “Well, we’ll do the Apache integration, or the NGINX integration and get the ball rolling”? Or was there immediate community support post-announcement, and maybe the publishing of (is it a spec?) the actual way it works.
Yeah, the protocol is called ACME, and it’s an IETS specification now. Before that, we just published the spec for it. We did originally create a client that we developed not for very long, because we realized that us putting resources into one client ourselves just does not cover enough use cases. There’s so much out there… So we really need to focus on the community-building clients and not us doing it.
And for that client, which has now been renamed to Certbot, the Electronic Frontier Foundation (EFF) - they were volunteering most of the work to make that client anyway. It wasn’t the Let’s Encrypt server-side engineers doing it. So we decided pretty early on that it makes more sense to just turn that client over to EFF and make it an EFF project, since they were doing most of the work anyway. And we wanted to focus on supporting this strong community instead of building clients ourselves.
So we did sort of try to bootstrap it by building this client early on, and it served its purpose well… But it’s at a much better home at EFF, and it’s really grown into an amazing client over there.
When we go back to the inception of things - I don’t wanna go too far back, but just enough to understand the crux of the problem. Obviously, an unsecure web is an issue, but what was the biggest thing that stood out to you, that made sense to move forward with the Internet Research Group, and that being the foundation behind Let’s Encrypt? What was the biggest problem happening, that was sort of like “This has gotta stop.”
[00:16:06.17] Yeah… There’s a few different people involved in starting ISRG, and I think they all have their own personal motivations for why they wanted to get into this… I wanna make clear this might not necessarily be true for all of them. But for me, at the time I was running the networking group at Mozilla, the group that does all the networking code in Firefox. And one of the most frustrating things about running that team is there was nothing you can do on the browser-side to make sites use HTTPS. So if the site doesn’t use HTTPS, you’re just stuck doing completely not secure networking, and there was no amount of code you can write, there’s no clever code you can write; you’re just stuck.
So if you’re sitting there, in charge of the networking stack for a major browser, it’s very frustrating that there’s nothing you can do about this. You can’t improve the situation. So we started thinking about “What’s the problem here? Why are people not using HTTPS?” And the biggest problem seemed to be that getting and managing certificates was too complicated, or too costly, or too time-consuming. For whatever reason, people didn’t wanna do that. Everything else is pretty easy. If you wanna turn on TLS in Apache or NGINX, it’s a pretty easy config flag. The software is all there. Easy to turn it on. You just can’t do it without a cert.
This really came to a head when I was participating in some of the discussions in the IETF about standardizing HTTP/2. That’s kind of a mouthful, so I’m just gonna call it H2 from here on out.
We do as well.
One of the big discussions in the standardization process for H2 was “Should H2 require HTTPS? Should it require TLS?” And for me, that felt like a no-brainer. Like, yeah, obviously H2 should require TLS. At that point I think it was like 2011 or 2012 when this conversation was happening, and it seemed like we know that not using TLS is a huge problem. It’s 2011. Why in the world would we ever create a new protocol that’s not secure by default? That seemed just crazy.
And there was a lot of pushback on that idea. Part of the pushback came from proxy providers; basically, people whose software and jobs depend on intercepting web traffic. So that’s sort of the expected pushback. But other than that, it just seemed like a no-brainer to me. But there was another objection, which was that if you make H2 require HTTPS, you are effectively gonna make it pay-to-play, and you’re gonna make it much harder to deploy, because you won’t be able to deploy H2 without buying certificates… And you won’t be able to deploy H2 without going through the certificate obtaining and managing processes. So the idea was that requiring TLS would make H2 deployment a handicap, basically, and pay-to-play.
That frankly felt pretty reasonable, and it felt to me like “If I’m gonna continue with this position that it should require TLS, and that it’s crazy to not to, then I need to be willing to deal with the criticism here. I need to have some answer to this.” At the time, I didn’t really have an answer. They were right - one of the great things about the web is that a lot of things don’t require you to pay. And if we required TLS for H2, you would effectively be putting a financial tax on anybody who wanted to deploy H2.
[00:20:05.17] And likely, people wouldn’t play.
Right.
So what’s the point of even creating the tech, or the new protocol, the new spec, unless people would use it… Except for the ones who can obviously pay.
Yeah, you hamper its adoption, and you also hamper the people who can’t afford to adopt it, right?
Yeah… I mean, the big companies that do it - you know, Google, Facebook, whatever…
For sure.
…that’s a lot of traffic on the web. So it still has a benefit, but I don’t think we should be designing major protocols like H2 primarily just for the biggest players out there. As centralized as the web has become in many ways, I think it’s still important to pursue some of the ideals of accessibility and making sure everyone has the ability to participate on the web.
So I thought those criticisms of requiring TLS were legitimate, and if I was gonna run around telling everybody that they have to use TLS all the time, then we needed to deal with that problem. So I went back to the team I was working on then, and we talked about a lot of different possible solutions, but it was hard to find any solution that was gonna solve the problem, and solve it in a reasonable amount of time. There were ideas where it’s like “Well, if we do this, then maybe in 10-20 years the situation is different and we can do this”, but that’s way too far. We should have done this 10-20 years ago, not be planning to do it 10-20 years in the future.
So the only solution we came up with that we were pretty sure would work, and that might work in a big way in 5 years or less, was that there just had to be a new certificate authority, that was public benefit, really easy to use, doesn’t cost money, and available all over the globe. Available everywhere, to everyone. Without that, we just didn’t see how we were gonna get out of this.
To be honest, I don’t think anybody involved in those discussions was thinking like “Man, I’m excited to spend the next 5 years of my life building a CA from scratch, and dropping all these other things that I wanted to do in my career, and build a CA.” It wasn’t the most attractive project. But it felt like this is what’s gotta happen. If we don’t do this, the web is gonna be not secure for a long time.
So we did it. We went out and started a new CA. At the time, I knew nothing about how to build or run a CA, so it was a lot of learning from me, and I think everybody involved. I don’t think anybody – we had some advisors who had some experience, but I don’t think anybody actually building the CA had ever built one before. So it was a big undertaking, but that’s why we did it.
And here we are, five years later, and… When we started, I think 39% of all page loads - so not websites, but 39% of the time you loaded any particular web page, it would be encrypted. And that’s mainly because of big websites like Google and Facebook and other big properties… And everything else wasn’t. Here we are, five years later, and in the United States I think we’re approaching 92%. Globally we’re over 80% now. And those have a great trendline up. So five years later we’ve encrypted most of it. We’ve got some more work to do, but we got there.
I’ve gotta imagine starting a CA from scratch is an undertaking… You’d mentioned that you had some advisors obviously giving some advice (that’s what advisors do), but the majority of everyone involved in co-founding the Internet Security Research Group had no clue how to do some of these things… So how did you get a clue? How did you do this? What’s involved in building a certificate authority?
Well, we got some advice from people, like you said, and sort of laid out some of the basics of how it works. There is a document out there called The Baseline Requirements, which is a document built by the CAs in the browsers combined, sort of come together in a forum called CA/Browser Forum. They created a document of all the rules and requirements that all CAs are required to abide by. And you can figure out a lot about how a CA is gonna have to work based on what those rules are… So we read those very carefully.
We hired some auditors who audit us every year, to make sure that we’re compliant with those, and some other rules. Our auditors helped us figure out some stuff… But yeah, mostly we just consumed all this information and started drawing out plans for how things work, and then we had iterated on them until it all seemed like it would work. Then we went out and bought the hardware, signed the agreements… Just got to work. Some things had to be iterated on a couple of times, but… Pretty much how you figure out anything else you don’t know.
Yeah. If I grabbed the right document, it’s 68 pages. I could imagine that’s quite a read, for one… Two, who gives the authority for a CA? Who do you get the authorization from to move forward?
Yeah, so you can start a CA and you can do whatever you want as a CA. The question is who trusts you? So if you start a CA and you do whatever you want, pretty much nobody’s gonna trust you, so it doesn’t matter that you’re really running a CA. If you’re running some sort of private CA, you need your clients to trust you. If you’re running a public CA like Let’s Encrypt, basically what that means is that the general public trusts you. What that comes down to is the browsers trusting you.
So if you wanna start a CA, you need at least all the major browsers to trust you. Today, that would be Google, Mozilla, Microsoft, Apple. Those are the big ones. If any one of them doesn’t trust you, then this whole thing falls apart. You can’t have a website that works in three of those browsers but not on iPhones, or something.
[00:27:51.20] So when you talk about becoming a publicly-trusted CA, what you’re really talking about is getting those four browser makers to trust you… And they all run what are called root programs inside their organizations. And those root programs decide who they trust, and then follow-up on compliance from everybody they’ve already decided to trust.
So when you start a CA, you need to build your systems, then you need to get them audited against the current auditing guidelines for CAs. Then you take that audit report and you include it with an application to each one of those root programs. So you’re submitting at least four applications to four different root programs, and they all have their different ways of applying.
Some of them are relatively simple emails or bugs to file, and some of them are longer applications. But you apply to all four of them, and then you wait to get accepted. That can take anywhere from three months to three years to get accepted. Then once you’re accepted, you need to wait for them to actually put that trust into the browsers.
So for something like Chrome or Safari, what that means is you’re waiting for them to ship a software update that includes your root of trust in it. And until that happens, until a user gets that update, their device still doesn’t trust you.
In the case of Microsoft, it’s more dynamic. They don’t do it through software updates necessarily. If they see a cert they don’t understand, they will query a server and check. So trust in the Microsoft ecosystem can be done pretty quickly. Once you’re in, you’re in. The real problem is stuff like Android in certain parts of the world. People have old Android devices that they don’t get updates anymore, and they never get rid of them, and in some cases they’re still manufacturing Android for devices… And those things are never gonna get an update. So if you want to get those devices to trust you, you’re really just talking about waiting for them to leave the ecosystem.
So the point of this is - between the time that you apply for trust and get approved, and then all the devices in the world actually trust you, you’re talking about a period of 6-10 years.
Wow. So commitment is required, I suppose…
Yeah…
…without saying so much. You think about some people’s plans for new ventures, whether they’re small ideas or big ideas; any sort of itch that’s scratched. So we talk to a lot of people who scratch itches around here and do something about it, and you have to think about your commitment level to said mission. If you have a horizon of say a year or two years, and you’re building a CA, maybe you need to stretch that quite significantly to 5-6, or maybe even further.
Yeah.
What was your horizon for this? Were you like 10-20 years that you kind of knew all this beforehand, or was it sort of learned as you go? Because you mentioned a lot of this was learning as you go.
So what I’ve just described is the basic process of getting trusted from scratch. And that does require a big commitment. It requires quite a bit of money to get set up to a point where you can pass audits and even apply, and then every year while you’re waiting for all this stuff to happen for 6-10 years you have to stay compliant, get audited every year. So you’re talking millions of dollars and 6-10 years before you can even be a publicly-trusted CA in any meaningful sense. That’s the basic process.
There is a way to make a shortcut, which is how Let’s Encrypt was able to start without waiting 6-10 years first. So we did go through the process that I’ve just described, building up our own root of trust from scratch… But the world right now does not really rely on that yet, because it has not been long enough.
[00:31:52.23] And somewhere around mid-to-late next year we’re gonna switch over to our own root that’s trusted from scratch. But from our inception through now, we have what’s called a cross-signature… Which means we knew we didn’t wanna wait 6-10 years to start offering Let’s Encrypt services, so we’ve found another CA that understood what we were trying to do and was willing to help. They had a root of trust that was already trusted.
What essentially happens is we create a contract, an agreement between us, and then their root of trust essentially lends its credibility to us. So they issued a certificate that our root is trusted by their root, and their root is trusted by the browsers, basically. So that’s called a cross-signature. We acquired that before we did much of anything… Because without that agreement in place, there’s really no CA.
So one of the first things we did was get that agreement, because without that agreement in place, there’s no point in buying hardware and doing anything else… Because –
It’s a long journey.
…we’re not gonna sit around and do nothing for 6-10 years. So that was a really critical agreement. We got that in place with a company called IdenTrust, who’s been a great partner for a while now. So we’re trusted through IdenTrust today, and mid-to-late next year we will stop using that cross-signature and just be trusted on our own.
That’s a big deal.
Yeah.
Will it be transparent, that trust, I suppose? …since it’s still you, it’s still trust, it’s still the same browser…
…unless you’re running an old Android device.
That’s right.
Yeah… You know, their root is really widely trusted, and that’s been fantastic. And it’s trusted all the way back into early Windows XP, and all the Android devices. The problem with that root is, you know, the longer a root is around, the more trusted it is, but eventually it expires. And that root expires next year.
I don’t remember the exact lifetime on it, but I think that’s a 20-year-old root, at least, if not more than 20 years. So the advantage of an old root is that it has really widely-trusted status, but the disadvantage is that it’s gonna expire soon. So we will be switching from an old root that’s very well trusted, to a younger root that is also very well trusted, but admittedly not quite far back as IdenTrust. But if you’re still running Windows XP on the public internet, you might have bigger problems than your certificate. Probably the same goes for really old versions of Android.
You’d mentioned the dollars involved for those 6-10 years, and from just groking past blog posts from you or others at Let’s Encrypt, it’s primarily a people cost, so staff. Is there a lot of cost aside from that when it comes to the fast-track that you took, or the non-fast track? Or the cost is primarily people?
Certainly the cost for us to run the CA today is primarily people. Roughly speaking, paying staff is about two-thirds of what we spend every year. There’s startup costs, and then there’s ongoing costs. For startup costs - usually, those cross-signing agreements do cost money, and that’s a non-trivial amount of money… So when another company agrees to trust a new CA, they are responsible for that trust. If the new CA that they’re trusting messes up, it’s on them. So in exchange for the liability they’re taking on by trusting, in our case, just some guy from Mozilla that walks into the office and says “I’m gonna quit my job and start a new CA, and it’s gonna do all these amazing things. You should trust–”
Hypothetically, right?
[00:35:53.23] Yeah… “You should trust us, and put your business and your reputation on the line” - it’s not an easy ask. So these cross-signing agreements - there’s a lot of liability involved, and for that reason they end up being non-trivial amounts of money. So that’s a big startup cost for anybody. Then going forward from that, that’s probably the biggest startup-specific cost, aside from maybe initial capital; you’re gonna need to buy servers, and HSMs, and things like that.
Ongoing, we have to buy a certain amount of hardware every year. We do use some cloud services, we use some external services, but mostly, aside from people, it’s about the data centers and what’s in them. Publicly-trusted CAs are not allowed to operate in the cloud, so we can’t run our CA systems on AWS or GCP or Azure or something like that. We have our own hardware in special, secure rooms inside data centers, and they’re not even normal data centers; they’re special, walled-off rooms in data centers, with a bunch of extra biometric access, and stuff like that. That stuff is a non-trivial expense, and you’ve got all this hardware that goes inside, you’re gonna have a lot of redundancy… So we pay for that stuff, and that’s where a lot of the rest of our budget goes.
Yeah. In a world where Let’s Encrypt is ubiquitous, which is what we’re getting to - liked you’d mentioned, 2,5 years ago 100 million certificates issued; a month or two ago, a billion. It’s quite a massive growth. In a world where Let’s Encrypt is ubiquitous, what’s the point of other CAs? I’m just thinking, why would anybody not use free?
There’s a lot that other CAs do that we don’t do. For example, we offer one specific type of certificate. You can’t change very much about it. We think shorter certificate lifetimes are better, so we don’t let anybody create a certificate that’s longer than 90 days in lifetime. And we also don’t offer human support. So there are a bunch of reasons to choose other CAs. For one thing, we don’t sign this sort of normal contracts; some people have procurement requirements, or they want certain things in contracts from their vendors, and we don’t do that. We don’t provide support. You can’t pay us for 24/7 phone support. If you don’t like the type of certificate we offer and you want something else, or you want it configured in some special way, we don’t do that…
So we’re sort of one size for everybody, and if that doesn’t work for you, then there’s luckily a lot of commercial CAs you can go to, and they’ll be happy to help you, I’m sure.
So you’re saying Let’s Encrypt is for everybody, but not for everybody.
Yeah, it’s a pretty basic option. I think it’s basic for two reasons. First of all, we’re trying to be a really efficient organization, so… As complicated as running a CA is, we try to scope that complexity and limit it as much as we can. We don’t wanna offer a ton of choices to people, because complexity just leads to more bugs, more cost, and things like that.
Another thing we’re really focused on is best practices. We tend to do whatever we think is the best practice. An example of that is the cryptographic algorithms that we offer, or the certificate lifetimes that we offer… Or you know, you can only get it through certain validation methods the way that we do it, because we think those are the only secure ones, or something like that.
But other people have other opinions. So between trying to be efficient and trying to focus on best practices, we offer a pretty limited service, that I think works for a lot of people, but not everybody.
And the web is huge. We may be serving 200 million sites right now, but there’s a lot more than 200 million sites right now, and they should all be using HTTPS. So there needs to be a robust ecosystem of CAs in the world, so that people who need something else besides what Let’s Encrypt provides have a place to go.
[00:40:05.13] Given the requirements to even be a trusted CA, it doesn’t seem like something that there are just handfuls of people listening to the show saying “I’m gonna drop what I’m doing today and become a CA.” It’s just such a long road. I almost think you have to really be invested, I suppose, in securing… And I guess that’s a whole different kind of problem or different kind of business. But given the amount of effort it takes to get there.
To start a business today, you have to kind of get to product-market fit. Create a product that people want, and people will buy. in this case, you can do that as a CA, but still not be able to sell it because it takes you so long to become a valid resource for giving it the trust; the trust is such a big deal. It’s an interesting business to create.
Yeah, creating a CA is not a decision to take lightly, but the way that most people create CAs now is not to wait for that process to play out.
They do the cross, like you’ve done.
A cross-signature… Or you just go acquire another CA. You just buy another CA.
There are at least a hundred existing publicly-trusted CAs. I’m not sure exactly how big the list is. They buy and sell each other all the time. Sometimes they go out of business. I don’t remember how many publicly-trusted CAs there are, but there’s at least a hundred… And if you wanna start a CA, you’re gonna start a serious business. One way is to go spend x millions of dollars on the cross-sign, or you can spend x millions of dollars just to go buy a CA.
Most of these CAs you’ve never heard of. They’re very small. They’re not under-the-couch money, but if you’re starting a trucking company and you need to go buy ten million dollars’ worth of trucks - that’s something people do all the time. You can probably go buy a CA for something in that order of money, so in some ways it’s not really that different from starting any other business, I would imagine. I only have experience with Let’s Encrypt in the cross-sign, I’ve never actually bought another CA… But I don’t think that the startup requirements are really that different, just because most people don’t wait for the from-scratch process to play out.
You mentioned the other certificate types. I’m just curious on your thoughts on extended validation certificates and the idea of wrapping up identity into encryption; establishing a secure connection. And then you also have this extended validation, so you know at least the CA trusts that the person who owns the certificate is who they claim to be. What are your thoughts on that style? I know you don’t offer it, but is it worthwhile?
I don’t know if I can say whether that’s worthwhile for any particular – you know, some people have specific needs, regulatory needs, or whatever… So I don’t know if I can say whether that’s worth any individual in general should do it. But I do have some thoughts… First of all, trying to include the identity of a legal organization in a cert does not affect encryption at all. You can’t tie the two together. You can put them in the same cert next to each other, but EV certs and OV certs, which contain this legal identity information - the encryption is no different than a DV cert. It’s the same.
The only theoretical value to that is if you display the identity to the user, and then let the user make a decision based on the identity they see. The problem there is – well, there’s a bunch of them. First of all, browsers are increasingly not showing that information to users, so there’s no point in having it in the cert if the browsers aren’t gonna show it to them. And the reason the browsers aren’t showing it as much anymore is that most researches show that people either don’t look at it at all, or don’t understand it when they do see it.
[00:44:02.07] So you’re not gonna build a secure system that relies on the average user on the internet looking at information and making informed decisions. That’s just not how security works. If that’s your plan, it’s not gonna result in generally increased security for anybody. It only works when it happens automatically, and doesn’t require people to look into it individually.
There’s a bank out there called USAA, and if you look at an EV cert from them, it says “United Something Automobile Something”. The spelled out name of the business is very long, and nobody knows what USAA stands for. They just know the bank has USAA. So when you see that kind of information pop up in an EV cert, how can you possibly expect anybody to make a reasonable decision about that.
So I don’t think that it’s very useful to put identity information in a certificate that’s used on the general internet… And the research backs that up, and browsers tend to agree and are dropping that from the UI.
Yeah, that’s true.
I don’t have any stake in this - we don’t issue it - so in some ways I don’t really care, but it seems not very helpful, and probably it’s not going to have a strong future on the internet.
No, I was just curious your thoughts on it.
I think at one point it was interesting because it was different. Not all certificates you’ve got gave you the option. So I can recall a day whenever you to GitHub.com, and it would say separately, twice almost; someone’s double-branding even. You know, heavy on the brand side.
With a big, green background, and then it was like very official…
Yeah, it seemed official. It seemed cool, it seemed secure. So I would think - which I don’t know all the research behind it, but from a UI perspective it’s probably cumbersome because it’s redundant… But it looked different than someone who didn’t pay anything for their certificate, or didn’t buy a certificate and then offered that… And it was unique. So you would see it happen on people who would wanna pay for it, I suppose.
Yeah… The problem there is that once you see it, it might possibly seem like a good thing to you… Although, again, the research shows that people don’t really react to it in a useful way. The problem is you don’t notice the absence of it.
Right.
If GitHub just didn’t have that, you wouldn’t say “Hey, it doesn’t have that thing. I’m gonna leave.”
Yeah. I may hop onto GitHub today and it doesn’t have it today. I don’t care.
Right. So it just turns out not to be very useful. And also, there’s a lot of issues with how it’s validated. In domain validation, where you’re just proving control of a server before you issue a cert, there are pretty clear and strong ways to do that validation. When people do identity validation, it basically involves phone calls, and faxing around document copies of your articles of incorporation, and copies of driver’s licenses, and stuff like that. It’s easier to mess with.
Pretty famously, recently someone registered Stripe Inc. in some state that’s not where the normal Stripe payment company is… And since registration of businesses is by state, they had an EV cert that they had Stripe Inc. Obviously, that’s not what you’d expect, but it’s not a bad cert. They legitimately did own Stripe Inc. in North Carolina, or wherever it was that they did.
Right. It’s like a namespace conflict, but it wasn’t inappropriate. The CA that issued that certificate could have went out to their business and got their articles of incorporation, and all the stuff, in the state that they’re in. So it’s completely valid.
[00:47:57.04] Yeah. There’s ultimately nothing wrong with that cert; they sort of arbitrarily revoked the cert, because they say “Well, we just don’t like that cert.” It brings a lot of arbitrariness into it. And that is a cool party trick, and it demonstrates some problems with EV certs, but the real issue is that nobody seems to care what’s in the cert anyway, so it doesn’t matter if you – you know, nobody really looks at it or makes security decisions on the basis of that stuff anyway, so it doesn’t matter. Namespace conflicts are sort of a second-order issue.
Right. I think it’s interesting that it was for a time almost like a status symbol amongst technology companies to have that. It was like “We’ve arrived” or “We have enough money to buy the more expensive–”, whatever it is. And really the browsers – like you said, the browsers, when they started to move that out of the way, in the browsers, when the vendors say “Yeah, let’s just go ahead… No one looks at it, except for nerds…” Most people don’t even look at the address bar. They don’t even know it exists, which is why the number one thing people google is “Google” or “Facebook”. They google Facebook to go to facebook.com, when they could just type it into their address bars, because people don’t…
Yeah, they’re missing four characters…
…look at the address bar, let alone “Is the background green? Does it have the thing?” You know… So really the browser vendors made that not a thing. I mean… That’s super-interesting. They’ve kind of like – because that was an advantage of a certain certificate or another; or it’s kind of an upsell. Isn’t it always an upsell? “Hey, get the Extended Validation Cert.” And it’s like, just the movements of the web, and the decision-making of the browser vendors basically just quashed the value there, because it was really only in the status symbol, like you said.
Yeah. I mean, “the advantage” is not really an advantage, because it doesn’t actually mean anything. It just takes up a bunch of UI space.
It’s kind of fascinating.
Yeah… Again, if your plan for security is to show average users some information and then expect them to make a really good decision based on that information, that is not ever gonna work. It doesn’t work for EV, it doesn’t work for anything else.
So Josh, we’ve been talking about Let’s Encrypt’s success over the five(ish) years you’ve been doing this. A lot has changed since the beginning, a lot has changed since 2017 when we had Jacob on the show saying “Let’s encrypt the web”, mostly extreme amounts of adoption. You have some stats in your billion certificates blog post that in June of 2017 approximately 59% of page loads used HTTPS globally, 64% in the U.S, and today that’s 81% of page loads use HTTPS globally. I think you mentioned that earlier in the conversation. And we’re at 91% in the United States. I wanted to reiterate that… That’s a massive number. 91% in the U.S. So you guys have played a large role in that. And I’m curious, because there’s also been – like, the web has changed alongside you, and the trends are changing, and security is more important, and all these things… So I’m curious, how much do you feel you’ve been pushing this up the hill, and how much do you feel that maybe you’ve been riding a wave in the last couple of years?
It doesn’t feel like pushing it up a hill so much. I think there was a lot of demand. I think developers understand that using HTTPS is a good thing; they understand that without it you’re not secure. I don’t think it’s hard to convince most of them to do it. I think they’re ready to do it if they have a reasonable option for doing it… And by reasonable I mean very easy to use.
[00:52:25.00] So we’ve put our service out there, and it’s not that hard to convince people to use Let’s Encrypt. We don’t really market or engage in too many activities around really trying to convince people to use Let’s Encrypt. Most of our efforts revolve around trying to get people to give back for using Let’s Encrypt, and keep stuff going. But yeah, it definitely doesn’t feel like pushing something uphill. It feels like people wanna do the right thing, they just need the tools. And now they have them.
I think the developer mindset - it’s my own personal opinion and experience - has changed, probably from “You should encrypt anything that’s important…”, I’m talking like 3-5 years ago that was kind of the ethos… Anything important - if you’re signing in, obviously if you’re making e-commerce transactions - those things should all be encrypted. Taking passwords etc. But that’s pretty much what needs to be encrypted. And I think nowadays, generally speaking, the ethos is “Just encrypt it all.”
All things.
Encrypt all the things.
Yeah. The thing that gets me about the first argument, that only important things should be encrypted, is that people need to remember that when data is not encrypted, not only can it be read by other people, but it can be modified. So any unencrypted traffic can have stuff injected into it. And it doesn’t matter whether that traffic is important or not. So if you’re on your banking website in one tab, and you think “Oh, that’s important. That needs to be encrypted”, and you’re over in another tab looking at memes, or something, and you think “These things are not important. These are just some mass-media GIFs flying around the internet. Why does that need to be encrypted?”, the problem is that unencrypted traffic can be modified. So you can have malware or some kind of exploit loaded into the traffic for that tab, that exploits your computer and now does stuff with your banking info, because they owned your browser through the unencrypted traffic in the meme tab.
Don’t go changing our memes.
It is really not a good idea to try to draw distinctions between what is important and what is not, because it’s all exploitable in the same ways, and that line just never gets drawn in the right place.
Yeah. Which makes celebrating a billion certificates all that more important, because you started out at the bottom and now you’re here, to use a rap song very wisely…
And that’s the thing…
You used that rap song very wisely.
…I mean, in 2017 a hundred million, and now you’re at a billion, five years later - that’s a big deal, and that means that so much more traffic and so many more people are not getting advantage taken over them. Or the opportunity to get the advantage taken over them because of being secure. And in a day prior to this, it cost money to enter; not that the money factor – I think it was just a barrier to the entry to using SSL, for the Jerods and the me’s of the world before, who said “Hey, only important traffic needs to be encrypted.” And now it’s like “Well, everything. For those reasons.” And that’s a big deal.
You mentioned that you haven’t done much to get there, so – I mean, going from zero to a hundred million, to a billion, no marketing, not much involved, just mostly community work, when you have to account for how you got here, how did you get here? What are the things you did to do that, specifically?
[00:55:58.10] Well, like I said, there was a lot of pent up demand, and we gave people the tools, and we made them easy to use. That’s really the gist of it. And then some people start doing the right thing, you get the numbers high enough, and then the mindset of the world switches from “HTTPS is an optional thing that you can have if you wanna spend time doing that” to “HTTPS is the standard thing that you need to do all the time, and if you don’t do it, you have a problem.”
One of the biggest accomplishments for us and for everybody – you know, it’s not just Let’s Encrypt; we’re not the only reason the web is where it is today. There’s lots of different people working on different great projects around the world that have helped promote HTTPS… But one of the big accomplishments of that community is that HTTPS is considered the standard today.
You set up a website. If you expect people to visit it, you need to have HTTPS. That’s a huge mindset change. [unintelligible 00:56:56.02] ways in which the internet has changed similarly in the past for other technologies. It is hard for me to imagine – or, not imagine… I don’t know everything about the history of the internet, but I don’t remember any other thing fundamentally changes how almost all this traffic flows across the internet in less than five years. I can’t think of another watershed change to how the internet functionally works that played out that quickly. I’m a huge fan of IPv6, but that transition has been dragging out for a long time…
It’s the slowest transition of all time.
You know… And when we started Let’s Encrypt, we were thinking “This cannot be an IPv6 trendline. It can’t be that way. We’ve gotta make sure this happens much faster than that.”
There’s a lot of other improvements to make to the internet, too. I hope this serves as an example of “If we wanna make a change, we can do it.” There’s a bunch of other stuff we should fix. It is possible to change major parts of how the internet works in big ways, in a few years, under the right circumstances, with the right plan.
What you’re sharing - it reminds me of this idea that I haven’t quite verbalized yet, but it’s this cog mentality. If you’ve ever heard of Seth Godin, he wrote a book called Linchpin. The idea is to be a linchpin. I think, in many ways, as individuals, we try to be really important… And that kind of goes against the idea of cog mentality, which means that you’re just a very sharp, very specific, very purposeful thing, as part of a much bigger, much more grand whole machine. So if it weren’t for the you’s of the world, Josh, doing Let’s Encrypt and all the effort here, then the browsers wouldn’t be able to its thing, and then the site developers wouldn’t be able to do their thing… So all these things are sort of in concert. A system. So this idea of a cog mentality really rings true here.
Yeah. Well, we’re happy to do what we do. But like I said, there’s a lot of people who play in this. Running CA servers and providing the APIs is an important part of this, but we wouldn’t be anywhere near where we are today if there weren’t hundreds of people out there writing ACME protocol clients that work with Let’s Encrypt, so people can just download software [unintelligible 00:59:17.06] it works.
The browsers have done a great job incentivizing moves to HTTPS by limiting new technology to HTTPS connections, and some UI work, things like that. So it’s been the browsers, it’s been the open source community, Let’s Encrypt… Lots of people involved. Even within Let’s Encrypt, there’s so many people involved in it. There’s the engineers that work on it, our sponsors, our funders… That’s huge. We don’t go anywhere unless somebody decides to write a pretty big check. And people who make those decisions, to write those checks - I feel like they often don’t get enough credit, because it’s not fun and open source-y, but that’s a big deal.
So the fact that there are people out there and companies that understand what we’re trying to do and they’re willing to write those checks, and stand up and really make the internet better - that’s where it starts.
[01:00:16.04] Are there any standout organizations that have been supporting you, either in big ways, or for a long time, that you’d like to give a shoutout to? Because like you said, they don’t get much credit. Maybe a logo on a web page somewhere. But do you have any major supporters? Like “We wouldn’t be here if it weren’t for this company, or this organization.”
Yeah, we’ve got over 70 corporate sponsors, so I’m definitely not gonna be able to list them all here… But our platinum sponsors are our biggest supporters; they write the biggest checks, and they’ve been fantastic. Companies don’t make the decisions, people inside those companies make the decisions, and I’m so glad that those people understand what we’re doing and get it done.
Our platinum sponsors right now are Mozilla, Cisco, Electronic Frontier Foundation, OVH - a company that I think not a ton of people in the U.S. have heard of, but they’re a great, huge cloud provider in Europe, and they have just been fantastic since very early on. And Google, specifically the Google Chrome team.
One thing that’s amazing is what you’ve done with that money. In that same post, you talk about how you’re serving 4x the websites that you were back then. And of course, now here you are at 200 million, so even more websites… And your budget hasn’t increased 4x, or anywhere near that. You went from a 2.61 million annual budget in 2017 to 3.35 million now, and from 11 staff members to 13 staff members. So only adding two staff in the course of three years, and 4x in your websites served - that’s pretty good numbers.
Yeah, internally we are obsessed with efficiency. Like I said, it’s a really big deal for people to entrust us with millions of dollars over a year. There’s a lot of good in the world that money can do. So when that money comes to us, it’s our obligation to make sure that we use it wisely, and do the most good we can do with it. That means delivering the best service, to the most people that we can. We take that responsibility to be good shepherds of that money really seriously.
So whenever we talk about a new service, or like a new feature, or some way in which we’re gonna expand our service, we have a whole bunch of things that we think about to make sure that we’re being efficient. One of the most important things is “Does it require any people to be involved with anything, anywhere on the chain?”
One of the reasons we don’t offer phone support is if we did, we would have to fill a skyscraper with people sitting by the phone. So when we think about delivering a feature, that feature cannot require support. We need to make sure that it’s so easy to use and so easy to document and so easy to automate that the people consuming the feature should not need support. Even the people who are the least technical. It should just happen. If they do need support, it should be as simple as reading a very easy to find bit of documentation.
So ease of use is, again, hugely important for efficiency. If it’s easy to use, then people don’t need to talk to you as much. If even some very small part of 1% of the people using Let’s Encrypt needed to actually talk to us on the phone about something, that would just be overwhelming. We can’t do that. So everything has to be very easy to use.
Internally, we think a lot about how much data do we store. We’re basically allergic to data. We only really hold on to what we really need to hold on to for either compliance purposes or to debug our own systems.
[01:03:56.22] But aside from that, we don’t wanna have more sensitive information than we need, we don’t wanna be sitting on piles of information where we have to pay for storage servers and things like that. We tend to just do what we need to do and not hold on tons of data. When we need to use an external service, we often find partners who are willing to provide the service free of charge to us, essentially as sponsors or donors.
We’re just very concerned about efficiencies, so we’re only 13 people today. We have a lot of specialized systems, but it’s probably – I don’t know what people imagine we run when they think about what is Let’s Encrypt’s actual hardware, but it’s like about three racks full of hardware. It’s not a ton of hardware. It’s all very carefully maintained in some ways, but you can fit – you know, modern servers are crazy powerful. You can fit a lot of stuff in there, you don’t need a lot of physical space.
We’ve got a couple different data centers, maybe three racks of hardware between them, and that’s triple-redundant. In theory, if we needed to, we could just run the CA out of one rack hardware, and that would serve all 200 million sites pretty easily.
So if you automate everything and get computers to do all the work for you, you can be pretty efficient. It still requires – I think this year we’re gonna spend a little under four million dollars, but that’s really not that much money. I’m fairly confident that there are Fortune 500 companies out there that spend more than four million dollars on their internal PKI systems.
Right. So you mentioned earlier that you weren’t sure you wanted to even spend the next five years of your life doing this, doing a CA, but you felt like somebody had to do it, and you were well-positioned and willing to. Here we are, you’ve done over a billion certificates, 200 million sites served, all these big numbers… And I think more importantly, those global trends, which from the very beginning you all have said you wanted to encrypt the whole web. The global trends I think are probably more important to you than Let’s Encrypt’s footprint on that. 81% globally, 91% in the U.S. Do you feel like Let’s Encrypt has accomplished its mission? Is there still a lot left to do?
Well, in the U.S. there’s still 9% of page loads that are not encrypted. Globally it’s still 19%.
And I think if you’re an engineer, you probably understand what I mean when I say something like “90% of the work is involved in finishing the last 10%.” The 10% or 20% around the world that haven’t moved to HTTPS yet, they’re almost by definition the ones that are hardest to reach. They either don’t know, or they don’t have the tools, or they have some reason why they haven’t switched, and it’s the people for whom it was easy to switch have mostly already done it.
So I think that last 10% is gonna be pretty – it’s not gonna be as easy as the 10% before that. And also, this service needs to continue going. I don’t know how long Let’s Encrypt is gonna need to be around, but it’s quite possible that it’ll be around 10, 20, 30 years. I have no idea. But it’s not like once you’ve encrypted a site, your work is done. You’ve gotta continue to issue new certificates on a regular basis.
So we need to be around for that, and in order to be around for that, we need to stay on the top of our game in terms of compliance and security. At the end of the day, people need to trust us. That’s what it really comes down to. We’re never done because trust is never done. If at any point the world loses confidence in us, we can either lose trust technically, where browsers don’t trust us on a cryptographic level; if our donors don’t trust us, we don’t get the money we need to continue… So the job is certainly not done. We need to maintain high standards and stay trusted for a long time now.
I wasn’t exactly thrilled about the idea of spending a huge chunk of my life building a CA and running it, but it turned out to be really great. It puts me in contact with so many people that are really passionate about making the web a better place, and that’s something I am very happy with. I love working with our board members, and our partners, and our community. I can have enthusiasm on tap anytime I want it, just calling people up and talking about what’s happening with us. So it’s turned out to be great, and our staff are wonderful, so as a job, I really couldn’t ask for more.
[01:08:25.02] Yeah, the benefits of a job often outweigh the job itself. Sometimes you don’t really care for the job itself, or the mission… Not so much the mission-mission, but the fact that you get to interface with so many people who care - it’s gotta be uplifting for you.
In light of what Jerod asked you, I’m sure that this will be a little easier for you to answer - or maybe not - but what’s on the horizon for you? Big picture. You mentioned 10, 30 years down the road, so you’ve gotta have some sort of idea… Give us a snapshot, maybe 1-2 years in the future. What’s something nearest on the horizon not many people know about, that is something you can share today?
Well, we’re gonna keep grinding and finishing encrypting the rest of the web; that we’ve already talked about. There’s so many more things that need to be worked on… I don’t know that – you know, Let’s Encrypt permission is pretty well scoped. We issue certificates, and our goal is to do 100% encryption, and be entrusted while we do that. In some ways, that’s a very narrow scope, and it’s a part of why we have done well, I think. But I think in doing this work, we’ve realized there are a bunch of other issues on the web that we need to solve. A couple of the ones that are top of my mind are – there’s a protocol called Border Gateway Protocol (BGP), and that is the protocol that’s used to decide how and where traffic gets routed around the internet.
So if you’re gonna send a packet from Seattle to Philadelphia, what exact route is that gonna take to get there. That’s all determined by BGP. That protocol is not secure. It’s very vulnerable, and I think the only reason it hasn’t been exploited more is it’s not very popular. People don’t know about it, the attackers don’t know about it. They’ve also had easier targets, but…
For as many security problems as we have, we’ve done a pretty good job working on them, and I think a useful way to think about the next 10-20 years of security is that I think we’re gonna keep pushing attackers down the stack. You improve application layer security, and then maybe the next step down the stack is the transport layer, or something like that. HTTPS, you encrypt that, and then the attacker has gotta move on from there. And right now, I think the next layer down that has not been exploited to its full potential yet is BGP. I think of that as the soft underbelly of the internet. Attackers are gonna take notice of it and they are gonna get better at it, and they can cause massive outages by doing that, they can reroute traffic wherever they want…
So I’m concerned about BGP, and that has some pretty direct impact on Let’s Encrypt, in that certain types of BGP exploits can be used to mess with certificate issuance processes. That’s true of any CA, it’s not specific to Let’s Encrypt; it’s just part of our risk profile as an industry. But it’s a hard thing to secure.
So I’m very interested in what we can do about BGP security going forward. That’s gonna require a lot of the big companies that operate the major pathways on the internet to change how they do things. So that’s one thing I’m interested in, and we do some work around that at Let’s Encrypt to mitigate the problem right now, and also try to invest a little bit in the long-term solutions there.
Interesting.
[01:11:54.27] Another thing that both affects us and that I’m personally pretty passionate about is memory safety. In the same way that it seems crazy to us now that you would start a major website and not use HTTPS - we know so much about the risk of that and it just seems crazy to do that now - I think we’re also gonna come to a point where we feel like it is crazy how people say stuff like “Well, I’m running a bank and I need to do some reverse-proxying, so I’m gonna spin up an instance of NGINX or Apache and do my reverse load balancing.” Because what you’re really saying there is “Why don’t I just stick several million lines of C code on the edge of my network? And that’ll probably be fine.” That code is not safe. [unintelligible 01:13:25.11].”
So we’re trying to remove that kind of code from inside Let’s Encrypt, because it’s a huge liability, but we/I am looking into ways that we can try to move the needle on this problem in software in general.
What’s your first step, do you think? What are some of your early insights on moving that needle?
The first step is don’t write any new code in C and C++, or any other memory-unsafe language. That should just be a given. If you can tolerate a garbage collector, if that’s fine, then you have a ton of options - Java, Go, whatever. If you want a memory-safe language that doesn’t use a garbage collector, go use Rust. You have that option now.
It seems like the next step would be having viable replacements for a lot of the software that’s already out there.
Yeah. The next step is we need to rewrite all the software that we already wrote in C and C++, and replace it. And when I tell people that, the most common reaction is like “You can’t possibly expect us to rewrite the world. That’s so unreasonable. You’re not a realistic person when you say that.” And you know, I really strongly object to that reaction. We’re in a world full of talented people who care, and we can absolutely accomplish that if we want to.
If your goal is to rewrite a major web server or a major proxy server, or a major library or whatever, in Rust - let’s just do it. Yeah, it’ll take five years, it’ll introduce some logic bugs along the way that will get fixed, but in the end, this software is gonna be around for a very long time. And we need to eliminate that massive class of bugs, because vulnerability scanning, and audits, and static analysis, pentesting - that stuff doesn’t even begin to deal with the problem. It’s a good thing to do if you’re stuck with C and C++, but it’s absolutely not gonna eliminate the bugs. That’s just not gonna go away until you rewrite it.
[01:16:05.22] What we’re doing right now, where we just spin up giant piles of C and C++ without thinking about it is – we should not be doing that. We can’t be doing that 10-20 years from now if we wanna try to have a more secure world than we have now. So I think we need to think bigger. We just need to think like “Yeah, let’s rewrite the world.” Rewriting a big web server is a big project, but I’m sure there are teams at any number of companies that could accomplish it on their own without a help, if they just decide to do it. Yeah, it’ll be five years, but whatever; five years from now, you put in some effort, and now you’ve got a much more secure software system.
So I’d like to just see some more ambition and some more optimistic thinking about this stuff. I think it’s really important. I don’t wanna be suffering from buffer overflows in everyday software that sits on the network edge 10-20 years from now.
My guess, Josh, is that you’re well-positioned to encourage, considering what you’ve done in the last five years… Going from zero to a billion certificates issued is a big deal; you’ve found a way to create a CA in a world where it’s very difficult. Obviously, there’s protocols by – was it the cross-signature? Is that what it’s called?
Yeah, cross-signature.
Cross-signature. Just that alone, that was a smart play, and you’ve been able to do so much… So I think you’ve probably piqued our interest, and as well many listeners listening to this show by saying so. We need you out there petitioning for this, and encouraging those out there that can do this to take on this mission to do so, and not look at the five or ten years that it might take to do it. We see such blowback when we don’t consider the large-scale costs over many years. If this software isn’t gonna go anywhere in the next 10, 20 or 30 years, then we’re gonna rely on it. And just like securing the web is more important than it has ever been, having secure software that doesn’t have memory issues or unsafe memory where you can do these things, it seems so clear to me.
Yeah. It’s gotta happen.
Josh, thank you so much for your mission. Thank you so much for Let’s Encrypt and the work you all have done; to you and the team. I know you’re not a lone soldier in this mission, but the many behind you enabling this. But without you and many others doing this, we would have 51% less internet secured, so thank you very much for that. We appreciate your mission, and we appreciate you. Thank you, Josh.
Thank you so much.
Our transcripts are open source on GitHub. Improvements are welcome. 💚 | https://changelog.com/podcast/389 | CC-MAIN-2020-24 | en | refinedweb |
Join the community to find out what other Atlassian users are discussing, debating and creating.
Hi All,
I am trying to return a count of all of the words in a multi-line text field using a "Calculated Text Field". Is there an in-built function to do this? The ".length" function returns the character count for the contents of the custom field. ".size" does not appear to work on the same custom field.
If there is not an in built way to do this, I was trying to loop through each character in the field looking for ' ' or '\n' which would indicate a new word, however this is error prone e.g. newlines appended to the end of the text.
Appreciate any guidance.
Regards
Hi,
Not sure what version of JIRA you are using and what add-ons you have installed, but as far as I know, this isn't possible out of the box. We've done a similar thing using the ScriptRunner add-on. We simply created a Script Field and have the following code in it:
import com.atlassian.jira.component.ComponentAccessor
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def cField = customFieldManager.getCustomFieldObjectByName('fieldName')
String cFieldValue = issue.getCustomFieldValue(cField)
if(cFieldValue) {
return cFieldValue.split().size()
}
return 0. | https://community.atlassian.com/t5/Jira-questions/Count-Words-in-a-multi-line-Custom-Text-Field/qaq-p/1004001 | CC-MAIN-2020-24 | en | refinedweb |
{-# LANGUAGE ConstraintKinds #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.PackageDb -- Copyright : (c) The University of Glasgow 2009, Duncan Coutts 2014 -- -- Maintainer : ghc-devs@haskell.org -- Portability : portable -- --. -- module GHC.PackageDb ( InstalledPackageInfo(..), ExposedModule(..), OriginalModule(..), BinaryStringRep(..), emptyInstalledPackageInfo, readPackageDbForGhc, readPackageDbForGhcPkg, writePackageDb ) where import Data.Version (Version(..)) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BS.Char8 import qualified Data.ByteString.Lazy as BS.Lazy import qualified Data.ByteString.Lazy.Internal as BS.Lazy (defaultChunkSize) import Data.Binary as Bin import Data.Binary.Put as Bin import Data.Binary.Get as Bin import Control.Exception as Exception import Control.Monad (when) import System.FilePath import System.IO import System.IO.Error import GHC.IO.Exception (IOErrorType(InappropriateType)) import System.Directory -- | This is a subset of Cabal's 'InstalledPackageInfo', with just the bits -- that GHC is interested in. -- } deriving (Eq, Show) -- | A convenience constraint synonym for common constraints over parameters -- to 'InstalledPackageInfo'. type RepInstalledPackageInfo srcpkgid srcpkgname unitid modulename = (BinaryStringRep srcpkgid, BinaryStringRep srcpkgname, BinaryStringRep unitid, BinaryStringRep modulename) -- |. data OriginalModule unitid modulename = OriginalModule { originalPackageId :: unitid, originalModuleName :: modulename } deriving (Eq, Show) -- | Represents a module name which is exported by a package, stored in the -- 'exposedModules' field. A module export may be a reexport (in which case -- 'exposedReexport' is filled in with the original source of the module). -- Thus: -- -- * @ExposedModule n Nothing@ represents an exposed module @n@ which -- was defined in this package. -- -- * @ExposedModule n (Just o)@ represents a reexported module @n@ -- which was originally defined in @o@. -- -- We use a 'Maybe' data types instead of an ADT with two branches because this -- representation allows us to treat reexports uniformly. data ExposedModule unitid modulename = ExposedModule { exposedName :: modulename, exposedReexport :: Maybe (OriginalModule unitid modulename) } deriving (Eq, Show) class BinaryStringRep a where fromStringRep :: BS.ByteString -> a toStringRep :: a -> BS.ByteString emptyInstalledPackageInfo :: RepInstalledPackageInfo a b c d => InstalledPackageInfo a b c d emptyInstalledPackageInfo = InstalledPackageInfo { unitId = fromStringRep BS.empty, sourcePackageId = fromStringRep BS.empty, packageName = fromStringRep BS.empty, packageVersion = Version [] [], abiHash = "", depends = [], importDirs = [], hsLibraries = [], extraLibraries = [], extraGHCiLibraries = [], libraryDirs = [], frameworks = [], frameworkDirs = [], ldOptions = [], ccOptions = [], includes = [], includeDirs = [], haddockInterfaces = [], haddockHTMLs = [], exposedModules = [], hiddenModules = [], exposed = False, trusted = False } -- | Read the part of the package DB that GHC is interested in. -- readPackageDbForGhc :: RepInstalledPackageInfo a b c d => FilePath -> IO [InstalledPackageInfo a b c d] readPackageDbForGhc file = decodeFromFile file getDbForGhc where getDbForGhc = do _version <- getHeader _ghcPartLen <- get :: Get Word32 ghcPart <- get -- the next part is for ghc-pkg, but we stop here. return ghcPart -- |. -- readPackageDbForGhcPkg :: Binary pkgs => FilePath -> IO pkgs readPackageDbForGhcPkg file = decodeFromFile file getDbForGhcPkg where getDbForGhcPkg = do _version <- getHeader -- skip over the ghc part ghcPartLen <- get :: Get Word32 _ghcPart <- skip (fromIntegral ghcPartLen) -- the next part is for ghc-pkg ghcPkgPart <- get return ghcPkgPart -- | Write the whole of the package DB, both parts. -- writePackageDb :: (Binary pkgs, RepInstalledPackageInfo a b c d) => FilePath -> [InstalledPackageInfo a b c d] -> pkgs -> IO () writePackageDb file ghcPkgs ghcPkgPart = writeFileAtomic file (runPut putDbForGhcPkg) where putDbForGhcPkg = do putHeader put ghcPartLen putLazyByteString ghcPart put ghcPkgPart where ghcPartLen :: Word32 ghcPartLen = fromIntegral (BS.Lazy.length ghcPart) ghcPart = encode ghcPkgs getHeader :: Get (Word32, Word32) getHeader = do magic <- getByteString (BS.length headerMagic) when (magic /= headerMagic) $ fail "not a ghc-pkg db file, wrong file magic number" majorVersion <- get :: Get Word32 -- The major version is for incompatible changes minorVersion <- get :: Get Word32 -- The minor version is for compatible extensions when (majorVersion /= 1) $ fail "unsupported ghc-pkg db format version" -- If we ever support multiple major versions then we'll have to change -- this code -- The header can be extended without incrementing the major version, -- we ignore fields we don't know about (currently all). headerExtraLen <- get :: Get Word32 skip (fromIntegral headerExtraLen) return (majorVersion, minorVersion) putHeader :: Put putHeader = do putByteString headerMagic put majorVersion put minorVersion put headerExtraLen where majorVersion = 1 :: Word32 minorVersion = 0 :: Word32 headerExtraLen = 0 :: Word32 headerMagic :: BS.ByteString headerMagic = BS.Char8.pack "\0ghcpkg\0" -- TODO: we may be able to replace the following with utils from the binary -- package in future. -- | Feed a 'Get' decoder with data chunks from a file. -- decodeFromFile :: FilePath -> Get a -> IO a decodeFromFile file decoder = withBinaryFile file ReadMode $ \hnd -> feed hnd (runGetIncremental decoder) where feed hnd (Partial k) = do chunk <- BS.hGet hnd BS.Lazy.defaultChunkSize if BS.null chunk then feed hnd (k Nothing) else feed hnd (k (Just chunk)) feed _ (Done _ _ res) = return res feed _ (Fail _ _ msg) = ioError err where err = mkIOError InappropriateType loc Nothing (Just file) `ioeSetErrorString` msg loc = "GHC.PackageDb.readPackageDb" -- Copied from Cabal's Distribution.Simple.Utils. writeFileAtomic :: FilePath -> BS.Lazy.ByteString -> IO () writeFileAtomic targetPath content = do let (targetDir, targetFile) = splitFileName targetPath Exception.bracketOnError (openBinaryTempFileWithDefaultPermissions targetDir $ targetFile <.> "tmp") (\(tmpPath, handle) -> hClose handle >> removeFile tmpPath) (\(tmpPath, handle) -> do BS.Lazy.hPut handle content hClose handle renameFile tmpPath targetPath) instance (RepInstalledPackageInfo a b c d) => Binary (InstalledPackageInfo a b c d) where put (InstalledPackageInfo unitId sourcePackageId packageName packageVersion abiHash depends importDirs hsLibraries extraLibraries extraGHCiLibraries libraryDirs frameworks frameworkDirs ldOptions ccOptions includes includeDirs haddockInterfaces haddockHTMLs exposedModules hiddenModules exposed trusted) = do put (toStringRep sourcePackageId) put (toStringRep packageName) put packageVersion put (toStringRep unitId) put abiHash put (map toStringRep depends) put importDirs put hsLibraries put extraLibraries put extraGHCiLibraries put libraryDirs put frameworks put frameworkDirs put ldOptions put ccOptions put includes put includeDirs put haddockInterfaces put haddockHTMLs put exposedModules put (map toStringRep hiddenModules) put exposed put trusted get = do sourcePackageId <- get packageName <- get packageVersion <- get unitId <- get abiHash <- get depends <- get importDirs <- get hsLibraries <- get extraLibraries <- get extraGHCiLibraries <- get libraryDirs <- get frameworks <- get frameworkDirs <- get ldOptions <- get ccOptions <- get includes <- get includeDirs <- get haddockInterfaces <- get haddockHTMLs <- get exposedModules <- get hiddenModules <- get exposed <- get trusted <- get return (InstalledPackageInfo (fromStringRep unitId) (fromStringRep sourcePackageId) (fromStringRep packageName) packageVersion abiHash (map fromStringRep depends) importDirs hsLibraries extraLibraries extraGHCiLibraries libraryDirs frameworks frameworkDirs ldOptions ccOptions includes includeDirs haddockInterfaces haddockHTMLs exposedModules (map fromStringRep hiddenModules) exposed trusted) instance (BinaryStringRep a, BinaryStringRep b) => Binary (OriginalModule a b) where put (OriginalModule originalPackageId originalModuleName) = do put (toStringRep originalPackageId) put (toStringRep originalModuleName) get = do originalPackageId <- get originalModuleName <- get return (OriginalModule (fromStringRep originalPackageId) (fromStringRep originalModuleName)) instance (BinaryStringRep a, BinaryStringRep b) => Binary (ExposedModule a b) where put (ExposedModule exposedName exposedReexport) = do put (toStringRep exposedName) put exposedReexport get = do exposedName <- get exposedReexport <- get return (ExposedModule (fromStringRep exposedName) exposedReexport) | https://downloads.haskell.org/~ghc/8.0.1/docs/html/libraries/ghc-boot-8.0.1/src/GHC-PackageDb.html | CC-MAIN-2020-24 | en | refinedweb |
A comprehensive approach for a techno-economic assessment of nodule mining in the deep sea
Abstract
Mine planning of land-based mineral deposits follows well-established methods. The deep sea is currently under exploration, but mine planning approaches are still lacking. A spatial planning tool to assess the techno-economic requirements and implications of manganese nodule mining on deep-sea deposits is proposed in this paper. The comprehensive approach has been validated using research findings of the Blue Mining project, which received funding from the European Commission. A part of the German exploration area E1, located in the Clarion-Clipperton Fracture Zone, Pacific Ocean, serves as a case study area. The approach contributes to a responsible utilization of mineral resources in the deep sea, considering geological, economic and financial as well as technical and operational aspects. The approach may also be applicable for an early-stage assessment of other projects related to spatially distributed mineral resources, e.g., marine phosphate nodules. Furthermore, it could also be helpful for the investigation of the environmental impacts of seafloor manganese nodule mining.
KeywordsDeep-sea mining Manganese nodules Blue Mining Spatial planning Marine mining Mine planning Harvesting
Abbreviations
- BGR
Federal Institute for Geosciences and Natural Resources (BGR), Hanover, Germany
- CAPEX
Capital expenditure
- CCZ
Clarion-Clipperton (Fracture) Zone
- Co
Cobalt
- CoV
Coefficient of variance
- Cu
Copper
- DCF
Discounted cash flow
- DSM
Deep-sea mining
- DMT
Dry metric ton (of SMnN)
- E1
Eastern German license area E1
- FeMn
Ferromanganese
- GAP-Analysis
Good, average, poor analysis
- GIS
Geographic information system
- IRR
Internal rate of return
- MSV
Mining support vessel
- Mn
Manganese
- Ni
Nickel
- NiEq
Nickel equivalent
- NPV
Net present value
- NSR
Net smelter/processor return
- OPEX
Operative expenditure
- ROM
Run of mine
- SMnN
Seafloor manganese nodules
- SMT
Seafloor mining tool
- SMP
Spatial mine planning
- MSP
Marine spatial planning
- REE
Rare earth elements
Introduction
First mining activities go back to the Stone Age (Sieveking et al. 1972). Since then, technologies have evolved from manual picking to high-tech mining, from the surface to the underground, and from the land to the sea. In the future, mining operations to extract marine minerals could take place in the deep sea. Seafloor manganese nodules (SMnN) may be one target of deep-sea mining (DSM) beyond the limits of national jurisdiction (Petersen et al. 2016; Hein and Koschinsky 2014; Mero 1962). Covering vast abyssal plains, high-tech harvesters are envisaged to collect these potato-sized rock concretions in water depths between 4000 and 6500 m (Volkmann and Lehnen 2017). SMnN primarily contain manganese, but are also rich in nickel, cobalt, copper, and other metals, which make them economically interesting (Hein et al. 2013). However, the future of DSM is still uncertain. Regulations for the exploitation of SMnN are still under development (ISA 2017a). Moreover, mining technologies are yet to attain a technological readiness level to undertake DSM operations (Knodt et al. 2016; ECORYS 2014; ISA 2008).
Exploitation technologies and methodologies as well as tools to plan for a sustainable exploitation must be developed in parallel to current exploration activities. If not, it will not be possible to exploit the resources once they are found, characterized, and whenever the market is ready. Spatial planning tools are used today in land-based mining (Preuße et al. 2016), for marine spatial planning purposes (Stelzenmüller et al. 2013) and in many other areas to plan human activities. Despite intensive research efforts since the 1970s, approaches to assess the techno-economic requirements and implications of SMnN mining are still lacking (Volkmann and Lehnen 2017; Sharma 2017; Abramowski 2016). In this light, a spatial planning tool and a method to valuate SMnN deposits is presented here and exemplified for a part of the eastern German license area, which is located in the Clarion-Clipperton Fracture Zone (CCZ), Pacific Ocean. The approach covers a whole range of disciplines—from exploration through to the financing of such projects and to the study of economics. To validate the results, research findings of the European research project “Blue Mining” are included as a specific case study (see “Background” section).
Blue Mining research contributes towards a sustainable spatial management and utilization of marine mineral resources (Volkmann 2014). Up to now, ecologic, economic, and societal aspects have been considered on a rather regional scale, i.e., for the entire CZZ (ISA 2017b; Lodge et al. 2014; Wedding et al. 2013). Although considered in marine spatial planning (Ehler and Douvere 2009; Ehler 2008; Ardron et al. 2008), the development of a spatial management strategy needs yet to be tackled for mining activities (Durden et al. 2017). Relating to this, the techno-economic requirements of commercial SMnN mining are assessed here and a planning approach is proposed. Besides mine planning by future mine operators, authorities may also apply the tool to identify and assess areas of potential commercial interest. The methodology may support the study of mining-related environmental impacts (Vanreusel et al. 2016; Mengerink et al. 2014) and human land use (Foley et al. 2005) in the deep sea—and may also be applicable to other spatially distributed marine mineral resources, e.g., phosphate nodules.
Background
This study uses background information of the Blue Mining project (2014–2018), which received funding from the European Commission (EC) in the 7th Framework Programme. Geological and technical aspects have been covered in an earlier publication with focus on the determination of production key figures (Volkmann and Lehnen 2017). Financial key figures were investigated by the Blue Mining project, but have only been partly published to date (Volkmann and Osterholt 2017). Exploration data have kindly been provided by the Federal Institute for Geosciences and Natural Resources (BGR).
Definitions
SMnN mining will mostly take place in international waters, on the seabed and subsoil beyond the limits of national jurisdiction termed “the Area” (Jenisch 2013). According to the United Nations Convention on the Law of the Sea (UNCLOS 1994), the International Seabed Authority (ISA or “the Authority”) shall organize, regulate, and control all activities in the Area, particularly with a view to administering its resources—the common heritage of mankind (Jaeckel et al. 2017). To plan future mining activities, clear definitions and demarcations are needed:
“Marine spatial planning” (MSP) is a “public process of analyzing and allocating the spatial and temporal distribution of human activities in marine areas to achieve ecological, economic and social objectives that are usually specified through a political process.” (Ehler and Douvere 2009). MSP should be ecosystem-based, with the goal “to maintain an ecosystem in a healthy, productive and resilient condition so that it can provide the goods and services humans want and need” (Ehler and Douvere 2009).
In contrast to MSP, “spatial mine planning” (SMP) is a process of analyzing and allocating the spatial and temporal distribution of human activities on the seafloor, which are related to a mining project. A spatial planning and management strategy to exploit SMnN in the most sustainable manner needs yet to be developed and, therefore, objectives, indicators, and regulations need to be defined. One main focus of research, as an important part of SMP, is the identification of the so-called “mineable area.”
The “mineable area” is the basis for other activities related to SMP, e.g., the identification of mine sites, mining fields, and routes (Volkmann and Lehnen 2017). In general, mining the seafloor area must be legally permitted and technically and economically feasible. As legal and environmental aspects are not included in the spatial planning tool presented here (see “Development of a spatial planning tool for SMnN mining” section), and since the future of SMnN mining is still uncertain, we refer to area(s) of potential commercial interest.
A “spatial (mine) planning tool” refers to a device that is necessary to or aids in the performance of SMP. A graphical calculating device, a nomogram, has been developed to determine the techno-economic requirements of a SMnN mining project and is used to identify the areas of (potential) commercial interest. Nomograms have roots back to the 1880s and “provide engineers with fast graphical calculations of complicated formulas to a practical precision” (Doerfler 2009). A later integration of the derived algorithms into a practical mine planning or scheduling software is conceivable.
Characteristics of the SMnN case study area
Clarion-Clipperton fracture zones (FZs) bordering the area where most of the ISA exploration areas for SMnN are located. The white area indicates the eastern German license area, within which the case study area of this paper is located
Apart from slight local variations, the chemical composition of the SMnN is relatively constant throughout the whole CCZ, especially when compared to variations in nodule abundance (in kg/m2; (Kuhn et al. 2017); the latter ranges between 0 and ~ 30 kg/m2 (based on wet nodule weight) with an average of 15 kg/m2 in the CCZ (SPC 2013). SMnN fields are not equally distributed on the seafloor within the CCZ but occur in patches. Economically interesting “patches” can cover an area of several thousand square kilometers (ISA 2010).
Water depths in the eastern German license area E1 vary from 1460 to 4680 m, with an average of 4240 m (Rühlemann et al. 2011). The seafloor of E1 is characterized by deep-sea plains interspersed with NNW-SSE-oriented horst and graben structures that are several kilometers wide, tens of kilometers long, and 100–300 m high, and many extinct volcanoes (seamounts) rising a few hundred to almost 3000 m over the surrounding abyssal plains (Rühlemann et al. 2011). Seafloor plains with slope angles less than 7° cover about 75% of the German license area and represent areas of interest with respect to future SMnN mining projects. However, due to environmental constraints, it is suggested that only about 20% of the license area may be mined in the future.
Bathymetric map (a) and slope angles (b) of the case study area in the eastern German exploration area E1. Slopes in the range of 0 to 7° are combined in map (c). Map (d) shows the predicted nodule abundance; areas with slopes exceeding 7° are excluded (white). The direction (top right to bottom right) indicates the processing/mapping sequence (see “Development of a valuation technique for SMnN deposits” section)
By nature, SMnN are polymetallic rock concretions which are comprised of several metals of economic value (UNOET 1987). During marine exploration, though different in subsequent mine planning, it is common to sum up the grades of the key metals. The sum of the nickel, copper, and cobalt contents averages 2.73%, the manganese content averages 31.1%, and the nodule abundance ranges from 0 to 22 kg/m2 (dry weight; unpublished BGR data). The nodule abundance distribution map (Fig. 2d) indicates increased values in topographically elevated areas. Grades have not been mapped since they are relatively constant. For instance, the coefficient of variance (CoV) for the combined Co + Cu + Ni grades throughout the entire E1 area is less than 10% compared to the CoV of nodule abundance which is > 30% (Knobloch et al. 2017).
Financial key figures of the case study
Revenues are generated from the sale of the metals nickel (Ni), cobalt (Co), copper (Cu), and optionally manganese (Mn), which could be sold as ferromanganese (FeMn; 73% Mn). The economic feasibility of SMnN mining will, at least for the foreseeable future, depend on these metals, even though trace metals such as rare earth elements (REE), tellurium (Te), lithium (Li), and gallium (Ga) (Hein et al. 2013) might be of economic interest as well (SPC 2016; Martino and Parson 2013). Their prices are based on time series data sets published by the USGS (2016), which were adjusted for inflation. The good case refers to the upper quartile, the average case to the average value, and the poor case scenario to the lower quartile of constant year 2015-dollar prices (1970 to 2015). The time series data set for manganese ore was scaled up to match with the 2015-price of ferromanganese. It is distinguished between three-metal (Ni, Co, Cu) and four-metal (plus Mn) processing routes (SPC 2016). Recovery rates reported by the ISA (2008) and average metal grades reported by Rühlemann et al. (2011) for E1 were used (Table 1).
The breakeven revenue is the minimum value required to cover all costs, including interest, taxes, and depreciation. Thus, it can be considered as a cost figure. The breakeven calculation is based on a discounted cash flow (DCF) analysis, using the time value of money to appraise long-term projects. SMnN and land-based mining projects share fundamental similarities: high risk and high capital cost. Capital expenditures (CAPEX) were estimated to range between about 2015-$1.2 and 1.5 billion. These costs were depreciated over 20 years using the straight-line method. Operative expenditures (OPEX) were estimated to range between $200 and 340/dmt SMnN (Volkmann and Osterholt 2017). Costs of a pilot mining test are not included. Tax and royalties are similar to rates which would be assumed for land-based mining projects. Discount rates of up to 25% apply, which are commensurate with the level of risk currently associated with the first SMnN mining projects. Production is assumed to range between 1 and 2 Mt/a (dry).
Assumptions and estimates have only been partly published for the Blue Mining project (Volkmann and Osterholt 2017). Most of these figures need yet to be validated through comprehensive studies and tests (Knodt et al. 2016; ECORYS 2014; ISA 2008). This concerns in particular the effective production and costs related to the processing and refining of SMnN. Assumptions and estimates may be compared to figures published in recent studies, e.g., BMWi (2016); SPC (2016).
Methodology
Concept of the approach to investigate the techno-economic requirements and implications of SMnN mining
Development of a valuation technique for SMnN deposits
Although proposals for the identification of the mineable area have been made (Volkmann and Lehnen 2017; UNOET 1979), a standardized reporting code for declaring SMnN reserves does not yet exist. Recent studies consider grade, nodule abundance, and hydro-acoustic backscatter data in conjunction with slope angles to tag prospective SMnN fields (Volkmann and Lehnen 2017; Knobloch et al. 2017; Mucha and Wasilewska-Blaszczyk 2013). Relating thereto, a method for identifying the areas of (potential) commercial interest is proposed here, which—in addition to the existing approaches—takes into account the economic value of SMnN.
Mapping the seafloor’s cash value
To map the seafloor’s cash value, information on grades, nodule abundance, metal prices, and technical parameters such as efficiencies and the climbing ability of the seafloor mining tool (SMT) are required.
The “seafloor’s cash value” (R′′) is the revenue which could be generated by mining a specific area (raster unit, i.e., pixel), in US-dollar ($) per square meter. Simplified, it is the money that can be collected from the seafloor, i.e., revenue is generated by collecting SMnN and by selling the recovered metals. The cash value is the product of the metal content recovered from the area and the nickel price (Formula 1).
R′′ = The seafloors average cash value [$/m2]
M′′ = Average nickel equivalent content (recoverable), see Formula 6 [t/m2]
pNi = Selling price of nickel [$/t]
NAF = Average nodule abundance in the fields [t/m2, dry]
gNiE = Average nickel equivalent grade, see Formula 2 [%]
ηC = Constant collecting efficiency [%]
Constant metal grades and metal recovery rates, but variable nodule abundances (in kg/t, dry weight; Fig. 2) and prices of the respective scenarios apply (Table 1). The average metal contents derive from geochemical analyses of more than 700 nodule samples (BGR data).
The “nickel equivalent grade” (gNiE) is defined as the percentage amount (sum) of nickel equivalents determined for Co, Cu, and optionally Mn (sold as FeMn) with Ni as the major metal. To calculate the equivalent grade, all metals (m) are converted to a single metal based upon metal prices (pm), grades (gm), and recovery rates (ηm) (Formula 2).
gNiE = Average nickel equivalent grade [%]
pm = Selling price of product containing metal m [$/t, metal content]
pNi = Selling price of nickel [$/t]
gm = Average grade of metal m in ore [%]
ƞm = Average recovery rate for metal m [%]
k = Number of metals recovered (here three or four metals)
m = Here: Ni (1), Co (2), Cu (3), and Mn sold as FeMn (4)
The distribution of nodule abundance per square meter in the case study area (Fig. 1) was modeled based on the neural network approach by Knobloch et al. (2017), who used bathymetry and backscatter data of the seafloor and several derived datasets as input data. Based on known nodule abundance at box corer sites, the neural network was trained to find patterns in the input data which correlate with the nodule abundance from box corers. It could be proven that such patterns exist and, thus, it was possible to predict the nodule abundance at all sites where hydro-acoustic data are available (Knobloch et al. 2017). Therefore, nodule abundance values in the study area were available with a resolution of about 100 m, leading to the application of raster data with pixel sizes of about 100 m by 100 m with one nodule abundance value per pixel (Fig. 2) in the present study.
The distribution of cash values for each scenario in the case study area was mapped with ArcGIS™. The seafloor’s cash value was then calculated by using the presented formula (Formula 1). Areas with slope angles above 7° were removed from the analysis (white areas in Fig. 2d) as currently proposed mining equipment may only cope with areas inclined up to 7°—if at all (Agarwal et al. 2012; Kuhn et al. 2011; Atmanand 2011). The potentially mineable area is smaller and patchier (Fig. 2b, c) when slopes should not exceed 3°. Cash values were filtered using a smoothing average filter to remove noisy data. An averaging filter was applied, replacing each pixel value in the image of the case study area with the mean value of its neighbors, including the central pixel of the 3 × 3 matrix.
Theoretical resource utilization
The theoretical resource utilization (RUMax) is defined as the percentage amount of SMnN (contained in the case study area) that could be recovered by assuming an ideal extraction process (Volkmann and Lehnen 2017). The ideal state implies constant extraction costs and an extraction ratio of 100%, i.e., all SMnN are recovered from the areas (pixels) classified as (potentially) mineable. Mining losses are not considered. Field characteristics or other factors which have (under production conditions) an impact on costs are also not considered. Grades are assumed to be constant. The percentage utilization is plotted against the average nodule abundance. In general, the higher the cutoff (threshold) value, the more areas (pixels) are excluded from the case study area and the higher is the average value and vice versa.
Development of a spatial planning tool for SMnN mining
The spatial planning tool proposed here for SMnN mining is called nomogram (see “Definitions” section). A nomogram is created for each of the four GAP scenarios. Assumptions and estimates (Table 1) apply as default parameters. The nomogram is divided into four quadrants and visualizes the mathematical relationships between project economics (quadrant I), mine production (quadrant II), deposit characteristics (quadrant III), and market economics (quadrant IV). A formulaic approach to create a spatial planning tool for SMnN is presented, which is tied to certain objectives and constraints.
In contrast to the nomogram, different units are used in the formulas to avoid the use of conversion factors. All figures refer to annual or annual average values.
Objectives and constraints
The breakeven cash value (\( {{\widehat{R}}_{\mathrm{A}}}^{\prime \prime } \)) and the breakeven price (\( {\widehat{p}}_{\mathrm{Ni}} \)) are sought. The breakeven cash value is used to identify the areas of potential commercial interest (see “Development of a valuation technique for SMnN deposits” section) and to investigate the theoretical resource utilization (RUMax). The breakeven price is required to assess the profitability and the techno-economic requirements of a SMnN mining project.
From a socioeconomic perspective, the case study area’s resource should be utilized in the best possible manner, leaving more equivalent areas unmined for future generations (Volkmann 2014). A theoretical resource utilization of 100% is assumed, i.e., all SMnN is recovered from the entire case study area. However, environmental aspects still need to be effectively integrated. From a financial standpoint (Volkmann 2014), profitability is an absolute prerequisite for a commercial operation, here indicated by the net profit per unit of output (NP′).
The “net profit per nickel equivalent unit” (NP′) is defined as the nickel price (pNi) minus the breakeven price (\( {\widehat{p}}_{\mathrm{Ni}} \)). A mining project can only be accepted for positive values (NP′ > 0) (Formula 3).
NP′ = Net profit per ton nickel equivalent [$/t, metal content]
pNi = Selling price of nickel price [$/t, metal content]
\( {\widehat{p}}_{\mathrm{Ni}} \) = Breakeven nickel (equivalent) price [$/t, metal content]
In addition, techno-operational constraints and assumptions of the Blue Mining case study apply (Volkmann and Lehnen 2017). It is assumed that the maximum production would be limited to 2 Mt per annum. With current mining technology, a maximum mining capacity (MRMax) of 9 m2/s is expected by using one or two seafloor mining tools (SMTs). Furthermore, an operating time of 5000 h per year (TA) and a collecting efficiency of 80% (ηC) are assumed and defined as constants (note that this is a simplification).
Quadrant I: mine project economics
The first quadrant shows breakeven revenue, i.e., cost isolines for production capacities in the range of 0.5 to 2.5 Mt/a. The calculation is based on breakeven sales values (i.e., the costs per dmt; Table 1). Economies of scale, i.e., cost advantages that would arise with increased output, apply. The annual breakeven revenue (\( {\widehat{R}}_{\mathrm{A}} \)) is plotted against the average mining rate (MRA) and the seafloor’s average breakeven cash value (\( {\widehat{R}}_{\mathrm{A}} \)). The latter needs to be determined to identify the areas of potential commercial interest (see “Development of a valuation technique for SMnN deposits” section).
The “seafloor’s breakeven cash value” (\( {{\widehat{R}}_{\mathrm{A}}}^{\prime \prime } \)) is the minimum economic value that the mineable (and mined) area must exhibit on average to ensure profitability. The main objective is to ensure sufficient annual revenues to cover all costs incurred in the project. The breakeven cash value depends on the breakeven revenue (\( {\widehat{R}}_{\mathrm{A}} \)), the annual operating time (TA), and the average mining rate (MRA) (Formula 4). The average mining rate indicates the operational performance (Volkmann and Lehnen 2017).
\( {{\widehat{R}}_{\mathrm{A}}}^{\prime \prime } \) = The seafloor’s breakeven cash value (annual average) [$/m2]
\( {\widehat{R}}_{\mathrm{A}} \) = Annual breakeven revenue [$/a]
MRA = Annual average mining rate [m2/h]
TA = Annual (scheduled) operating time [h/a]
Quadrant II: mine production
The second quadrant shows production isolines for rates in the range of 0.5 to 2.5 Mt/a. The annual production rate (PA) is plotted against MRA and the average nodule abundance (NAF). Full capacity utilization is assumed, i.e., production and breakeven isolines match (PA = PA Max). The isolines indicate the dimension (scale) of a SMnN mining system, i.e., the designed capacity.
The “annual production rate” (PA) is defined as the dry mass of SMnN which would be recovered each year (Volkmann and Lehnen 2017). The annual production rate (Formula 5) is the product of the average nodule abundance in the mining fields (NAF), the annual operating time (TA), the average mining rate (MRA), and the collecting efficiency (ηC). The collecting efficiency is the percentage of SMnN picked-up from the seafloor. Further losses (of metals) are expected to occur in subsequent processes of the mine value chain (Melcher 1989), but are neglected in the calculations because the overall efficiency still needs to be assessed.
PA = Annual production rate [t/a, dry]
NAF = Average nodule abundance in the fields (annual average) [t/m2]
TA = Annual (scheduled) operating time [h/a]
MRA = Average mining rate (annual average) [m2/h]
ηC = Constant collecting efficiency [%]
Quadrant III: deposit characteristics
The third quadrant shows nickel equivalent grade isolines in the range of 1 to 7%. Although the nickel equivalent grade (gNiE) depends on the market conditions, it is rather unlikely that values are outside of this range with respect to historical metal prices and grades of the case study area. The nickel equivalent grade is plotted against NAF and the recoverable metal content (M′′). The relationship is shown for metal content, which is used in the cash value formula (Formula 1).
The “seafloor’s recoverable metal content” (M′′) is defined as the metal content that would be recovered from the seafloor. To calculate M′′, nodule abundance, the nickel equivalent grade, and the collecting efficiency (ηC) must be determined (Formula 6).
M′′ = The seafloor’s recoverable metal content (nickel equivalent) [t/m2]
NAF = Average nodule abundance in the fields [t/m2, dry]
gNiE = Average nickel equivalent grade [%]
ηC = Constant collecting efficiency [%]
The nickel equivalent grade and nodule abundance are results of the economic deposit assessment (see “Development of a valuation technique for SMnN deposits” section) and apply as annual averages. The nodule abundance depends on RUMax or vice versa.
Quadrant IV: market economics
The fourth quadrant shows price isolines in the range of $6000 to 30,000 per metric ton (metal content). In the light of historical metal prices and breakeven cash values, it is rather unlikely that values are outside this range for the case study area. The nickel price (pNi) is plotted against M′′ and the breakeven cash value (\( {{\widehat{R}}_{\mathrm{A}}}^{\prime \prime } \)). The breakeven price (\( {\widehat{p}}_{\mathrm{Ni}} \)) is sought, i.e., required to appraise the project.
The “break-even nickel (equivalent) price” (\( {\widehat{p}}_{\mathrm{Ni}} \)) is the ratio of \( {{\widehat{R}}_{\mathrm{A}}}^{\prime \prime } \) to the metal content, which would be recovered from the seafloor area (M′′; Formula 7). It represents the economic minimum price required to cover all costs incurred in the project to result in a positive investment decision.
\( {\widehat{p}}_{\mathrm{Ni}} \) = Breakeven nickel (equivalent) price [$/t]
\( {{\widehat{R}}_{\mathrm{A}}}^{\prime \prime } \) = The seafloor’s breakeven cash value [$/m2]
M′′ = The seafloor’s recoverable nickel (equivalent) content [t/m2]
Guidance on using the nomogram
The nomogram is a specific tool for SMP to assess the techno-economic requirements of a mining project. Using the nomogram requires that a comprehensive assessment is conducted to determine breakeven revenues (costs) and constraints, among other model parameters. In combination with the deposit valuation method, the areas of commercial interest can be identified, and the theoretical resource utilization and potential land use can be studied with the generated maps.
Maps of estimated cash values in the case study area in the eastern German exploration area. a Four-metal good case scenario. b Four-metal average case scenario. c Four-metal poor case scenario. d Three-metal average scenario
Nomogram of the good case scenario (red rectangle) implying four-metal recovery (Ni, Co, Cu, and Mn). The dashed blue line in quadrant I relates to the RUmax curve and not to the production isolines
Results
In the following sections, the results of the assessment of the three- and four-metal GAP scenarios (Table 1) are presented, using both seafloor maps and nomograms.
Deposit potential of the SMnN case study area
Maps of the cash value are shown for the different GAP scenarios (Fig. 4). In these areas, slopes do not exceed 7°. Grades were shown to be constant in the study area. Comparing the four-metal good case (Fig. 4a) and four-metal average case scenario (Fig. 4b), the area divides into two contiguous areas. At higher prices in the good case, more areas fall into the class of cash values > $9/m2. These areas exhibit the highest nodule abundance (15–20 kg/m2; Fig. 2d) and are situated in the eastern part of the case study area. For the four-metal poor case scenario (Fig. 4c), the same can be observed, but cash values fall into the next lower classes. In the case of the three-metal average case scenario (Fig. 4d), the study area is more or less one large area with cash values between $3 and 6/m2.
According to the metal prices and recovery rates of the GAP scenarios (Table 1), the average nickel equivalent grade would be about 4.5 wt% in the case of four-metal and around 2 wt% in the case of three-metal recovery.
Minimum average seafloor’s cash values required to break even depending on the mining rate; estimated for the Blue Mining case study
Comprehensive evaluation of the case study
The nomograms are related to the case study area (Fig. 2) and to the assumptions defined for the four different GAP scenarios (Table 1). Objectives and constraints apply (see “Development of a spatial planning tool for SMnN mining” section).
Four-metal good case scenario
In the case of the four-metal good case scenario (Fig. 5), an average mining rate of about 9.8 m2/s would be required to result in a production of 2 Mt/a, while aiming to best utilize the resource of the case study area. The breakeven price would amount to about $8000/t, in contrast to a selling nickel price of about $16,000/t assumed for the scenario. The average seafloor’s cash value should not be less than ~ $4.5/m2. In this case, the net profit (NP′) is positive and the mining project would be economically viable. However, mining rates exceeding 9 m2/s are not expected to be achievable on average at present.
At a lower mining rate of 8 m2/s, a production of only ~ 1.7 Mt/a can be reached, based on an average nodule abundance of 14.8 kg/m2. However, at a breakeven cash value of ~ $5.7/m2 still a positive, but lower, net profit (NP′) could be achieved (Fig. 5(IV)). In Fig. 4a the cash values per square meter have been mapped, and it becomes apparent that a value of $5.7/m2 is reached in almost the complete case study area. If the mining rate would only be 4 m2/s, ~ 0.8 Mt/a could be mined in the case study area at 100% resource utilization. The breakeven nickel price would amount to about $12,000/t with a breakeven cash value of ~ $6.5/m2. However, almost all areas, i.e., pixels of the case study area are higher than the average minimum cash value (Fig. 4a).
Based on the assumption to mine the entire case study area, the smaller the project’s scale (capacity), the more pixels (Fig. 4) are below the economic minimum average value (Fig. 5(I)). In the light of constant metal prices and grades, profitability is improved by up-scaling the system’s capacity (economies of scale). Higher production rates require higher mining rates. As expected to be not realizable for the good case scenario (~ 9.8 m2/s), uneconomic pixels would have to be excluded from mining to result in a higher average nodule abundance (Fig. 5(III)). Planning with 2 Mt/a, a (lower) mining rate of 7.5 m2/s would result in the same net profit (NP′; Fig. 5(IV)), but would lead to a RUMax of only ~ 5%, relating to an average abundance of ~ 19 kg/m2 (Fig. 5(II)).
Four-metal average case scenario
Nomogram of the average (moderate) case scenario (red rectangle) implying four-metal recovery (Ni, Co, Cu, and Mn)
Three-metal average case scenario
Nomogram of the average (moderate) case scenario (red rectangle) implying three-metal recovery (Ni, Co, and Cu). A negative net profit (NP′) can be observed
Four-metal poor case scenario
Nomogram of the poor case scenario (red rectangle) implying four-metal recovery (Ni, Co, Cu, and Mn)
Discussion
The discussion focuses on the methodology and derived results, but not on the background, i.e., assumptions and estimates related to deposit characterization and financial analysis.
Critical review of the methodology
Deposit valuation method
Using the method presented here (see “Development of a valuation technique for SMnN deposits” section), it is not yet possible to identify the (potentially) mineable area. Although technical and economic criteria have been considered (Fig. 2; Fig. 4), additional criteria might need to be considered, such as the size of SMnN, the trafficability of the soil, and areas of environmental interest that require protection, among others. Nevertheless, sound criteria to differentiate between non-mineable and mineable areas need to be investigated and these methods should be further fine-tuned and validated for other areas within the CCZ (ISA 2010). Moreover, none of the known SMnN resources have reached the status of a “reserve,” yet. This is due to the lack of geological confidence, economic technological readiness, and a missing legal framework for the exploitation of SMnN (Volkmann and Lehnen 2017).
The approach to identify the areas of potential commercial interest provides only a rough representation of the reality. The breakeven cash value (Formula 4) and the slope angle are used as criteria, i.e., pixels are excluded from mining which are below the economic minimum value and are not accessible for the SMTs (> 7°). Filters to identify contiguous areas have been developed, which have been inspired by traffic patterns of farming machines (Volkmann and Lehnen 2017). These filters were not applied to the case study area in order to not further increase the complexity of the analysis. However, maps of the seafloor’s cash value (Fig. 4) can be used to visually identify potentially mineable fields—seeking for coherent, large-scale areas, with a simple geometry and only few geological disturbances (obstacles). Surrounding areas and areas within should be included, if accessible and as long the (annual) average value is not less than the minimum cash value.
The breakeven cash value depends on the mining rate achieved in the particular area (Formula 4). The mining rate may depend, inter alia, on the slope angle, soil condition, number of obstacles, and field shape, among other factors. Furthermore, geological and field properties will influence costs, e.g., the steeper the slope, the higher the energy consumption and costs. In contrast, the collecting efficiency, a factor of the cash value formula (Formula 1), may depend on the burial depth and size of SMnN, among other factors. Therefore, these influencing factors should be analyzed for different area- and field-specific “patterns” by conducting pilot mining tests, experiments, or simulations. In the next step, a “preliminary reserve” could be estimated, not considering field design and route planning at this stage. The preliminary reserve, i.e., the mineable area could serve as a basis for further route planning to determine the “in-field reserve” (Volkmann and Lehnen 2017).
Spatial planning tool
The nomogram (see “Development of a spatial planning tool for SMnN mining” section) has several limitations. Because the breakeven calculation (see “Financial key figures of the case study” section) is based on a discounted cash flow (DCF) method, the nomogram is to be seen as a supporting tool for the strategic planning of a commercial mining project. Assuming that the cash flows of the financial model are constant over time is a simplification: from experience, metal prices, costs and production rates, among other model parameters, change during the life time of a mine. This is, however, counterbalanced by considering multiple scenarios with different parameter values (Table 1). Moreover, other methods may apply to determine the economic breakeven value (Wellmer et al. 2008). A further limitation is that the size and location of the case study area is fixed, whereas seafloor consumption is variable. It chiefly depends on the production (target) and average nodule abundance in the mining area (Volkmann and Lehnen 2017). Because equivalent areas have been identified for E1 (BGR unpublished data), it is assumed that the model area would be extensible, i.e., the characteristics of the model area apply to (smaller) sub-areas or fields.
Because the creation and use of the nomogram is relatively time-consuming, especially for larger data sets, computer-aided SMP should be sought. Using computer software, data handling, analysis, and visualization would be easier, faster, and dynamic. The tool could be integrated into GIS-software, e.g., ArcGIS™, which is designed to store, manipulate, analyze, and visualize spatial data. Moreover, the presented tool may also apply for other spatially distributed marine minerals, e.g., phosphate nodules. In precision farming, for instance, soil properties are obtained via close sensing, while remote sensing is commonly used to obtain information on the field, e.g., the yield. The collected data is used to generate application maps providing the user and the agricultural tools with information, e.g., fertilizer suggestions and traffic routes (Mulla 2013). For SMnN mining software, respective tools and methods still need to be developed, which will allow determination of the mineable area, the engineering of mining fields, and route planning. Then, it may be possible to benchmark the economic performance of a mining system, while assessing the environmental and societal implications of SMnN mining.
Validity of the results
The model case study and scenarios are hypothetical and based on assumptions and estimates of the Blue Mining case study. To assess the general techno-economic requirements in view of resource utilization, results of other projects need to be evaluated and compared.
Techno-economic requirements
A prerequisite of any mining project is economic feasibility. Based on the results of the Blue Mining case study (cf. nomograms), at least moderate conditions (Table 1) are necessary to realize economic SMnN mining, while focusing on the metals nickel, cobalt, copper, and manganese. This fits with the general consensus on the profitability of SMnN mining (SPC 2016; Martino and Parson 2013; Johnson and Otto 1986). Especially the high expectations on the internal rate of return (IRR), which are reflected in the breakeven revenue (costs; Table 1), make SMnN mining technologically difficult—although the techno-economic feasibility of SMnN mining has not yet been demonstrated. Currently, an IRR (discount rate) of about 15 to 30% is anticipated to be commensurate with the level of risk associated with SMnN projects (BMWi 2016; Martino and Parson 2013). However, it should be noted that commercial ventures must make a profit, while governments and their agencies may not (Gertsch and Gertsch 2005).
In the past, low profitability forced companies to focus on large scale (> 1 Mt/a) rather than on small-scale projects (≤ 1 Mt/a), with a median of 1.5 Mt/a of dry SMnN (SPC 2016). Also, the lifting system developed by Blue Mining partners is designed for production rates of up to 2 Mt/a. SPC (2016) states “that three-metal plants only become attractive as long as the plants receive 2-3 million dry tonnes of nodule per year as inputs. […] Four metal plants can sustain a much smaller operation at 1.5 million dry tonnes of nodules per year, as long as there is a high manganese recovery rate to make the operation competitive with respect to the additional capital and operating expenditures.” However, boosting profitability by harnessing economies of scale is restricted, because the production from one vessel or platform has shown to be limited to about 1.5 to 2 Mt/a dry SMnN, due mainly to technical, operational, and geological reasons (Volkmann and Lehnen 2017).
In the recent past, recommendations suggest (Martino and Parson 2013) that small-scale projects (Handschuh et al. 2003; Søreide et al. 2001) may be advisable under the dominance of the conventional (land-based) mining industry and low profitability of SMnN mining. Although cost savings due to economies of scale are tempting, an oversupply of metals due to an emerging number of SMnN projects could abruptly stop the rapid spread (Martino and Parson 2013). The conventional mining industry could recognize a reduction of metal prices as an effective barrier or even measure to drive SMnN mines out of the market (Marvasti 1998, 2000). Based on the results (cf. nomograms), small-scale mining would be most profitable under good conditions, while it would be just profitable under conditions assumed for the average case scenario (Table 1). Thus, the development of cost-efficient and high-performance mining concepts as well as adequate prices will be decisive to ensure economic viability.
The nomograms and the generated maps on the areas of potential commercial interest show that mining must be selective to be economically viable. Even in the good case scenario (Fig. 5(II)), the miner would have to “pick the cherries,” i.e., the most economic parts from the model area (> 9 $/m2; Fig. 4a) due to the capacity restriction of the SMT. To achieve average mining rates of 4 to 10 m2/s, mining capacities of 7.5 to 20 m2/s would have to be provided by one or several SMTs, depending on the time efficiency and the operating time (Volkmann and Lehnen 2017). Improving operating and time efficiency by adopting a most simple mining pattern and navigating the SMT(s) through the most nodule-rich areas with favorable field conditions (mostly flat and with only few obstacles) may be reasonable to increase productivity or if technically and/or economically unavoidable. However, an excessive practice would lead to a lower mining efficiency and reserve recovery (extraction ratio) within a mine site, thus, to a poor utilization of resources and land (Volkmann and Lehnen 2017).
Environmental considerations
Beside profitability and land and resource utilization, the affected seafloor area has been advocated to be an important aspect of sustainability (Volkmann 2014). Using the nomograms and maps of the areas of potential commercial interest, it may be possible to ecologically investigate the affected seafloor area (MIDAS 2016b; Thiel and Schriever 1993; Sharma 2013).. Also, it is yet uncertain if “cherry-picking” would be reasonable to preserve the abyssal ecosystem or to foster its recovery on a smaller scale (Vanreusel et al. 2016), i.e., within a mine site or mining field (Volkmann and Lehnen 2017). At the present time, the “impacts and effects of mining surrounding the directly mined area are poorly understood” (MIDAS 2016a). Although it is known that fine particles whirled up by SMTs and released from the MSV can be transported over large distances of several hundreds of kilometers, forming a thin sediment layer on the seafloor which may overlap and suppress the benthic ecosystem (SPC 2013; Sharma et al. 2001), it is not yet possible to define absolute threshold values or to predict the severity of the impact (MIDAS 2016a). Sound criteria need yet to be defined.
Conclusions
The presented tool and deposit valuation method contributes to an early understanding of the relationships between geological, technical, operational, economic, and financial aspects of SMnN mining, and the implications of SMnN mining in terms of resource and land utilization are considered. However, the comprehensive approach needs to be fine-tuned and validated with larger data sets, and possible environmental impacts still need to be considered. To work towards sustainable development, the development of a spatial planning and management strategy needs to be tackled. This requires that sound objectives, indicators, and regulations are formulated. In addition to a mining code, a computer code, i.e., a software for spatial mine planning (SMP), is required. In this context, interdisciplinary research, mining tests, and simulations, accompanied by comprehensive environmental studies, need to be conducted to determine the mineable area and to pre-define proper mining concepts.
Notes
Acknowledgements
This work received funding by the EU as part of the 7th Framework Programme (GA No. 604500). Exploration data were kindly provided by the German Federal Institute for Geosciences and Natural Resources (BGR) where we would like to thank Dr. Annemiek Vink for a critical review of our manuscript. Furthermore, we would like to thank Prof. Bernd Lottermoser (RWTH Aachen University) for additional input.
References
- Abramowski T (2016) Deep sea mining value chain: organization, technology and development. Interoceanmetal Joint Organization, SzczecinGoogle Scholar
- Agarwal B, Hu P, Placidi M, Santo H, Zhou JJ 2012 Feasibility study on manganese nodules: recovery in the Clarion-Clipperton Zone.
- Ardron J, Gjerde K, Pullen S, Tilot V (2008) Marine spatial planning in the high seas. Mar Policy 32(5):832–839. CrossRefGoogle Scholar
- Atmanand MA (2011) Status of India’s polymetallic nodule mining Programme. In: Chung JS (ed) Proceedings of the twenty-first (2011) international offshore and polar engineering conference. ISOPE, CupertinoGoogle Scholar
- BMWi 2016 Analysis of the Economic Benefits of Developing Commercial Deep Sea Mining Operations in Regions where Germany has Exploration Licenses of the International Seabed Authority, as well as Compilation and Evaluation of Implementation Options with a Focus on the Perfomance of Pilot Mining Test. With the assistance of Ramboll IMS and HWWI. Hamburg. Federal Ministry for Economic Affairs and Energy Division I C 4, Project No. 59/15Google Scholar
- Doerfler R (2009) On jargon-the lost art of nomography. UMAP J 30(4):457Google Scholar
- Durden JM, Murphy K, Jaeckel A, van Dover CL, Christiansen S, Gjerde K, Ortega A, Jones DOB (2017) A procedural framework for robust environmental management of deep-sea mining projects using a conceptual model. Mar Policy 84:193–201. CrossRefGoogle Scholar
- ECORYS 2014 Study to investigate state of knowledge of deep-sea mining: Final Report under FWC MARE/2012/06 - SC E1/2013/04.” Accessed 26 Nov 2016.
- Ehler C (2008) Conclusions: benefits, lessons learned, and future challenges of marine spatial planning. Mar Policy 32(5):840–843. CrossRefGoogle Scholar
- Ehler C, Douvere F 2009 Marine spatial planning, a step-by-step approach toward ecosystem-based management. IOC Manuals and Guides 53 (New York, NY) 309(5734):570–574.. CrossRefGoogle Scholar
- Gertsch R, Gertsch L 2005 Economic analysis tools for mineral projects in space. Space Resources Roundtable,. Last viewed Sep 21: 3–11
- Handschuh R, Schulte E, Grebe H, Schwarz W (2003) Economic simulations for a small scale manganese nodule mining system taking into account new technologies. In: Proceedings of The Fifth Ocean Mining Symposium, edited by The International Society of Offshore and Polar Engineers, 71. International Society of Offshore and Polar Engineers (ISOPE), Tsukuba, 15–19 Sept 2003Google Scholar
- Hein JR, Koschinsky A (2014) Deep-ocean ferromanganese crusts and nodules. In: Holland HD, Turekian KK (eds) Treatise on geochemistry, 2nd edn. Elsevier, Amsterdam, pp 273–291. CrossRefGoogle Scholar
- Hein JR, Mizell K, Koschinsky A, Conrad TA (2013) Deep-ocean mineral deposits as a source of critical metals for high-and green-technology applications: comparison with land-based resources. Ore Geol Rev 51:1–14. CrossRefGoogle Scholar
- Hoagland P (1993) Manganese nodule price trends. Resour Policy 19(4):287–298. CrossRefGoogle Scholar
- ISA (ed) 2008 Polymetallic nodule mining technology: current status and challenges ahead. Proceedings of a workshop held by the International Seabed Authority in Chennai, India February 18-22, 2008.
- ISA (ed) (2010) A geological model of polymetallic nodule deposits in the Clarion Clipperton fracture zone. Technical study 6. International Seabed Authority, KingstonGoogle Scholar
- ISA 2017a Ongoing development of regulations on exploitation of mineral resources in the area. Accessed 30 Nov 2017.
- ISA 2017b Report of the Chair of the Legal and Technical Commission on the work of the Commission at its session in 2017. ISBA/23/C/13.
- Jaeckel A, Gjerde KM, Ardron JA (2017) Conserving the common heritage of humankind—options for the deep-seabed mining regime. Mar Policy 78:150–157. CrossRefGoogle Scholar
- Jenisch U (2013) Tiefseebergbau–Lizenzvergabe und Umweltschutz. NuR 35(12):841–854. CrossRefGoogle Scholar
- Johnson CJ, Otto JM (1986) Manganese nodule project economics: factors relating to the Pacific region. Resour Policy 12(1):17–28. Scholar
- Knobloch A, Kuhn T, Rühlemann C, Hertwig T, Zeissler K-O, Noack S (2017) Predictive mapping of the nodule abundance and mineral resource estimation in the Clarion-Clipperton Zone using artificial neural networks and classical geostatistical methods. In: Sharma R (ed) Deep-Sea Mining. Springer, ChamCrossRefGoogle Scholar
- Knodt S, Kleinen T, Dornieden C, Lorscheidt J, Bjørneklett B, Mitzlaff A 2016 Development and engineering of offshore mining systems—state of the art and future perspectives. Offshore Technology Conference, HoustonGoogle Scholar
- Kuhn T, Rühlemann C, Wiedicke-Hombach M, Rutkowsky J, Wirth HJ, Koenig D, Kleinen T, Mathy T (2011) Tiefseeförderung von Manganknollen. Schiff & Hafen (5):78–83Google Scholar
- Kuhn T, Wegorzewski A, Rühlemann C, Vink A 2017 Composition, formation, and occurrence of polymetallic nodules. In: Sharma R (2017) Deep-sea mining: resource potential, technical and environmental considerations. Springer International Publishing, Cham. pp 23–63. Google Scholar
- Lodge M, Johnson D, Le Gurun G, Wengler M, Weaver P, Gunn V (2014) Seabed mining: international seabed authority environmental management plan for the Clarion–Clipperton zone. A partnership approach. Mar Policy 49:66–72. CrossRefGoogle Scholar
- Martino S, Parson LM (2013) Spillovers between cobalt, copper and nickel prices: implications for deep seabed mining. Miner Econ 25(2–3):107–127. CrossRefGoogle Scholar
- Marvasti A (1998) An assessment of the international technology transfer systems and the new law of the sea. Ocean Coast Manag 39(3):197–210. CrossRefGoogle Scholar
- Marvasti A (2000) Resource characteristics, extraction costs, and optimal exploitation of mineral resources. Environ Resour Econ 17(4):395–408. CrossRefGoogle Scholar
- Melcher PR (1989) Konzeption eines Fördersystems zum Abbau von Manganknollen. Forsch Ingenieurwesen 55(1):16–31. CrossRefGoogle Scholar
- Mengerink KJ, van Dover CL, Ardron J, Baker M, Escobar-Briones E, Gjerde K, Koslow JA et al (2014) A call for deep-ocean stewardship. Science (New York, NY) 344(6185):696–698.. CrossRefGoogle Scholar
- Mero JL (1962) Ocean-floor manganese nodules. Econ Geol 57(5):747–767. CrossRefGoogle Scholar
- MIDAS 2016a Implications of MIDAS results for policy makers: recommendations for future regulations.” Accessed 13 Dec 2017.
- MIDAS 2016b Managing impacts of deep sea resource exploitation: research highlights. Accessed 13 Dec 2016.
- Mucha J, Wasilewska-Blaszczyk M 2013 The Contouring accuracy of polymetallic nodules ore fields in the Interoceanmetal (IOM) Area, East Pacific Ocean. In Proceedings of the Tenth (2013) ISOPE Ocean Mining and Gas Hydrates Symposium: Deep ocean minerals, exploration, mining, gas hydrates and environment, edited by J. S. Chung. Cupertino, CalifGoogle Scholar
- Mulla DJ (2013) Twenty five years of remote sensing in precision agriculture: key advances and remaining knowledge gaps. Biosyst Eng 114(4):358–371. CrossRefGoogle Scholar
- Petersen S, Krätschell A, Augustin N, Jamieson J, Hein JR, Hannington MD (2016) News from the seabed—geological characteristics and resource potential of deep-sea mineral resources. Mar Policy 70:175–187. CrossRefGoogle Scholar
- Preuße A, Beckers D, Charlier F, Müller D, PapstM, Preuße L (2016) 16th International Congress for mine surveying, Brisbane, 12–16 Sept 2016Google Scholar
- Rühlemann C, Kuhn T, Wiedicke-Hombach M, Kasten S, Mewes K, Picard A 2011 Current status of manganese nodule exploration in the German license area. In Chung, pp 168–73Google Scholar
- Sharma R (2013) Deep-sea impact experiments and their future requirements. Mar Georesour Geotechnol 23(4):331–338. CrossRefGoogle Scholar
- Sharma R, Nath N, Parthiban G, Sankar SJ (2001) Sediment redistribution during simulated benthic disturbance and its implications on deep seabed mining. Deep-Sea Res II 48(16):3363–3380. CrossRefGoogle Scholar
- Sieveking GDG, Bush P, Ferguson J, Craddock PT, Hughes MJ, Cowell MR (1972) Prehistoric flint mines and their identification as sources of raw material. Archaeometry 14(2):151–176. CrossRefGoogle Scholar
- Søreide F, Lund T, Markussen JM (2001) Deep ocean mining reconsidered: A study of the manganese nodule deposits in Cook Island. In: The proceedings of the Fourth (2001) ISOPE Ocean Mining Symposium, edited by The International Society of Offshore and Polar Engineers (ISOPE). Cupertino, CalifGoogle Scholar
- SPC (2013) Deep Sea Minerals. In: Baker E, Beaudoin Y (eds) Manganese nodules, a physical, biological, environmental, and technical review, vol 1B. Secretariat of the Pacific CommunityGoogle Scholar
- SPC (2016) An assessment of the costs and benefits of mining deepsea minerals in the Pacific Island Region: deep-sea mining cost-benefit analysis. Suva, Fiji. SPC Technical Report SPC00035Google Scholar
- Stelzenmüller V, Lee J, South A, Jo F, Rogers SI (2013) Practical tools to support marine spatial planning: a review and some prototype tools. Mar Policy 38:214–227. CrossRefGoogle Scholar
- Thiel H, Schriever G (1993) Environmental consequences of deep-sea mining. Int Chall 13:54–70Google Scholar
- UNCLOS 1994 United Nations Convention on the Law of the Sea. Accessed 18 Nov 2016.
- UNOET (ed) (1979) Manganese nodules: dimensions and perspectives. Natural resources forum library 2. Reidel, DordrechtGoogle Scholar
- UNOET (ed) (1987) Delineation of mine sites and potential in different sea areas. Seabed Minerals Series 4, vol. 9. Graham & Trotman, LondonGoogle Scholar
- USGS 2016 USGS minerals information: commodity statistics and information. Accessed 15 Sept 2017.
- Vanreusel A, Hilario A, Ribeiro PA, Menot L, Arbizu PM (2016) Threatened by mining, polymetallic nodules are required to preserve abyssal epifauna. Sci Rep 6(1):26808. CrossRefGoogle Scholar
- Volkmann SE (2014) “Deliverable 3.41: sustainable indicators.” Public report submitted to the EU Commission within the 7th Framework Programme (GA No. 604500). Accessed July 26, 2016.
- Volkmann SE, Lehnen F (2017) Production key figures for planning the mining of manganese nodules. Mar Georesour Geotechnol:1–16. CrossRefGoogle Scholar
- Volkmann SE, Osterholt V 2017 Deliverable 3.42: sustainable economic models and evaluation. Public report submitted to the EU Commission within the 7th Framework Programme (GA No. 604500).
- Wedding LM, Friedlander AM, Kittinger JN, Watling L, Gaines SD, Bennett M, Hardy SM, Smith CR (2013) From principles to practice: a spatial approach to systematic conservation planning in the deep sea. Proc R Soc B Biol Sci 280(1773):20131684. CrossRefGoogle Scholar
- Wellmer FH, Dalheimer M, Wagner M (2008) Economic evaluations in exploration. Springer, Ber. | https://link.springer.com/article/10.1007/s13563-018-0143-1 | CC-MAIN-2018-47 | en | refinedweb |
Ex.
In
mix.exs, add the ExMachina dependency:
def deps do # Get the latest from hex.pm. Works with Ecto 2.0 [ {:ex_machina, "~> 2.1"}, ] end
And start the ExMachina application. For most projects (such as
Phoenix apps) this will mean adding
:ex_machina to the list of applications in
mix.exs. You can skip this step if you are using Elixir 1.4
def application do [mod: {MyApp, []}, applications: [:ex_machina, :other_apps...]] end
In
mix.exs, add the ExMachina dependency:
def deps do [ {:ex_machina, "~> 2.1", only: :test}, ] end
Add your factory module inside
test/support so that it is only compiled in the
test environment.
Next, be sure to start the application in your
test/test_helper.exs before
ExUnit.start:
{:ok, _} = Application.ensure_all_started(:ex_machina) %MyApp.Article{ title: "Use ExMachina!", # associations are inserted when you call `insert` author: build(:user), }.
def make_admin(user) do %{user | admin: true} end def with_article(user) do insert(:article, user: user) user end build(:user) |> make_admin |> insert |> with_article)
Before opening a pull request, please open an issue first.
$ git clone $ cd ex_machina $ mix deps.get $ mix test
Once you've made your additions and
mix test passes, go ahead and open a PR!
ExMachina is Copyright 2015 thoughtbot. It is free software, and may be redistributed under the terms specified in the LICENSE file.
ExMachina is maintained and funded by thoughtbot, inc. The names and logos for thoughtbot are trademarks of thoughtbot, inc.
We love open source software, Elixir, and Phoenix. See our other Elixir projects, or hire our Elixir Phoenix development team to design, develop, and grow your product. | https://recordnotfound.com/ex-machina-thoughtbot-176 | CC-MAIN-2018-47 | en | refinedweb |
This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of C++11 status.
Section: 99 [func.ret] Status: C++11 Submitter: Alisdair Meredith Opened: 2009-11-19 Last modified: 2017-02-03
Priority: Not Prioritized
View all other issues in [func.ret].
View all issues with C++11 status.
Discussion:
Addresses UK 198
NB Comment: UK-198 makes this request among others. It refers to a more detailed issue that BSI did not manage to submit by the CD1 ballot deadline though.
result_of is essentially a metafunction to return the type of an expression, and belongs with the other library metafunctions in <type_traits> rather than lurking in <functional>. The current definition in <functional> made sense when result_of was nothing more than a protocol to enable several components in <functional> to provide their own result types, but it has become a more general tool. For instance, result_of is now used in the threading and futures components.
Now that <type_traits> is a required header for free-standing implementations it will be much more noticeable (in such environments) that a particularly useful trait is missing, unless that implementation also chooses to offer <functional> as an extension.
The simplest proposal is to simply move the wording (editorial direction below) although a more consistent form for type_traits would reformat this as a table.
Following the acceptance of 1255, result_of now depends on the declval function template, tentatively provided in <utility> which is not (yet) required of a free-standing implementation.
This dependency is less of an issue when result_of continues to live in <functional>.
Personally, I would prefer to clean up the dependencies so both result_of and declval are available in a free-standing implementation, but that would require slightly more work than suggested here. A minimal tweak would be to require <utility> in a free-standing implementation, although there are a couple of subtle issues with make_pair, which uses reference_wrapper in its protocol and that is much harder to separate cleanly from <functional>.
An alternative would be to enact the other half of N2979 and create a new minimal header for the new C++0x library facilities to be added to the freestanding requirements (plus swap.)
I have a mild preference for the latter, although there are clearly reasons to consider better library support for free-standing in general, and adding the whole of <utility> could be considered a step in that direction. See NB comment JP-23 for other suggestions (array, ratio)
[ 2010-01-27 Beman updated wording. ]
The original wording is preserved here:
Move 99 [func.ret] to a heading below 19.15 [meta]. Note that in principle we should not change the tag, although this is a new tag for 0x. If it has been stable since TR1 it is clearly immutable though.
This wording should obviously adopt any other changes currently in (Tentatively) Ready status that touch this wording, such as 1255.
[ 2010-02-09 Moved to Tentatively Ready after 5 positive votes on c++std-lib. ]
Proposed resolution:
From Function objects 19.14 [function.objects], Header <functional> synopsis, remove:
// 20.7.4 result_of: template <class> class result_of; // undefined template <class F, class... Args> class result_of<F(ArgTypes...)>;
Remove Function object return types 99 [func.ret] in its entirety. This sub-section reads:
namespace std { template <class> class result_of; // undefined template <class Fn, class... ArgTypes> class result_of<Fn(ArgTypes...)> { public : // types typedef see below type; }; }
Given an rvalue
fnof type
Fnand values
t1, t2, ..., tNof types T1, T2, ..., TN in
ArgTypes, respectively, the type member is the result type of the expression
fn(t1, t2, ...,tN). The values
tiare lvalues when the corresponding type
Tiis an lvalue-reference type, and rvalues otherwise.
To Header <type_traits> synopsis 19.15.2 [meta.type.synop], add at the indicated location:
template <class T> struct underlying_type;
To Other transformations 19.15.7.6 [meta.trans.other], Table 51 — Other transformations, add:
At the end of Other transformations 19.15.7.6 [meta.trans.other] add:
] | https://cplusplus.github.io/LWG/issue1270 | CC-MAIN-2018-47 | en | refinedweb |
- Citrix ADC Release Notes
- Getting Started with Citrix ADC
- Where Does a Citrix ADC Appliance Fit in the Network?
- How a Citrix ADC Communicates with Clients and Servers
- Introduction to the Citrix ADC Product Line
- Install the hardware
- Access a Citrix ADC
-
- LSN44 in a cluster setup
- Dual-Stack Lite
- Large Scale NAT64
- Points to Consider for Configuring Large Scale NAT64
- Configuring DNS64
- Configuring Large Scaler NAT64
- Configuring Application Layer Gateways for Large Scale NAT64
- Configuring Static Large Scale NAT64 Maps
- Logging and Monitoring Large Scale NAT64
- Port Control Protocol for Large Scale NAT64
- LSN64 in a cluster setup
-
- Citrix ADC URL Filtering
- Citrix ADC Solutions
- Setting Up Citrix ADC for XenApp/XenDesktop
- Global Server Load Balancing (GSLB) Powered Zone Preference
-
- Prerequisites
-
-
- Jumbo frames on Citrix ADC VPX instances
- Licensing
- Upgrade and downgrade a Citrix ADC appliance
- Authentication, authorization, and auditing application traffic
- How Authentication, authorization, and auditing works
- Enabling AAA
- Setting up an authentication virtual server
- Creating an authentication profile
- Configuring users and groups
- Configuring Authentication, authorization, and auditing policies
- Authorizing user access to application resources
- Auditing authenticated sessions
- Session settings
- Traffic settings
- Authenticating with client certificates
- Configuring Authentication, authorization, and auditing with commonly used protocols
- Citrix ADC
- Citrix ADC configuration support in a cluster
- Prerequisites for cluster nodes
- Cluster overview
- Setting up a Citrix ADC cluster
- Distributing traffic across cluster nodes
- Managing the Citrix ADC cluster
- Configuring linksets
- Nodegroups for spotted and partially-striped configurations
- Configuring redundancy for nodegroups
- Disabling steering on the cluster backplane
- Synchronizing cluster configurations
- Synchronizing time across cluster nodes
- Synchronizing cluster files
- Viewing the statistics of a cluster
- Discovering Citrix ADC
- FAQs
- Troubleshooting the Citrix ADC DNS logging
- Configure DNS suffixes
- DNS ANY query
- Configure negative caching of DNS records
- Caching of EDNS0 client subnet data when the Citrix ADC appliance is in proxy mode
- Domain name system security extensions
-
- Citrix ADC Appliances in Active-Active Mode Using VRRP
- Using the Network Visualizer
- Configuring Link Layer Discovery Protocol
- Jumbo Frames
- Citrix ADC Support for Microsoft Direct Access Deployment
- Access Control Lists
- IP Routing
- Internet Protocol version 6 (IPv6)
- Traffic Domains
- VXLAN
- Priority Load Balancing
- Citrix ADC Extensions
- Citrix ADC extensions - language overview
- Citrix ADC extensions - library reference
- Citrix ADC extensions API reference
- Protocol extensions
-
- TLSv1.3 protocol support as defined in RFC 8446
- How-to articles
- SSL certificates
- Create a certificate
- Install, link, and update certificates
- Generate a server test certificate
- Import and convert SSL files
- SSL profiles
- Certificate revocation lists
- Monitor certificate status with OCSP
- OCSP stapling
- Ciphers available on the Citrix ADC appliances
- Server certificate support matrix on the ADC appliance
- Client authentication
- Server authentication
- SSL actions and policies
- Selective SSL logging
-
- ICAP for remote content inspection
- Citrix ADC Appliance
- Remove and Replace a Citrix ADC in a High Availability Setup
- TCP Optimization
- Troubleshooting Citrix ADC
-!
Import and convert SSL files
You can now import SSL resources, such as certificates, private keys , CRLs, and DH keys, from remote hosts even if FTP access to these hosts is not available. This
You can use the CLI and GUI to import a file (resource) from a remote host.
Import a certificate file from a remote host by using the CLI
At the command prompt, type:
import ssl certFile [<name>] [<src>]
Example:
import ssl certfile my-certfile
show ssl certfile Name : my-certfile URL :
To remove a certificate file, use the rm ssl certFile command, which accepts only the ‘name’ argument.
Import a key file from a remote host by using the CLI
At the command prompt, type:
import ssl keyFile [<name>] [<src>]
Example:
import ssl keyfile my-keyfile
show ssl keyfile Name : my-keyfile URL :
To remove a key file, use the rm ssl keyFile command, which accepts only the ‘name’ argument.
Import a CRL file from a remote host by using the CLI
At the command prompt, type:
import ssl crlFile [<name>] [<src>]
To remove a CRL file, use the rm ssl crlFile command, which accepts only the <name> argument.
Example:
import ssl crlfile my-crlfile show ssl crlfile Name : my-crlfile URL :
Import a DH file from a remote host by using the CLI
At the command prompt, type:
import ssl dhFile [<name>] [<src>]
Example:
import ssl dhfile my-dhfile show ssl dhfile Name : my-dhfile URL : dsa:
OpenSSL>rsa- in <PKCS#8 Key Filename> -des3 -out <encrypted Key Filename> OpenSSL>dsa -in <PKCS#8 Key Filename> -des3 -out <encrypted Key Filename> (the personal information exchange syntax standard) to PEM or DER format for importing a certificate to the appliance, and can convert PEM or DER to PKCS#12 for exporting a certificate. For additional security, conversion of a file for import can include encryption of the private key with the DES or DES3 algorithm.
Note:
If you use the GUI to import a PKCS#12 certificate, and the password contains a dollar sign ($), backquote (`), or escape () character, the import may. | https://docs.citrix.com/en-us/netscaler/12-1/ssl/ssl-certificates/export-existing-certs-keys.html | CC-MAIN-2018-47 | en | refinedweb |
WeMartiansAreFriendly 1 Posted June 4, 2007 Why do you have to compile the executible in ansi and unicode.. Would it be possible to compile for both using if conditions? if osverion >= winnt then unicode mode else ansi mode endif Is unicode a library and Why does it not work for win9x, I think it need backwords compatibility. Some insight would be nice. Don't bother, It's inside your monitor!------GUISetOnEvent should behave more like HotKeySet() Share this post Link to post Share on other sites | https://www.autoitscript.com/forum/topic/47089-unicode-question/ | CC-MAIN-2018-47 | en | refinedweb |
In node.js, module is a JavaScript file and it will contain a set of functions to reuse it in node.js applications.
In node.js, each file is treated as separate module and the modules in node.js are same like JavaScript libraries.
In node.js, modules are useful to move the common functionalities to separate .js file to reuse it in applications based on our requirements. In node.js, each module has its own context, so if we create any new module that won’t interfere with other modules in application.
In node.js, we can include or import a module by using
require directive with module name like as shown below.
// importing node.js built-in http module
var http = require('http');
We imported an
http module by using
require directive. Now our application is having an access to HTTP module so we can create a server to listen a request and response on particular port number like as shown below.
// creating server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome to Tutlane');
res.end();}).listen(4200);
This is how we can include or import a modules in our node.js applications.
In node.js, modules are divided into three primary categories, those are:
By default, the node.js comes with a set of built-in modules and these are useful while implementing an application.
Generally, the built-in or core modules are installed on our machine during the node.js installation and those will load automatically when node.js process starts. To use built-in modules in our node.js application, we need to import it using
require directive like as mentioned above.
Following table lists some of the important built-in / core modules available in node.js.
Following is the example of using a built-in / core
http module in node.js applications. Now, create a file called Helloworld.js and write the code like as shown below.
// importing node.js built-in http module
var http = require('http');
// creating server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(4200);
If you observe above code, we imported an
http module by using
require directive to access HTTP module and created a server to listen the request and response on port number 4200.
Here, the above code will tells the computer to write “Hello World” if anyone tries to access your computer on port 4200.
Now, open node.js command prompt and navigate to the folder that contains a Helloworld.js file and initiate it by entering a command like as shown below.
Now your computer will work as server so if anyone tries to access your computer with port 4200, then in return they will get a “Hello world” message like as shown below.
In node.js, the external modules are implemented by node.js community people to solve the lot of common coding problems without rewriting the same code for every application.
Generally, these external modules are published in Node Package Manager (NPM) registry, so to use external modules in our application, first we need to install the external module codebase from NPM locally using
Npm install module_name command.
Once we install the codebase locally from NPM, then we can import it in our application using
require(‘module_name’) function.
Following table lists some of the widely downloaded external / third party modules from NPM in node.js.
In node.js, the built-in and external modules are created by others to fulfill some common functionalities, but it's not limited that we should use only those packages/modules.
In node.js, we can also create our own custom module and use it in our application by just importing it.
Following is the example of creating a module called custommodule to perform an arithmetic operations like addition, multiplication, subtraction and division.
Now, create a file called custommodule.js and write the code like as shown below.
// Creating function for adding two values
exports.Addition = function(val1, val2)
{
return (val1 + val2)
}
// Creating function for subtracting two values
exports.Subtract = function(val1, val2)
{
return (val1 - val2)
}
// Creating function for multiplying two values
exports.Multiplication = function(val1, val2)
{
return (val1 * val2)
}
// Creating function for dividing two values
exports.Division = function(val1, val2)
{
return (val1 / val2)
}
Here, we created our own custom module (custommodule) with different functions and used an
exports keyword to make our properties and methods available outside the module file.
In node.js, we can include or import our custom module same like built-in or external modules by using
require directive with module name like as shown below.
Now, create a file called mathoperations.js and write the code like as shown following to include our custom module (custommodule) in node.js application.
// Import bulit-in and custom modules
var http = require('http');
var cm = require('./custommodule');
//Create server
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Addition: ' + cm.Addition(25,50) + '</br>');
res.write('Subtraction: ' + cm.Subtract(25,50) + '</br>');
res.write('Multiplication: ' + cm.Multiplication(25,50) + '</br>');
res.write('Division: ' + cm.Division(25,50));
res.end();
}).listen(4200, console.log('Server running on port 4200'));
If you observe above example, we used a
./ to locate our custom module (customodule) in
require function, that means the custom module (custommodule.js) exists in the same folder where mathoperations.js file exists.
Now open node.js command prompt, navigate to the folder where the files exists and enter a command like
node mathoperations.js and click enter like as shown below.
Now our computer will work as server, so if anyone tries to access our computer with url, then in return they will get result like as shown below.
This is how we can create and import custom modules in our node.js applications based on requirements. | https://www.tutlane.com/tutorial/nodejs/nodejs-modules | CC-MAIN-2018-47 | en | refinedweb |
Shuffle the incoming slices randomly. More...
#include <SliceShuffle.h>
Shuffle the incoming slices randomly.
Incoming slices are stored in a buffer and on each process call a random one is drawn as output.
Controls:
Definition at line 38 of file SliceShuffle.h.
SliceShuffle constructor.
Add any specific controls needed by this MarSystem.
Definition at line 25 of file SliceShuffle.cpp.
SliceShuffle copy constructor.
All member MarControlPtr have to be explicitly reassigned in the copy constructor.
Definition at line 31 of file SliceShuffle.cpp.
SliceShuffle destructor.
Definition at line 39 of file SliceShuffle.cpp.
Implementation of the MarSystem::clone() method.
Definition at line 44 of file SliceShuffle.cpp.
Implementation of the MarSystem::myProcess method.
Pick a random slice.
Get slice from buffer and store the new input.
Definition at line 75 of file SliceShuffle.cpp. | http://marsyas.info/doc/sourceDoc/html/classMarsyas_1_1SliceShuffle.html | CC-MAIN-2018-47 | en | refinedweb |
MBFS: a parallel metadata search method based on Bloomfilters using MapReduce for large-scale file systems
Abstract
The metadata search is an important way to access and manage file systems. Many solutions have been proposed to tackle performance issue of metadata search. However, the existing solutions build a separate metadata index at the internal or external file system through the related data structure or database use semantics and event-notification method to construct the index structure, utilize the sampling-based method to conduct direct metadata search on the namespace, face problems of the high I/O overhead for maintaining consistency between metadata indexes and metadata, have enormous space overhead for metadata indexes storing and low accuracy of results and so on. To address these problems, this paper presents MBFS, a fast, accurate and lightweight metadata search method based on multi-dimensional Bloomfilters. We create a multi-dimensional Bloomfilter structure on the basis of the directory entry that can prune sub-trees to narrow the search scope of namespace. MBFS is capable of producing fast and accurate answers for a class of complex search over a file system after consuming a small number of disk accesses. MBFS residing in the file system does not need additional I/O overhead to maintain consistency. MBFS consists of Bloomfilters which are composed of bits, so it is a lightweight metadata search method that consumes marginal space overhead. Moreover, MBFS employs MapReduce for speeding up search under the environment of multiple metadata servers. Extensive experiments are conducted to prove the effectiveness of MBFS. The experimental results show that MBFS can achieve an excellent performance not only on the search latency, but also on the accuracy of results with low space and time overhead.
KeywordsLarge-scale file systems Parallel metadata search Fast and accurate Lightweight Multi-dimensional Bloomfilters
Notes
Acknowledgments
This version has benefited greatly from the many detailed comments and suggestions from the anonymous reviewers. The authors gratefully acknowledge these comments and suggestions. The work described in this paper was supported by the National Natural Science Foundation of China under Grant No. 61370059 and 61232009, the Beijing Natural Science Foundation under Grant No. 4152030, the fund of the State Key Laboratory of Software Development Environment under Grant No. SKLSDE-2014ZX-05, the Open Research Fund of The Academy of Satellite Application under Grant NO. 2014_CXJJDSJ_04, the Fundamental Research Funds for the Central Universities under Grant NO. YWF-14-JSJXY-14 and YWF-15-GJSYS-085, the Open Project Program of National Engineering Research Center for Science & Technology Resources Sharing Service (Beihang University).
References
- 1.Agrawal N, Arpaci-Dusseau AC, Arpaci-Dusseau RH (2009) Generating realistic impressions for file-system benchmarking. ACM Trans Storage 5(4):16CrossRefGoogle Scholar
- 2.Agrawal N, Bolosky WJ, Douceur JR, Lorch JR (2007) A five-year study of file-system metadata. ACM Trans Storage 3(3):9CrossRefGoogle Scholar
- 3.APPLE (2009) Spotlight server: stop searching, start finding.
- 4.Arasu A, Cho J, Garcia-Molina H, Paepcke A, Raghavan S (2001) Searching the web. ACM Trans Internet Technol 1(1):2–43CrossRefGoogle Scholar
- 5.Bergman K, Borkar S, Campbell D, Carlson W, Dally W, Denneau M, Franzon P, Harrod W, Hill K, Hiller J et al (2008) Exascale computing study: technology challenges in achieving exascale systems. Defense Advanced Research Projects Agency Information Processing Techniques Office (DARPA IPTO), Technical Report 15Google Scholar
- 6.Brin S, Page L (1998) The anatomy of a large-scale hypertextual web search engine. Comput Netw ISDN Syst 30(1):107–117CrossRefGoogle Scholar
- 7.Broder A, Mitzenmacher M (2004) Network applications of bloom filters: a survey. Internet Math 1(4):485–509MathSciNetCrossRefzbMATHGoogle Scholar
- 8.Cohen S, Matias Y (2003) Spectral bloom filters. In: Proceedings of the 2003 ACM SIGMOD international conference on management of data, pp 241–252. ACMGoogle Scholar
- 9.Dai D, Ross RB, Carns P, Kimpe D, Chen Y (2014) Using property graphs for rich metadata management in hpc systems. In: 2014 9th parallel data storage workshop (PDSW), pp 7–12. IEEEGoogle Scholar
- 10.Dean J, Ghemawat S (2008) Mapreduce: simplified data processing on large clusters. Commun ACM 51(1):107–113CrossRefGoogle Scholar
- 11.Engines I (2008) Power over information.
- 12.Fan L, Cao P, Almeida J, Broder AZ (2000) Summary cache: a scalable wide-area web cache sharing protocol. IEEE/ACM Trans Netw 8(3):281–293CrossRefGoogle Scholar
- 13.Fast (2008) A microsoft subsidiary. fast-enterprise search.
- 14.Ficara D, Giordano S, Procissi G, Vitucci F (2008) Multilayer compressed counting bloom filters. In: INFOCOM 2008. The 27th conference on computer communications. IEEEGoogle Scholar
- 15.Gifford DK, Jouvelot P, Sheldon MA et al. (1991) Semantic file systems. In: ACM SIGOPS operating systems review, vol 25. ACM, pp 16–25Google Scholar
- 16.Google I (2007) Google desktop: information when you want it, right on your desktop.
- 17.Google I (2008) Google enterprise.
- 18.Groups ES (2007) ESG research report: storage resource management on the launch pad. Technical Report etsg-1809930. Technical Report, Enterprise Strategy GroupsGoogle Scholar
- 19.Hua Y, Jiang H, Feng D (2014) Fast: near real-time searchable data analytics for the cloud. In: SC14: international conference for high performance computing, networking, storage and analysis, pp 754–765. IEEEGoogle Scholar
- 20.Hua Y, Jiang H, Zhu Y, Feng D (2010) Rapport: semantic-sensitive namespace management in large-scale file systems. CSE Technical reports. University of Nebraska, LincolnGoogle Scholar
- 21.Hua Y, Jiang H, Zhu Y, Feng D, Tian L (2009) Smartstore: a new metadata organization paradigm with semantic-awareness for next-generation file systems. In: Proceedings of the conference on high performance computing networking, storage and analysis, pp 1–12. IEEEGoogle Scholar
- 22.Hua Y, Jiang H, Zhu Y, Feng D, Xu L (2014) SANE: semantic-aware namespace in ultra-large-scale file systems. IEEE Trans Parallel Distrib Syst 25(5):1328–1338CrossRefGoogle Scholar
- 23.Hua Y, Zhu Y, Jiang H, Feng D, Tian L (2011) Supporting scalable and adaptive metadata management in ultralarge-scale file systems. IEEE Trans Parallel Distrib Syst 22(4):580–593CrossRefGoogle Scholar
- 24.Huang HH, Zhang N, Wang W, Das G, Szalay A (2012) Just-in-time analytics on large file systems. IEEE Trans Comput 61(11):1651–1664MathSciNetCrossRefGoogle Scholar
- 25.Huston L, Sukthankar R, Wickremesinghe R, Satyanarayanan M, Ganger GR, Riedel E, Ailamaki A (2004) Diamond: a storage architecture for early discard in interactive search. FAST 4:73–86Google Scholar
- 26.Imran M, Hlavacs H (2013) Searching in cloud object storage by using a metadata model. In: 2013 Ninth international conference on semantics, knowledge and grids (SKG), pp 121–128. IEEEGoogle Scholar
- 27.Inc GG (2008) Compare search appliance tools.
- 28.Katcher J (1997) Postmark: a new file system benchmark. Technical Report TR3022, Network Appliance, 1997.
- 29.KAZEON: Kazeon: search the enterprise.
- 30.Leung A, Adams I, Miller EL (2009) Magellan: a searchable metadata architecture for large-scale file systems. University of California, Santa Cruz, Technical Report UCSC-SSRC-09-07Google Scholar
- 31.Leung AW (2009) Organizing, indexing, and searching large-scale file systems. PhD thesis, University of California, Santa CruzGoogle Scholar
- 32.Leung AW, Pasupathy S, Goodson GR, Miller EL (2008) Measurement and analysis of large-scale network file system workloads. In: USENIX annual technical conference, vol 1, pp 213–226Google Scholar
- 33.Leung AW, Shao M, Bisson T, Pasupathy S, Miller EL (2009) Spyglass: fast, scalable metadata search for large-scale storage systems. FAST 9:153–166Google Scholar
- 34.Liu J, Feng D, Hua Y, Peng B, Nie Z (2014) Using provenance to efficiently improve metadata searching performance in storage systems. Future Gener Comput SystGoogle Scholar
- 35.Madden APWBA, Long MMDD. Examining scientific data for scalable index designsGoogle Scholar
- 36.Malkani P, Ellard D, Ledlie J, Seltzer M (2003) Passive NFS tracing of email and research workloads. Proceedings of the 2nd USENIX conference on file and storage technologies. pp 203–216Google Scholar
- 37.Mathur A, Cao M, Bhattacharya S, Dilger A, Tomas A, Vivier L (2007) The new ext4 filesystem: current status and future plans. In: Proceedings of the Linux symposium, vol 2. Citeseer, pp 21–33Google Scholar
- 38.MetaTracker (2008) Metatracker for linux.
- 39.Microsoft I (2009) Windows search 4.0.
- 40.Nunez J (2008) High end computing file system and IO R&D gaps roadmap. In: HEC FSIO R&D ConferenceGoogle Scholar
- 41.Ohara Y (2013) Hctrie: a structure for indexing hundreds of dimensions for use in file systems search. In: 2013 IEEE 29th symposium on mass storage systems and technologies (MSST), pp 1–5. IEEEGoogle Scholar
- 42.Owens L, Brown M, Poore K, Nicolson N (2008) The forrester wave: enterprise search, q2 2008. For information and knowledge management professionalsGoogle Scholar
- 43.Pagh A, Pagh R, Rao SS (2005) An optimal bloom filter replacement. In: Proceedings of the sixteenth annual ACM-SIAM symposium on discrete algorithms. Society for Industrial and Applied Mathematics, pp 823–829Google Scholar
- 44.Pathan AI, Sinhal A (2013) Encode decode linux based partitions to hide and explore file system. Int J Comput Appl 75(12)Google Scholar
- 45.Ross RB, Thakur R et al (2000) PVFS: a parallel file system for linux clusters. In: Proceedings of the 4th annual Linux showcase and conference, pp 391–430Google Scholar
- 46.Schwan P (2003) Lustre: building a file system for 1000-node clusters. In: Proceedings of the 2003 Linux symposium, vol 2003Google Scholar
- 47.SNIA (2010) Nfs traces.
- 48.Soules CA, Ganger GR (2005) Connections: using context to enhance file search. In: ACM SIGOPS operating systems review, vol 39. ACM, pp 119–132Google Scholar
- 49.Soules CA, Keeton K, Morrey III CB (2009) Scan-lite: enterprise-wide analysis on the cheap. In: Proceedings of the 4th ACM European conference on computer systems. ACM, pp 117–130Google Scholar
- 50.van Heuven van Staereling R, Appuswamy R, van Moolenbroek DC, Tanenbaum AS (2011) Efficient, modular metadata management with loris. In: 2011 6th IEEE international conference on networking, architecture and storage (NAS). IEEE, pp 278–287Google Scholar
- 51.Szalay A (2008) New challenges in petascale scientific databases. In: Scientific and statistical database management. Springer, Berlin, p 1Google Scholar
- 52.Takata M, Sutoh A (2012) Event-notification-based inactive file search for large-scale file systems. In: APMRC, 2012 digest. IEEE, pp 1–7Google Scholar
- 53.Ward L (2009) PDSI SciDAC: released trace data.
- 54.Weil SA (2007) Ceph: reliable, scalable, and high-performance distributed storage. PhD thesis, University of California, Santa CruzGoogle Scholar
- 55.Xiao B, Hua Y (2010) Using parallel bloom filters for multiattribute representation on network services. IEEE Trans Parallel Distrib Syst 21(1):20–32CrossRefGoogle Scholar
- 56.Xu L, Huang Z, Jiang H, Tian L, Swanson D (2014) VSFS: a searchable distributed file system. In: Parallel data storage workshop (PDSW), 2014 9th. IEEE, pp 25–30Google Scholar
- 57.Xu L, Jiang H, Liu X, Tian L, Hua Y, Hu J (2011) Propeller: a scalable metadata organization for a versatile searchable file system. CSE Technical reports. University of Nebraska, LincolnGoogle Scholar
- 58.Yu Y, Zhu Y, Ng W, Samsudin J (2014) An efficient multidimension metadata index and search system for cloud data. In: 2014 IEEE 6th international conference on cloud computing technology and science (CloudCom), pp 499–504. IEEEGoogle Scholar
- 59.Zhang Q, Feng D, Wang F, Wu S (2014) Mlock: building delegable metadata service for the parallel file systems. Sci China Inf Sci 58(3):1–14CrossRefGoogle Scholar | https://link.springer.com/article/10.1007%2Fs11227-015-1464-2 | CC-MAIN-2018-47 | en | refinedweb |
Assets¶
Coaster provides a simple asset management system for semantically versioned assets using the semantic_version and webassets libraries. Many popular libraries such as jQuery are not semantically versioned, so you will have to be careful about assumptions you make around them.
- class
coaster.assets.
VersionedAssets[source]¶
Semantic-versioned assets. To use, initialize a container for your assets:
from coaster.assets import VersionedAssets, Version assets = VersionedAssets()
And then populate it with your assets. The simplest way is by specifying the asset name, version number, and path to the file (within your static folder):
assets['jquery.js'][Version('1.8.3')] = 'js/jquery-1.8.3.js'
You can also specify one or more requirements for an asset by supplying a list or tuple of requirements followed by the actual asset:
assets['jquery.form.js'][Version('2.96.0')] = ('jquery.js', 'js/jquery.form-2.96.js')
You may have an asset that provides replacement functionality for another asset:
assets['zepto.js'][Version('1.0.0-rc1')] = { 'provides': 'jquery.js', 'bundle': 'js/zepto-1.0rc1.js', }
Assets specified as a dictionary can have three keys:
To request an asset:
assets.require('jquery.js', 'jquery.form.js==2.96.0', ...)
This returns a webassets Bundle of the requested assets and their dependencies.
You can also ask for certain assets to not be included even if required if, for example, you are loading them from elsewhere such as a CDN. Prefix the asset name with ‘!’:
assets.require('!jquery.js', 'jquery.form.js', ...)
To use these assets in a Flask app, register the assets with an environment:
from flask_assets import Environment appassets = Environment(app) appassets.register('js_all', assets.require('jquery.js', ...))
And include them in your master template:
{% assets "js_all" -%} <script type="text/javascript" src="{{ ASSET_URL }}"></script> {%- endassets -%} | https://coaster.readthedocs.io/en/latest/assets.html | CC-MAIN-2018-47 | en | refinedweb |
Lab Exercise 9: Inheritance
The purpose of this lab is to give you practice in creating a base class and many child (derived) classes that inherit the methods and fields of a base class. In addition, we'll be modifying the L-system class to enable it to use rules that include multiple possible replacement strings and choose them stochastically (randomly).
Adding the capability to incorporate different replacements will enable you to draw yet more complex L-system structures where each tree is unique. We'll continue to use material from the ABOP book.
Tasks
This week we'll modify the lsystem.py and turtle_interpreter.py files and create a new shapes.py file that implements shapes other than trees. Please follow the naming conventions for classes and methods. We'll provide some test code that expects particular classes, methods, and parameter orderings.
- Create a new working folder. Copy your lsystem.py and turtle_interpreter.py files from your prior assignment (version 2). This week we are writing version 3 of both files. Make sure a comment at the top of the file indicates they are version 3.
- The change to the Lsystem class is to enable it to use rules with multiple possible replacements. During replacement, the particular replacement string is chosen randomly. There are a number of methods requiring modification: __init__, read, replace, and addRule. In addition, you'll need to import the random package.
An example of an L-system with multiple possible replacements is given below. Note that the rule has the symbol F followed by three separate replacement strings, separated by spaces.
base F rule F F[+F]F[-F]F F[+F]F F[-F]F' ]
Here are the specific changes required for your Lsystem class.
- In the __init__ method, change the initialization of the self.rules field to be an empty dictionary instead of an empty list.
- We need to rewrite the addRule method because newrule argument, then the newrule variable will be:
[ 'F', 'F[+F]', 'F[-F]', 'F[+F][-F]' ]
The symbol 'F' is the first item in the list (newrule[0]) and the set of replacements is the remainder of the list (newrule[1:]). Modify the addRule method so that it assigns the list of replacements (newrule[1:]) to the self.rules dictionary with the symbol (newrule[0]) as the key.
- In the replace method,
- Because we are using mutators to update the information in the object, the read method should not change, so long as you are passing to self.addRule the argument words[1:], which passes everything but the first item in the words list.
When you're done with these changes, try running the classtest.py test file from last week. Do the trees all look the same?.
- Make three changes to the TurtleInterpreter class.
First, just after the class TurtleInterpreter: creating the class variable, add the following three lines to the beginning of the __init__ method. Note that we have to use the class name to access a class variable.
if TurtleInterpreter.initialized: return TurtleInterpreter.initialized = True
Now the __init__ method will not create another turtle window if it already exists.
Second, add two cases to draw string. For the character '{' call turtle.begin_fill(), and for the character '}' call turtle.end_fill().
Third, if you don't already have it, create a method color(self, c) that sets the turtle's color to the value in c.
When you're done, download and run the following test function. You should get something like the following, but with randomly selected colors.
- We're now going to start building a system that makes use of our turtle interpreter class to build shapes that are not necessarily the output of L-systems. Just as we made functions in the second project to draw shapes, now we're going to make classes that create shape objects.
Create a new file shapes.py. In it, create a class called Shape. It is a base class, from which other classes will be derived. Then define an init method with the following definition.
def __init__(self, distance = 100, angle = 90, color = (0, 0, 0), istring = '' ): # create a field of self called distance and assign it distance # create a field of self called angle and assign it angle # create a field of self called color and assign it color # create a field of TurtleInterpreter object # have the TurtleInterpreter object place the turtle at (xpos, ypos, orientation) # have the TurtleInterpreter object set the turtle color to self.color # have the TurtleInterpreter object draw the string # Note: use the distance, angle, and string fields of self # Note: multiply the distance by the scale parameter of the method
- In the same file, but below the Shape class definition, begin a new class Square that is derived from Shape.
class Square(Shape):Have the __init__() method of the Square class take two optional arguments: distance and color. The __init__() method should do the following.
def __init__(self, distance=100, color=(0, 0, 0) ): # call the parent's __init__ method with self, distance, # an angle of 90, color,.
When you are done with the lab exercises, you may begin the project. | http://cs.colby.edu/courses/F18/cs151-labs/labs/lab09/ | CC-MAIN-2018-47 | en | refinedweb |
ASP.NET webservices use XML 1.0 which restricts the character set allowed to the following chars:
[2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
(Source:)
As you can see several characters below 0x20 are not allowed with XML 1.0. This also includes characters like the vertical tab (0x0B) which is used pretty frequently.
For backward compatibility reasons .NET webservices do not support XML 1.1 which would allow these character as explained in the following article:
W3C Recommendations NOT Supported at This Time
...
XML 1.1 - Microsoft has deliberately chosen not to support the XML 1.1 Recommendation unless there is significant customer demand.
Usually the limitation of XML 1.0 is not hurting - except if the XML response sent back to the client would include one of the forbidden characters like the vertical tab.
An interesting tidbit is that the web service stub (server) routines implemented in .NET framework do not bother about the invalid characters when encoding the XML response. They encode the invalid characters as numeric character reference like for the vertical tab char. The problem occurs in the web service proxy (client) routines. These raise an exception when an entity is returned which is not allowed in XML 1.0:
There is an error in XML document (8, 1314).)
...
So there is a slight discrepancy between the handling of the invalid characters on the web service proxy and stub side.
It would be great if the ASP.NET webservice classes would avoid sending invalid numeric character references to the client at all - but that is not implemented in .NET framework. As the client also cannot get hands on the content before the exception is raised it would be required to fix the issue in the application logic of the web service itself.
Means each web service method would have to replace the invalid characters before sending the XML content to the client.
The problem here is that usually the automatic XML serialization of managed objects is used to create the XML response. So fixing the issue inside the web service is also not trivial.
This issue also affects the standard sharepoint web services which allow access to SharePoint content.
To overcome this problem it would be required to remove the invalid characters from the XML response (e.g. replace them with a space char) after they have been serialized to XML and before they are sent over the wire to the caller of the web service.
The good message is: ASP.NET has indeed a way to achieve this: SoapExtensions. A SoapExtension allows to consume and modify the SOAP message sent from client to server and vice versa.
Below is a SoapExtension which replaces the invalid control characters with a blank character (0x20) using Regular Expressions:
///
///.
///
using System;
using System.IO;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace StefanG.SoapExtensions
{
public class XmlCleanupSoapExtension : SoapExtension
{
private Regex replaceRegEx;
private Stream oldStream;
private Stream newStream;
// to modify the content we redirect the stream to a memory stream to allow
// easy consumption and modifcation
public override Stream ChainStream(Stream stream)
{
// keep track of the original stream
oldStream = stream;
// create a new memory stream and configure it as the stream object to use as input and output of the webservice
newStream = new MemoryStream();
return newStream;
}
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
// the module is intended to look at all methods. Not on methods tagged with a specific attribute
throw new Exception("The method or operation is not implemented.");
}
public override object GetInitializer(Type serviceType)
{
// create a compiled instance of the Regular Expression for the chars we would like to replace
// add all char points beween 0 and 31 excluding the allowed white spaces (9=TAB, 10=LF, 13=CR)
StringBuilder RegExp = new StringBuilder("&#(0");
for (int i = 1; i <= 31; i++)
{
// ignore allowed white spaces
if (i == 9 || i == 10 || i == 13) continue;
// add other control characters
RegExp.Append("|");
RegExp.Append(i.ToString());
// add hex representation as well
RegExp.Append("|x");
RegExp.Append(i.ToString("x"));
}
RegExp.Append(");");
string strRegExp = RegExp.ToString();
// create regular expression assembly
Regex regEx = new Regex(strRegExp, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// return the compiled RegEx to all further instances of this class
return regEx;
}
public override void Initialize(object initializer)
{
// instance initializers retrieves the compiled regular expression
replaceRegEx = initializer as Regex;
}
public override void ProcessMessage(SoapMessage message)
{
if (message.Stage == SoapMessageStage.AfterSerialize)
{
// process the response sent back to the client - means ensure it is XML 1.0 compliant
ProcessOutput(message);
}
if (message.Stage == SoapMessageStage.BeforeDeserialize)
{
// just copy the XML Soap message from the incoming stream to the outgoing
ProcessInput(message);
}
}
public void ProcessInput(SoapMessage message)
{
// no manipulation required on input data
// copy content from http stream to memory stream to make it available to the web service
TextReader reader = new StreamReader(oldStream);
TextWriter writer = new StreamWriter(newStream);
writer.WriteLine(reader.ReadToEnd());
writer.Flush();
// set position back to the beginning to ensure that the web service reads the content we just copied
newStream.Position = 0;
}
public void ProcessOutput(SoapMessage message)
{
// rewind stream to ensure that we read from the beginning
newStream.Position = 0;
// copy the content of the stream into a memory buffer
byte[] buffer = (newStream as MemoryStream).ToArray();
// shortcut if stream is empty to avoid exception later
if (buffer.Length == 0) return;
// convert buffer to string to allow easy string manipulation
string content = Encoding.UTF8.GetString(buffer);
// replace invalid XML entities using regular expression
content = replaceRegEx.Replace(content, " ");
// convert back to byte buffer
buffer = Encoding.UTF8.GetBytes(content);
// stream byte buffer to the client app
oldStream.Write(buffer, 0, buffer.Length);
}
}
}
The above code should be compiled into a C# class library project and signed with a strong name to allow placing the DLL into a GAC.
Afterwards the SoapExtension can be registered in the web.config of the affected web service. For SharePoint webservices this would be the web.config in the following directory:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\
The following entry needs to be added to the web.config:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
<system.web>
<webServices>
<soapExtensionTypes>
<add type="StefanG.SoapExtensions.XmlCleanupSoapExtension, XmlCleanupSoapExtension, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0e15300fe8a7b210" priority="1" group="0" />
</soapExtensionTypes>
...
</webServices>
...
</system.web>
...
</configuration>
Afterwards all responses from webservice methods in the affected web application will automatically be cleaned up.
The complete source code can also be downloaded from here:
Wondering why you kept the default throw exception for the first Method ?
If something calls it would it not be better to just call the base ?
Hi BinaryJam,
the "base" class is an abstract class and the GetInitializer method is not implemented there.
So you have to implement the method yourself.
Cheers,
Stefan
Does this work for .NET web services that were created using VS’s wsdl.exe app? I’ve compiled a third party’s web service into a webservice.cs class in this way, and need some way to clean up the returned xml.
Sorry if this question belongs elsewhere – I’m very new to implementing web services, so maybe there’s an even simpler answer – thanks for your help!
Hi Nat,
from my understanding this should work for any type of ASP.NET web service.
Cheers,
Stefan
instead of GetInitialize to build RegEx. Isn't private shared variable make sense ?!
private shared m_RegEx = new RegEx("&#(0|1|x1|2|x2|3|x3|4|x4|5|x5|6|x6|7|x7|8|x8|11|xb|12|xc|14|xe|15|xf|16|x10|17|x11|18|x12|19|x13|20|x14|21|x15|22|x16|23|x17|24|x18|25|x19|26|x1a|27|x1b|28|x1c|29|x1d|30|x1e|31|x1f);", RegExOptions.compiled | RegExOptions.Ignorecase)
Fantastic! Used this to fix my issue: Sharepoint's web service's method GetListItems fails with error "'_', hexadecimal value 0x0B, is an invalid character. I did modify the following method, as my invalid characters were coming back from Sharepoint.
public void ProcessInput(SoapMessage message)
{
// copy content from http stream to memory stream to make it available to the web service
TextReader reader = new StreamReader(oldStream);
TextWriter writer = new StreamWriter(newStream);
string outputStr = reader.ReadToEnd();
outputStr = replaceRegEx.Replace(outputStr, " ");
writer.WriteLine(outputStr);
writer.Flush();
// set position back to the beginning to ensure that the web service reads the content we just copied
newStream.Position = 0;
}
So when SharePoint sends a vertical tab, how can we stop it on the client side? SharePoint web services are not something that can easily be modified to fix what is clearly a bug.
Hi Dale,
you would need to read the stream in raw format as otherwise the code generated by .NET will run into the exception.
Cheers,
Stefan
Hi Stefan GoBner
I am getting Exception :Response is not well-formed XML. Inner ExceptionMsg :'', hexadecimal value 0x1F, is an invalid character. Line 1, position 1.
how to reslove this issue based on your SoapExtension in Console Application
Hi Tejas,
this extension fixes the issue on the server, before the content is sent over the wire.
This solution cannot be used to fix the issue on the receiver side.
Cheers,
Stefan
Hi Stefan GoBner,
Thanks for your reply,
Is there any way to use this type of SOAP extensions in receiver side to resolve issue.
Hi Tejas,
you cannot use this method on the receiving side, as you cannot modify the stream content before the exception occurs.
Cheers,
Stefan
It is totally possible to implement a SOAP extension that works client side (receiving side) to clean up the response from the server. I implemented it myself, and it works great.
It seems like Stefan was saying this is not possible, but it is absolutely possible.
Hi Stefan,
I tried your solution, and made all the stages i think. But i get now new error:
“client found response content type of ” but expected ‘text xml’ The request failed with an empty response.”
When i delete from the web.service the lines:
so the error doesn’t appeaer (but then the original problem you tried to solve comes back..)
Any idea what i can do ?…
Thanks a lot for your help !!
Nathan
I meant that the lines you added to the ws make the error
Hi Nathan,
your comment seems to be incomplete.
Which lines did you remove?
The error message indicates that an empty response was received – means that everything was removed from the response.
My code does not do this so I think there is something different in your code.
Cheers,
Stefan | https://blogs.technet.microsoft.com/stefan_gossner/2009/08/26/how-to-deal-with-invalid-characters-in-soap-responses-from-asp-net-web-services/ | CC-MAIN-2018-47 | en | refinedweb |
Let inexed C++ implementation of Kasai’s algorithm.
// C++ program for building LCP array for given text #include <bits/stdc++.h> using namespace std; // Structure to store information of a suffix struct suffix { int index; // To store original index int rank[2]; // To store ranks and next rank pair }; // A comparison function used by sort() to compare two suffixes // Compares two pairs, returns 1 if first pair is smaller int cmp(struct suffix a, struct suffix b) { return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0); } // This is the main function that takes a string 'txt' of size n as an // argument, builds and return the suffix array for the given string vector<int> buildSuffixArray(string txt, int n) { // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array of structures. // The structure is needed to sort the suffixes alphabatically // and maintain their old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At his point, all suffixes are sorted according to first // 2 characters. Let us sort suffixes according to first 4 // characters, then first 8 and so on int ind[n]; // This array is needed to get the index in suffixes[] // from original index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as that of previous // suffix in array, assign the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix array vector<int>suffixArr; for (int i = 0; i < n; i++) suffixArr.push_back(suffixes[i].index); // Return the suffix array return suffixArr; } /* To construct and return LCP */ vector<int> kasai(string txt, vector<int> suffixArr) { int n = suffixArr.size(); // To store LCP array vector<int> lcp(n, 0); // An auxiliary array to store inverse of suffix array // elements. For example if suffixArr[0] is 5, the // invSuff[5] would store 0. This is used to get next // suffix string from suffix array. vector<int> invSuff(n, 0); // Fill values in invSuff[] for (int i=0; i < n; i++) invSuff[suffixArr[i]] = i; // Initialize length of previous LCP int k = 0; // Process all suffixes one by one starting from // first suffix in txt[] for (int i=0; i<n; i++) { /* If the current suffix is at n-1, then we don’t have next substring to consider. So lcp is not defined for this substring, we put zero. */ if (invSuff[i] == n-1) { k = 0; continue; } /* j contains index of the next substring to be considered to compare with the present substring, i.e., next string in suffix array */ int j = suffixArr[invSuff[i]+1]; // Directly start matching from k'th index as // at-least k-1 characters will match while (i+k<n && j+k<n && txt[i+k]==txt[j+k]) k++; lcp[invSuff[i]] = k; // lcp for the present suffix. // Deleting the starting character from the string. if (k>0) k--; } // return the constructed lcp array return lcp; } // Utility function to print an array void printArr(vector<int>arr, int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } // Driver program int main() { string str = "banana"; vector<int>suffixArr = buildSuffixArray(str, str.length()); int n = suffixArr.size(); cout << "Suffix Array : \n"; printArr(suffixArr, n); vector<int>lcp = kasai(str, suffixArr); cout << "\nLCP Array : \n"; printArr(lcp, n); return 0; } suffx previous value was 2. Since there is no character after “a”, final value of LCP is 1. We fill lcp[0] as 1.
We will soon be discussing
Recommended Posts:
- Suffix Array | Set 2 (nLogn Algorithm)
- Z algorithm (Linear time pattern searching Algorithm)
- Suffix Array | Set 1 (Introduction)
- Pattern Searching | Set 8 (Suffix Tree Introduction)
- Ukkonen’s Suffix Tree Construction – Part 1
- Number of elements greater than K in the range L to R using Fenwick Tree (Offline queries)
- Iterative Segment Tree (Range Minimum Query)
- Count inversions of size k in a given array
- Remove edges connected to a node such that the three given nodes are in different trees
- Sum of K largest elements in BST using O(1) Extra space
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. | https://www.geeksforgeeks.org/%C2%AD%C2%ADkasais-algorithm-for-construction-of-lcp-array-from-suffix-array/ | CC-MAIN-2018-34 | en | refinedweb |
imap: An efficient IMAP client library, with SSL and streaming
This is an IMAP library for Haskell that aims to be efficient, easy to use, transparent when it comes to underlying libraries and support results streaming. To this end it employs
ListT, so you can use it with any concurrency management library of your choosing.
It tries to implement RFC-3501 as faithfully as possible, diverging from it where we noticed that servers have different ideas. If you want to understand this library, it's highly recommended to skim through that RFC first.
Usage
For a description of types used in this tutorial or an in-depth description of functions presented, please check the documentation or the source code.
All of the commands will output their results in
ListT and
MonadIO. Results consist of a list of
UntaggedResults followed by a single
TaggedResult that describes the command state (if it succeeded or failed).
We provide a helper function that simplifies the output types for the cases when you don't care about the streaming and just want a list of
UntaggedResults or an error message. Depending on your needs you will probably use it for all the commands that are not
FETCH.
Also, remember that you probably have to keep the connection alive so that the server doesn't disconnect you. Send a
noop from time to time to achieve that.
Simple, no streaming
You need a connection object first, so that you can execute commands on it. It's produced by
connectServer, which accepts parameters from Network.Connection. Say you want to connect to gmail:
import Network.Connection import Network.IMAP import Network.IMAP.Types
let tls = TLSSettingsSimple False False False let params = ConnectionParams "imap.gmail.com" 993 (Just tls) Nothing conn <- connectServer params Nothing
From now on you can run commands on this connection. The second parameter to
connectServer is `Maybe IMAPSettings`. If settings are not provided, sane defaults will be used. We will use the
simpleFormat helper function to convert from
ListT to
IO. Let's log in:
simpleFormat $ login conn "mylogin" "mypass" Right [Capabilities [CIMAP4,CUnselect,CIdle,CNamespace,CQuota,CId,CExperimental "XLIST",CChildren,CExperimental "X-GM-EXT-1",CUIDPlus,CCompress "DEFLATE",CEnable,CMove,CCondstore,CEsearch,CUtf8 "ACCEPT",CListExtended,CListStatus,CAppendLimit 35882577]]
You can see that the server replied with a
CAPABILITIES reply and the login was successful. Next, let's select an inbox:
simpleFormat $ select conn "inbox2" Left "[NONEXISTENT] Unknown Mailbox: inbox2 (Failure)"
Oh, let's fix that
simpleFormat $ select conn "inbox" Right [Flags [FAnswered,FFlagged,FDraft,FDeleted,FSeen,FOther "$NotPhishing",FOther "$Phishing",FOther "NonJunk"],PermanentFlags [FAnswered,FFlagged,FDraft,FDeleted,FSeen,FOther "$NotPhishing",FOther "$Phishing",FOther "NonJunk",FAny],UIDValidity 1,Exists 65,Recent 0,UIDNext 1050,HighestModSeq 251971]
Again you can use the metadata if you wish to. Let's see what messages we have (consult the RFC if you're unsure about the parameter to
uidSearch):
simpleFormat $ uidSearch conn "ALL" Right [Search [105,219,411,424,425,748,763,770,774,819,824,825,..]]
Fetching a message is straigtforward as well:
simpleFormat $ uidFetch conn "219" Right [Fetch [MessageId 2,UID 219,Body "Delivered-To: michal@monad.cat\r\nReceived: by...
If you need more control on the parameters of fetch, there is a more general function available:
simpleFormat $ uidFetchG conn "219 ALL"
Do you want multiple messages in one reply? That's easy with UID ranges!
simpleFormat $ uidFetchG conn "219:9000 RFC822.SIZE" Right [Fetch [MessageId 2,UID 219,Size 4880],Fetch [MessageId 3,UID 411,Size 7392],...]
That's where streaming comes in handy - if these were message bodies you would probably like to do something with them before all are downloaded.
Replies we didn't expect
IMAP protocol allows for messages pushed to the client at any time, even when they're not requested. This is used to notify the client that a new message had arrived, or as status of a message had changed as it was read by another client. These server messages wait for you in a bounded message queue and you can read them like:
import qualified Data.STM.RollingQueue as RQ msgs <- atomically . RQ.read . untaggedQueue $ conn
Where
conn is the connection from previous step.
Streaming
There's an excellent article by Gabriel Gonzalez you should read :)
Modules
Downloads
- imap-0.3.0.8.tar.gz [browse] (Cabal source package)
- Package description (as included in the package)
Maintainer's Corner
For package maintainers and hackage trustees | http://hackage.haskell.org/package/imap | CC-MAIN-2018-34 | en | refinedweb |
I tried to allocate memory on MPB using RCCE_malloc in gory mode. I use the emulator to run a simple examples like this (haven't got scc HW yet):
#include <stdio.h>
#include <stdlib.h>
#include "RCCE.h"
int RCCE_APP(int argc, char** argv) {
RCCE_init(&argc, &argv);
double * temp=(double *) RCCE_malloc(sizeof(double));
if (!temp) printf("allocation was not successful ! \n");
RCCE_finalize();
return (1);
}
It seems that allocation is always unsuccessful. Any ideas why it is like this?
I preffered to ask before have a look at RCCE_malloc code in gory mode.
Omid
You must allocate whole cache lines. RCCE_malloc returns NULL if size is not a multiple of 32 bytes. | https://communities.intel.com/thread/21070 | CC-MAIN-2018-34 | en | refinedweb |
On Tue, Mar 22, 2016 at 10:57 AM, Peter Geoghegan <p...@heroku.com> wrote: > That's right - I have a small number of feedback items to work > through. I also determined myself that there could be a very low > probability race condition when checking the key space across sibling > pages, and will work to address that.
I attach a V2 revision. Behavioral changes: * Fixes very low probability race condition when verifying ordering across sibling pages with bt_index_check()/AccessShareLock. Notably, the fix does not involve using the high key from the next page instead of the first item, despite my recent suggestion that it would; I changed my mind. In this revision, bt_right_page_check_scankey() continues to return the first item on the next/right page (as a scankey), just as in the first version. The locking considerations here are more complicated than before, and hopefully correct. I abandoned the high key idea when I realized that a concurrent page split could happen in the right sibling, making the high key generally no more safe in the face of concurrent target page deletion than continuing to use the first data item. Using the first data item from the right page is better than using the high key item from the right page verification-wise anyway, so that's good. I found a new way of locking down and recovering from any race conditions (the low probability bug in V1 for bt_index_check()/AccessShareLock calls to the C function bt_right_page_check_scankey()). I won't go into the gory details here, but I will mention that my new approach is inspired by how backwards scans work already. * Adds DEBUG1 traces that indicate the level and page currently being checked. Advanced users will probably find these traces useful on occasion. It's nice to be able to see how amcheck walks the B-Tree in practice. Non-behavioral changes: * Explains why an ExclusiveLock is needed on the target index by bt_index_parent_check() (and a ShareLock on its heap relation). This new explanation talks about why an ExclusiveLock *is* necessary when checking downlinks against child pages, per Tomas Vondra's request. (Note that nothing changes about child/downlink verification itself). Before now, I focused on why they were not necessary, but Tomas was right to point out that that isn't enough information. * No longer uses the word "comport" in an error message, per Amit Langote. Similarly, minor typos fixed, per Tomas. * Adds a variety of pg_regress-based tests for external sorting. (Via various CREATE INDEX statements involving a variety of datatypes. Data is generated pseudo-randomly.) Notably, the regression tests *never* test external sorting today. ISTM that amcheck is a convenient, reliable, and portable way of testing the sorting of collatable types like text, so this is the best way of testing external sorting. External sorting uses abbreviated keys for runs, but discards them as runs are written out, and so the merging of runs does not use abbreviated keys. Abbreviated comparisons and authoritative comparisons are therefore reliably used within the same sort. One particular goal here is that something like the recent strxfrm() debacle might be caught by this testing on some platforms (if we ever get back to trusting strxfrm() at all, that is). The style of these new tests is unorthodox, because a variety of collations are tested, which varies from system to system; we should discuss all this. The tests can take a minute or two to run on my laptop, but that could vary significantly. And so, whether or not that needs to be targeted by something other than "check" and "installcheck" is a discussion that needs to happen. I imagine a lot of buildfarm animals have slow storage, but on the other hand I don't think hackers run the contrib regression tests so often. I prefer to not follow the example of test_decoding if possible; test_decoding's Makefile only runs tests when wal_level=logical is expected (that's how the relevant Makefile targets are scoped), but it's a complicated special case. Review ------ As already noted after the first bullet point, there are some tricky considerations on fixing the race when the user calls bt_index_check(). Reviewers should pay close attention to this; could I be wrong about that being race-safe even now? This seems to me to be by far the best place for reviewers to look for problems in this patch, as it's the only bt_index_check()/AccessShareLock case that compares anything *across* pages. The measures taken to prevent false positives described within bt_target_page_check() require expert review, especially because this is the one case where a faulty rationale may result in under-protection from false positives, and not just harmless over-protection. The rationale for why we can reliably recover from a race described within the C function bt_right_page_check_scankey() is *complicated*. I may have failed to make it as simple as possible despite significant effort. It's hard to describe these things in an accessible way. Maybe someone can try and understand what I've said there, and let me know how I might have fallen short. I have used a new term, "cousin page" in this explanation (cf. sibling page). This seems like useful terminology that makes these difficult explanations a bit more accessible. -- Peter Geoghegan
From 06085b27dc36c1e05e0049d90374b9c687e5ea9. To test amcheck, add regression tests that feature a variety of CREATE INDEX statements (these are always external sort cases), and verify the indexes afterwards in each case. Aside from testing amcheck itself, this approach also fills a gap in the test coverage of the standard regression tests, since external sorts were previously completely untested. This also makes it possible to test OS collations without any specific expectation about an "expected" pg_regress output, or even specific advanced knowledge of which collations are to be tested. --- contrib/Makefile | 1 + contrib/amcheck/Makefile | 22 + contrib/amcheck/amcheck--1.0.sql | 20 + contrib/amcheck/amcheck.c | 1265 ++++++++++++++++++++ contrib/amcheck/amcheck.control | 5 + contrib/amcheck/expected/extern_sort_bytea.out | 44 + .../amcheck/expected/extern_sort_collations.out | 42 + contrib/amcheck/expected/extern_sort_numeric.out | 44 + contrib/amcheck/expected/install_amcheck.out | 1 + contrib/amcheck/sql/extern_sort_bytea.sql | 23 + contrib/amcheck/sql/extern_sort_collations.sql | 42 + contrib/amcheck/sql/extern_sort_numeric.sql | 29 + contrib/amcheck/sql/install_amcheck.sql | 1 + doc/src/sgml/amcheck.sgml | 247 ++++ doc/src/sgml/contrib.sgml | 1 + doc/src/sgml/filelist.sgml | 1 + 16 files changed, 1788 contrib/amcheck/expected/extern_sort_bytea.out create mode 100644 contrib/amcheck/expected/extern_sort_collations.out create mode 100644 contrib/amcheck/expected/extern_sort_numeric.out create mode 100644 contrib/amcheck/expected/install_amcheck.out create mode 100644 contrib/amcheck/sql/extern_sort_bytea.sql create mode 100644 contrib/amcheck/sql/extern_sort_collations.sql create mode 100644 contrib/amcheck/sql/extern_sort_numeric.sql create mode 100644 contrib/amcheck/sql/install_amcheck.sql create mode 100644 doc/src/sgml/amcheck.sgml diff --git a/contrib/Makefile b/contrib/Makefile index d12dd63..cecfb6d 100644 --- a/contrib/Makefile +++ b/contrib/Makefile @@ -6,6 +6,7 @@ include $(top_builddir)/src/Makefile.global SUBDIRS = \ adminpack \ + amcheck \ auth_delay \ auto_explain \ btree_gin \ diff --git a/contrib/amcheck/Makefile b/contrib/amcheck/Makefile new file mode 100644 index 0000000..26b7b9b --- /dev/null +++ b/contrib/amcheck/Makefile @@ -0,0 +1,22 @@ +#), c.relname, c.relpages +FROM pg_index i +JOIN pg_opclass op ON i.indclass[0] = op.oid +JOIN pg_am am ON op.opcmethod = am.oid +JOIN pg_class c ON i.indexrelid = c.oid +JOIN pg_namespace n ON c.relnamespace = n.oid +WHERE am.amname = 'btree' AND n.nspname = 'pg_catalog' +-- Don't check pg_class (bt_index_parent_check() requires this): +AND c.relname NOT LIKE 'pg_class%' +-- Function may throw an error when this is omitted: +AND i.indisready AND i.indisvalid +ORDER BY c.relpages DESC LIMIT 10; + bt_index_check | relname | relpages +----------------+---------------------------------+---------- + | pg_depend_reference_index | 43 + | pg_depend_depender_index | 40 + | pg_proc_proname_args_nsp_index | 31 + | pg_description_o_c_o_index | 21 + | pg_attribute_relid_attnam_index | 14 + | pg_proc_oid_index | 10 + | pg_attribute_relid_attnum_index | 9 + | pg_amproc_fam_proc_index | 5 + | pg_amop_opr_fam_index | 5 + | pg_amop_fam_strat_index | 5 +(10 rows) +</screen> + This example shows a session that performs verification of every + catalog index in the database <quote>test</> (except those + associated with the <structname>pg_class</structname> catalog). + Details of just the 10 largest indexes verified are displayed. + Since no error is raised, all indexes tested appear to be + logically consistent.. <function>bt_index_parent_check</function> + follows the general convention of raising an error if it finds a + logical inconsistency or other problem. + <>major</> operating system version in use is + inconsistent. Such inconsistencies will generally only arise on + standby servers, and so can generally only be detected on standby + servers. If a problem like this arises, it may not affect each + individual index that is ordered using an affected collation, + simply because 4e3f337..9f6389c 30adece..5675d6d: | https://www.mail-archive.com/pgsql-hackers@postgresql.org/msg282979.html | CC-MAIN-2018-34 | en | refinedweb |
import "go.chromium.org/luci/milo/buildsource/rawpresentation"
build.go html.go logDogBuild.go logDogStream.go
const ( // DefaultLogDogHost is the default LogDog host, if one isn't specified via // query string. DefaultLogDogHost = chromeinfra.LogDogHost )
func AddLogDogToBuild( c context.Context, ub URLBuilder, mainAnno *miloProto.Step, build *ui.MiloBuild)
AddLogDogToBuild takes a set of logdog streams and populate a milo build. build.Summary.Finished must be set.
func GetBuild(c context.Context, host string, project types.ProjectName, path types.StreamPath) (*ui.MiloBuild, error)
GetBuild returns a build from a raw annotation stream.
InjectFakeLogdogClient adds the given logdog.LogsClient to the context.
You can obtain a fake logs client from
go.chromium.org/luci/logdog/api/endpoints/coordinator/logs/v1/fakelogs
Injecting a nil logs client will panic.
NewClient generates a new LogDog client that issues requests on behalf of the current user.
ReadAnnotations synchronously reads and decodes the latest Step information from the provided StreamAddr.
func SubStepsToUI(c context.Context, ub URLBuilder, substeps []*miloProto.Step_Substep) ([]*ui.BuildComponent, []*ui.PropertyGroup)
SubStepsToUI converts a slice of annotation substeps to ui.BuildComponent and slice of ui.PropertyGroups.
type AnnotationStream struct { Project types.ProjectName Path types.StreamPath // Client is the HTTP client to use for LogDog communication. Client *coordinator.Client // contains filtered or unexported fields }
AnnotationStream represents a LogDog annotation protobuf stream.
Fetch loads the annotation stream from LogDog.
If the stream does not exist, or is invalid, Fetch will return a Milo error. Otherwise, it will return the Step that was loaded.
Fetch caches the step, so multiple calls to Fetch will return the same Step value.
func (as *AnnotationStream) Normalize() error
Normalize validates and normalizes the stream's parameters.
type Stream struct { // Server is the LogDog server this stream originated from. Server string // Prefix is the LogDog prefix for the Stream. Prefix string // Path is the final part of the LogDog path of the Stream. Path string // IsDatagram is true if this is a MiloProto. False implies that this is a text log. IsDatagram bool // Data is the miloProto.Step of the Stream, if IsDatagram is true. Otherwise // this is nil. Data *miloProto.Step // Text is the text of the Stream, if IsDatagram is false. Otherwise // this is an empty string. Text string // Closed specifies whether Text or Data may change in the future. // If Closed, they may not. Closed bool }
Stream represents a single LogDog style stream, which can contain either annotations (assumed to be MiloProtos) or text. Other types of annotations are not supported.
type Streams struct { // MainStream is a pointer to the primary stream for this group of streams. MainStream *Stream // Streams is the full map streamName->stream referenced by MainStream. // It includes MainStream. Streams map[string]*Stream }
Streams represents a group of LogDog Streams with a single entry point. Generally all of the streams are referenced by the entry point.
type URLBuilder interface { // LinkURL returns the URL associated with the supplied Link. // // If no URL could be built for that Link, nil will be returned. BuildLink(l *miloProto.Link) *ui.Link }
URLBuilder constructs URLs for various link types.
type ViewerURLBuilder struct { Host string Prefix types.StreamName Project types.ProjectName }
ViewerURLBuilder is a URL builder that constructs LogDog viewer URLs.
func NewURLBuilder(addr *types.StreamAddr) *ViewerURLBuilder
NewURLBuilder creates a new URLBuilder that can generate links to LogDog pages given a LogDog StreamAddr.
BuildLink implements URLBuilder.
Package rawpresentation imports 24 packages (graph) and is imported by 8 packages. Updated 2018-08-14. Refresh now. Tools for package owners. | https://godoc.org/go.chromium.org/luci/milo/buildsource/rawpresentation | CC-MAIN-2018-34 | en | refinedweb |
Document Reader : Visual C#
Document Reader is a text-editor cum text-to-speech converter. It means that this Visual C# program lets you read your text documents as well as listen to them. Isn’t that cool? I’m sure you’d love it.
Document Reader
If you’re not a programmer and just want to download and use this program, you can download it here. To listen to the document, click on the “Read Aloud” option in the Document Menu. If you are a programmer, you might want to read the details of the program in the sections that follow. This program requires .NET Framework 4.5
Document Reader – Concept
This program is based on a previously published Visual C# project – the SharpPad, which was a text-editor. The new and interesting part of the Document Reader is the ability to read text aloud.
This program utilizes the System.Speech.Synthesis namespace for converting text to speech. An instance of the SpeechSynthesizer class is created and used to read the text. There are several methods to set the type, volume and rate of the sound produced (However, these functions had no effect on the properties of the sound produced when this program was being developed and tested). The SpeakAsync() method finally produces the sound (You can also use the Speak() method instead).
Apart from that, everything is easy to guess. The SpeakAsync() method reads the contents of the RichTextBox and converts the text to speech. However, if there is no text in the RichTextBox, the program says, “The current document is blank. Please open a document with some text”.
Document Reader – Screenshots
The following images describe the functionality of the Document Reader:
Document Reader – Blank
Document Reader – Opening a File
Document Reader – Document Opened
Document Reader – Reading Aloud
As you can see in the above images, you just need to open a text document and then click on the “Read Aloud” option in the Document Menu. The program starts converting the document’s text to speech. The volume of the speech output depends upon your computer’s Speaker Volume. You can also modify the code to make the speech output work as per your requirements.
Downloads
Click here to download the source code of Document Reader (71 KB)
Click here to download only the executable of this program (22 KB). This program requires .NET Framework 4.5
Click here to download the installer of this program (159 KB). This program requires .NET Framework 4.5
Share this COOL project
This is one of the best projects by Windows Code Bits yet. If you liked this project, don’t forget to share it and help others. Also, let us know your opinion about this program. Your feedback helps us create better projects. | https://www.wincodebits.in/2016/02/document-reader-visual-c.html | CC-MAIN-2018-34 | en | refinedweb |
public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub exByte(); } public static void exByte(){ double d=3.4444d; d=34444-04;//exponential notation System.out.println("d is"
why above gives compile error.
below why giving false.
Open in new window
float f=3.4444f;
d=34444-04;//subtraction notation
System.out.println("d is"+d);
System.out.println("f is"+f);
System.out.println("d==f is"+ (d==f));
d=34444e-04;//exponential notation
System.out.format("d is %.16f\n",d);
System.out.format("f is %.16f\n",f);
System.out.println("d==f is"+ (d==f));
d is34440.0
f is3.4444
d==f isfalse
d is 3.4444000000000000
f is 3.4444000720977783
d==f isfalse
d is34440.0
d is3.4444E8
Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
exByte();
}
public static void exByte(){
float f=3.4444f;
double d=3.4444d;
d=34444-04;//exponential notation
System.out.println("d is"+d);
System.out.println("d==f is"+ d==f);
System.out.println("d==f is"+ f==d);
}
}
both of above bolded lines giving error incomatible types even high precision double assigned to low precision float or vice versa.
please advise
Those lines should have been
System.out.println("d==f is"+ (d==f));
System.out.println("d==f is"+ (f==d));
what it mean by subtraction notation
why it gave output
d is34440.0
Open in new window
above gives
Open in new window
how it exponential operator different from addition or subtraction. please advise
Exponential (a.k.a. scientific) notation for float or double literals can be expressed using E or e
Open in new window
i got output as
Open in new window
means like below right
d3=34444*(10 to the power of -4)
which is moving the decimal to left side 4 digits as below
d3 is 3.4444000000000000
i wonder why below line giving compilation error
//float f3 = 34444e-04;//exponential notation
please advise
a double approximates 3.4444 as
3.444399999999999906208358
a float approximates 3.4444 as
3.4444000720977783203125
you can explicitly convert
float f3 = (float)34444e-04;
or start with a float
float f3 = 34444e-04f;
Experts Exchange Solution brought to you by
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial | https://www.experts-exchange.com/questions/28632970/double-exponentioal-notation.html | CC-MAIN-2018-47 | en | refinedweb |
SD card not recognized in expansion board with LoPy and deepsleep shield
I have inserted an 8GB FAT32 formatted SD card into an expansion board and put the deepsleep shield and LoPy on top of that. When i open REPL and do:
from machine import SD
sd = SD()
i get: "OSError: the requested operation failed"
Any clues to what is going on? The SD Card opens up fine in my Mac.
I have a sensor attached to pins G11 and G24 on the expansion board. Could this be conflicting on the Uart? The LoPy is on firmware 1.7.9.b1
- jmarcelino last edited by
@robin
UART0 is a bit special - need to look into that myself - but you can easily redefine the UART1 pins (and UART2 unless on the GPy/FiPy)
@jmarcelino does this mean you cannot use UART and the SD card?
I have not been able to use Uart 0 (this interfered with program and REPL execution) nor have i been able to redefine Uart 0 to different pins.
Is there an example of how to use UART and SD together?
Thanks @jmarcelino
The reference for the expansion board indeed lists this pin as being used by the SD card. Moved my sensor to G4 an G5. Its a pity G11 and G24 are the default Uart pins.
- jmarcelino last edited by jmarcelino
@robin
G11 is definitely connected to the SD card (SD_CMD) so you can't use it for other purposes if you need the SD card working. | https://forum.pycom.io/topic/2381/sd-card-not-recognized-in-expansion-board-with-lopy-and-deepsleep-shield | CC-MAIN-2018-47 | en | refinedweb |
Gecode::Int::Linear::ReLq< Val, P, N, rm > Class Template Reference
[Integer propagators]
Propagator for reified bounds consistent n-ary linear less or equal More...
Detailed Description
template<class Val, class P, class N, ReifyMode rm>
class Gecode::Int::Linear::ReLq< Val, P, N, rm >
Propagator for reified bounds consistent n-ary linear less or equal
The type Val can be either
long long int or
int, defining the numerical precision during propagation. The types P and N give the types of the views.
The propagation condition pc refers to both views.
Requires
#include <gecode/int/linear.hh>
Definition at line 749 of file linear.hh.
Constructor & Destructor Documentation
Constructor for cloning p.
Definition at line 844 of file int-nary.hpp.
Constructor for creation.
Definition at line 822 of file int-nary.hpp.
Member Function Documentation
Create copy during cloning.
Implements Gecode::Actor.
Definition at line 849 of file int-nary.hpp.
Perform propagation.
Implements Gecode::Propagator.
Definition at line 855 of file int-nary.hpp.
Post propagator for
.
Definition at line 828 of file int-nary.hpp.
The documentation for this class was generated from the following files:
- gecode/int/linear.hh
- gecode/int/linear/int-nary.hpp | https://www.gecode.org/doc-latest/reference/classGecode_1_1Int_1_1Linear_1_1ReLq.html | CC-MAIN-2018-47 | en | refinedweb |
ansible-galaxy − None
ansible−galaxy [delete|import|info|init|install|list|login|remove|search|setup] [−−help] [options] ...
command to manage Ansible roles in shared repostories, the default of which is Ansible Galaxy.
−−list
List all of your integrations.
−−remove REMOVE_ID
Remove the integration matching the provided ID value. Use −−list to see ID values.
−−version
show program’s version number and exit
−c, −−ignore−certs
Ignore SSL certificate validation errors.
−h, −−help
show this help message and exit
−s API_SERVER, −−server API_SERVER
The API server destination
−v, −−verbose
verbose mode (−vvv for more, −vvvv to enable connection debugging)
info
prints out detailed information about an installed role as well as info available from the galaxy API.
−−offline
Don’t query the galaxy API when creating roles
−p, −−roles−path
The path to the directory containing your roles. The default is the roles_path configured in your ansible.cfgfile (/etc/ansible/roles if not configured)
search
searches for roles on the Ansible Galaxy server
−−author AUTHOR
GitHub username
−−galaxy−tags GALAXY_TAGS
list of galaxy tags to filter by
−−platforms PLATFORMS
list of OS platforms to filter by
setup
Setup an integration from Github or Travis for Ansible Galaxy roles
list
lists the roles installed on the local system or matches a single role passed as an argument.
remove
removes the list of roles passed as arguments from the local system.
init
creates the skeleton framework of a role that complies with the galaxy metadata format.
−f, −−force
Force overwriting an existing role
−−container−enabled
Initialize the skeleton role with default contents for a Container Enabled role.
−−init−path INIT_PATH
The path in which the skeleton role will be created. The default is the current working directory.
−−role−skeleton ROLE_SKELETON
The path to a role skeleton that the new role should be based upon.
install
uses the args list of roles to be installed, unless −f was specified. The list of roles can be a name (which will be downloaded via the galaxy API and github), or it can be a local .tar.gz file.
−n, −−no−deps
Don’t download roles listed as dependencies
−i, −−ignore−errors
Ignore errors and continue with the next specified role.
−r ROLE_FILE, −−role−file ROLE_FILE
A file containing a list of roles to be imported
import
used to import a role into Ansible Galaxy
−−status
Check the status of the most recent import request for given github_user/github_repo.
−−no−wait
Don’t wait for import results.
−−branch REFERENCE
The name of a branch to import. Defaults to the repository’s default branch (usually master)
−−role−name ROLE_NAME
The name the role should have, if different than the repo name
verify user’s identify via Github and retrieve an auth token from Ansible Galaxy.
−−github−token TOKEN
Identify with github token rather than username and password.
delete
Delete a role from Ansible Galaxy.
The following environment variables may be specified.
ANSIBLE_CONFIG — Override the default ansible config file
Many more are available for most options in ansible.cfg
/etc/ansible/ansible.cfg — Config file, used if present
~/.ansible.cfg — User config file, overrides the default config if present
Ansible was originally written by Michael DeHaan. See the AUTHORS file for a complete list of contributors.
Copyright © 2017 Red Hat, Inc | Ansible. Ansible is released under the terms of the GPLv3 License.
ansible(1), ansible−config(1), ansible−console(1), ansible−doc(1), ansible−inventory(1), ansible−playbook(1), ansible−pull(1), ansible−vault(1)
Extensive documentation is available in the documentation site:. IRC and mailing list info can be found in file CONTRIBUTING.md, available in: | http://man.sourcentral.org/MGA6/1+ansible-galaxy | CC-MAIN-2018-47 | en | refinedweb |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
Hi,
I have written a code for Merge Script in Bitbucket. Its working in Admin but in Admin to repository it showing the following error.
[Static type checking] - You tried to call a method which is not allowed: groovy.json.JsonSlurper#() @ line 18, column 20. def JSON_slurper = new groovy.json.JsonSlurper().
These are the import packages i have used for JSON.
import groovy.json.JsonOutput
import groovyx.net.http.HttpResponseException
import groovy.json.JsonSlurper
Thanks,
please stop forwarding me questions just because you've asked them, it's really annoying and I ignore. | https://community.atlassian.com/t5/Bitbucket-questions/Bitbucket-Merge-script-working-in-Gobal-Admin-but-not-in-Admin/qaq-p/93886 | CC-MAIN-2018-47 | en | refinedweb |
Chapter 5. Conditional CAPM. 5.1 Conditional CAPM: Theory Risk According to the CAPM. The CAPM is not a perfect model of expected returns.
- Claude Hopkins
- 2 years ago
- Views:
Transcription
1 Chapter 5 Conditional CAPM 5.1 Conditional CAPM: Theory Risk According to the CAPM The CAPM is not a perfect model of expected returns. In the 40+ years of its history, many systematic deviations from it have been documented. (We will talk more about those deviations, or anomalies, later in the course). However, the CAPM made the point that still remains the central concept in modern finance theory: risk is not return variance. Rather, risk is the covariance of returns with an economy-wide source of volatility (namely, the market). Indeed, the variance created by the independent realizations of random outcomes can always be eliminated through diversification. For example, playing heads-andtails once and betting $100 on heads is a very risky thing to do. But playing headsand-tails times betting 1 cent is not risky at all, because the number of bets you win and lose will be approximately equal, and on average, according to the Law of Large Numbers, you will break even almost surely. The CAPM points out that not all risks in the economy can be handled this way. 78
2 5.1. CONDITIONAL CAPM: THEORY 79 Surely, the risk that the company will lose its visionary leader is huge if you hold one stock only, but the same risk is small if you hold hundreds of stocks in your portfolio. However, the risk of economy sliding into another recession will impact all stocks in any portfolio. No matter how diversified the portfolio is, it will be hit by the economy-wide shock. The question is only how much it will be hit. The CAPM says that risk is exactly this how much they will be hit, and only this type of risk is compensated in the market. The stock that does not react much to ups and downs in the economy has low risk (low beta) and will offer low expected return. Risk according to the CAPM: Any asset that appreciates when the market goes up and loses value when the market goes down, is risky and has to earn more than the risk-free rate. Risk is when the value drops when market goes down. The predictability of market returns provides important information that the amount of risk and the investors reluctance to bear it both change over time. In recessions, investors are very risk-averse and require a high return for bearing risk. In expansions, they are willing to take bigger risks for smaller return. It is therefore natural that the investors would wish to limit their risk exposure during recessions and increase the risk exposure during booms. However, the CAPM is a one-period model, in which such preferences cannot exist. This could be one of the reasons the CAPM fails to explain many regularities in returns Risk According to the Conditional CAPM Here is an example of how the Conditional CAPM works. Assume that recessions are three times shorter than expansions, that is, the economy spends 25% of time in a recession and 75% of time in an expansion. Assume also that the expected market risk
3 80 CHAPTER 5. CONDITIONAL CAPM premium is 4% during expansions and 12% during recessions. The average market risk premium is then % + 3 4% = 6%, just as we observe in the data. 4 Consider two stocks. One stock has the beta of 2 in recession and the beta of 2 3 in expansion. The other has the beta of 1 2 in recession and the beta of 7 in expansion. 6 The CAPM will see only the average beta of each stock: = 1 for the first 4 one and = 1 for the second one. Hence, the CAPM will predict that the 4 excess return to both stocks will be, on average, 6%. Stock A: Countercyclical Beta Stock B: Countercyclical Beta Market risk Stock Stock risk Market risk Stock Stock risk premium beta premium premium beta premium Recession (p=1/4) 12% 2 24% 12% 1/2 6% Expansion (p=3/4) 4% 2/3 8/3% 4% 7/6 14/3% Average 6% 1 8% 6% 1 5% Static CAPM 6% 1 6% 6% 1 6% However, in reality the first stock is expected to earn 2 12% = 24% in recessions and 2 3 4% = 8 % in expansions, which makes its expected excess return % % 1 4 = 8% on average. The second stock is expected to earn 1 12% = 6% 2 during recessions and % = % during expansions, which makes its expected excess return 14 3 % % 1 = 5% on average The first stock is the one that exhibits the undesirable behavior: its risk exposure (aka market beta) increases in recessions, when bearing risk is especially painful, and decreases in expansions, when investors do not mind bearing more risk. Hence, the first stock is riskier than what the CAPM would lead us to think and earns higher return, which cannot be explained by the CAPM. The CAPM would estimate that the first stock has an abnormal return (aka the alpha) of 2% per year, suggesting this is a good investment. The Conditional CAPM retorts that the extra reward comes to
4 5.1. CONDITIONAL CAPM: THEORY 81 the owners of the first stock in return for bearing the extra risk of undesirable beta changes, and the first stock is in fact as good investment as anything else. The second stock, to the contrary, exhibits the desirable behavior by lowering the beta when risks are high and raising the beta when risks are low. Thus, the second stock is less risky than what the CAPM says, and earns a lower return. The CAPM would attribute the negative alpha of -1% per year to the second stock, suggesting that it is a poor investment choice, but the Conditional CAPM shows that the second stock is a reasonable conservative investment. Risk according to the Conditional CAPM: In addition to the market risk as described by the CAPM, the countercyclicality of the market beta (i.e., higher beta in recessions) is another source of risk. Risk is when the risk exposure increases in bad times How Important is the Risk Captured by the Conditional CAPM In this subsection, we will try to estimate the amount of additional risk created by the changing beta. That is, we will try to answer the question: is it likely that the difference in the expected return as estimated by the CAPM and the Conditional CAPM substantial? To do that, we need to look at what went wrong with the static CAPM from the statistical standpoint. Let s recall the definition of covariance: Cov(X, Y ) E[(X E(X)) (Y E(Y ))] (5.1) That is, covariance is the expected value of the product between the two deviations from the average. Now, let s use the fact that expectation is linear, that is, the expected sum is the sum of expectations (E(X + Y ) = E(X) + E(Y )) and E(aX) = a E(X). E(X) and
5 82 CHAPTER 5. CONDITIONAL CAPM E(Y ) in (5.1) above are numbers, not random variables, therefore E[(X E(X)) (Y E(Y ))] = E[X Y E(X) Y E(Y ) X + E(X) E(Y )] = = E(X Y ) E(E(X) Y ) E(E(Y ) X) + E(E(X) E(Y )) = = E(X Y ) E(X) E(Y ) E(Y ) E(X) + E(X) E(Y ) = E(X Y ) E(X) E(Y ) I conclude that the definition of the covariance implies Cov(X, Y ) = E(X Y ) E(X) E(Y ) (5.2) E(X Y ) = Cov(X, Y ) + E(X) E(Y ) (5.3) Assume now that both the beta and the market risk premium are random variables. What we are interested in is the risk premium of the stock, E(β S R M ) = E(β S ) E(R M ) + Cov(β S, R M ) (5.4) That is, we are interested in the average product of the stock beta and the market risk premium in all states of the world. The static CAPM does not distinguish between the states of the world and assumes that if we see any variation in the stock beta and the market risk premium, this variation is pure noise. Therefore, the static CAPM suggests that we compute the product of the average beta and the average market risk premium. In reality, however, the variation in the stock beta and the market risk premium is not purely random. It is correlated, and the covariance term measures the bias in the estimate of the expected risk premium of the stock provided by the static CAPM. That is, if the covariance is positive (i.e, in most states of the world the stock beta and the market risk premium are either both high or both low, see Stock A from the numerical example above), then the static CAPM will underestimate the risk and the
6 5.1. CONDITIONAL CAPM: THEORY 83 expected risk premium of the stock. Conversely, if the correlation is negative (i.e., in most states of the world either the stock beta is high and the market risk premium is low, or vice versa), the static CAPM will overestimate the risk and the expected risk premium of the stock. The covariance term in (5.4) does much more than express the simple example in the previous subsection in the complex mathematical symbols. In fact, it gives the estimate of the bias in the static CAPM compared to the Conditional CAPM, that is, exactly what we are looking for in this section. We can now do some comparative statics, i.e., look at what the bias depends on. By definition again, the covariance is the product of the correlation and the two standard deviations, Cov(β S, R M ) Corr(β S, R M ) σ(β S ) σ(r M ) (5.5) We draw two important conclusions from (5.5). First, the bias in the static CAPM and, therefore, the usefulness of the Conditional CAPM increases in the correlation between the stock beta, β S, and the market risk premium, R M. If they are tightly related (for example, driven by the same variables like the four variables in Chapter 4, Section 1), the bias is large and the Conditional CAPM is important. If they vary pretty much independently of each other, there is little difference between the Conditional CAPM and the static CAPM. Once again: time variation in the market risk premium and the stock beta is a necessary, but insufficient condition for the Conditional CAPM usefulness. The Conditional CAPM is only useful if those two move together, not just move. Second, the usefulness of the Conditional CAPM increases in the variation in both the market risk premium and the stock beta. If both of them vary by a lot, the
7 84 CHAPTER 5. CONDITIONAL CAPM difference between the static CAPM and the Conditional CAPM is large, and using the correct model (the Conditional CAPM) is important. But do the market risk premium and the stocks betas vary enough to make the Conditional CAPM significantly different in its predictions from the static CAPM? Let s turn one last time to the numerical example from the previous section. Even if the risk premium in recession and in expansion is very different (in our example it triples from 4% to 12%, about what we figured out it would do - see Chapter 4, Section 1) and the betas vary by a lot (the beta differential between the first and second stocks changes from 1.5 in recession to -0.5 in expansion, which is unbelievably large compared to what we see in the data), the return differential is only 3%, way smaller than the most important deviations from the CAPM we will consider later in the course. This is called the Lewellen-Nagel (JFE 2006) critique: the variations in betas and the expected market risk premium are too small to make the Conditional CAPM successful in explaining the return differentials between different groups of stocks we observe in the real-life data. 5.2 Conditional CAPM in the Data First Look at the Value Effect Petkova and Zhang (JFE 2005) use the Conditional CAPM in the effort to explain one of the most important and stubborn anomalies in finance - the value effect. The simple CAPM cannot explain why value firms (mature companies with low market-to-book) earn on average higher returns than growth firms (young fast-growing companies with high market-to-book). Market-to-book is the ratio of the firm s market capitalization to its book value
8 5.2. CONDITIONAL CAPM IN THE DATA 85 of equity. Market-to-book higher than 1 signals the existence of growth potential, market-to-book lower than 1 is the sign of poor prospects. High market-to-book ratios are characteristic of risky high tech firms, for which a high proportion of the value is their future that has not yet found its way to the books. Low market-to-book firms are generally mature companies with few expansion opportunities, but steady cash flows and high dividends. Hence, it is pretty surprising that value firms beat growth firms, since most people would say that growth firms are riskier. The following regression illustrates the value effect: HML t = 0.58 (0.12) 0.27 (0.03) (MKT t RF t ) (5.6) The variable on the left-hand side is the zero-investment portfolio that sells growth firms and uses the proceeds to buy value firms 1. It is regressed on the excess return to the market portfolio (value-weighted CRSP index is used as a proxy). According to the CAPM, the intercept of the regression (aka the alpha), which measures abnormal return, should be zero. It is important to understand why the CAPM predicts that the alpha in (5.6) should be zero. It will allow us to understand why the alpha is the measure of abnormal returns and enable us to use it to measure the deviations from the CAPM (anomalies) and the performance of actively managed portfolios (e.g., mutual funds). 1 Data footnote: The sample period in the regression is from August 1963 to December The HML portfolio is one of the Fama-French factors we will discuss later. To form it, we sort all firms into three market-to-book groups (top 30%, middle 40%, bottom 30%) and two size groups (below median and above median). Then in each size group we buy value firms (bottom 30% on market-to-book) and sell growth firms (top 30% on market-to-book). The returns to the two value minus growth portfolios are value-weighted. The HML return is the simple average of the returns to the two value minus growth portfolios (value minus growth for small firms and value minus growth for large firms). The portfolio is called HML as an acronym for high minus low, because Fama and French in their paper sorted firms on book-to-market, not market-to-book, and value firms have high book-to-market.
9 86 CHAPTER 5. CONDITIONAL CAPM The CAPM implies that for each asset (a stock, a bond, an option) E(R t ) = RF t + β (E(MKT t ) RF t ) E(R t ) RF t = β (E(MKT t ) RF t ) (5.7) The rearranging of the terms on the right implies that the asset s risk premium is exactly proportional to the market risk premium, and the beta is the coefficient of proportionality. Therefore, the CAPM predicts that in the regression of excess returns to any asset on the excess return to the market the intercept (the alpha) is zero. If the alpha is not zero, the CAPM is violated. The positive alpha implies that the asset earns the return above what is a fair compensation for risk β (E(MKT t ) RF t ), and vice versa. Also, pay attention to the fact that the regression prescribed by the CAPM has excess returns both on the left and on the right. Why is (5.6) different? It is different because we are looking at the zero-investment portfolio that shorts growth firms and uses the proceeds to finance the purchases of value firms. 2 Essentially, we are looking at the difference in the (excess) returns between value firms and growth firms. You can interpret (5.6) as two regressions E(H t ) RF t = β H (E(MKT t ) RF t ) (5.8) E(L t ) RF t = β L (E(MKT t ) RF t ) (5.9) Now deduct (5.9) from (5.8), and you will get (5.6) - the risk-free rate cancels in the process, and thus does not appear in (5.6). Now, let s go back to the alpha, our measure of abnormal return and the CAPM validity. In regression (5.6), the alpha far exceeds zero: it is 0.59% (59 bp) per month 2 By law, you have to leave the proceeds from the short sale with the lender, and the lender will pay you close to the risk-free rate on those. That is, when you short (e.g., growth stocks), the government makes you go long in the Treasury bill. To complete the zero-investment strategy (HML) in real life, you have to do an extra deal: borrow at the risk-free rate or close and buy the long part (value stocks). Then you will be long in value stocks, short in Treasuries, short in growth stocks, and long in Treasuries, all for the same sum of money. The Treasuries positions cancel out, and you hold the HML portfolio with no cash invested.
10 5.2. CONDITIONAL CAPM IN THE DATA 87 and highly significant (0.58/0.12 = ). This is the value effect: even though value firms have lower beta than growth firms (by in the regression), they earn higher return. The return differential between value and growth beats the CAPM prediction by 7% (0.59% 12) per year. (We will talk more about the value effect and the HML portfolio when we get to the Fama-French model and anomalies) Empirical Setup Petkova and Zhang allow the beta to change over time by making it a linear function of the four macroeconomic variables we discussed when we talked about long-run return predictability - the default premium (DEF ), the dividend yield (DIV ), the Treasury bill rate (T B), and the term premium (T ERM). That is, Petkova and Zhang assume that β t = γ 0 + γ 1 DEF t 1 + γ 2 DIV t 1 + γ 3 T B t 1 + γ 4 T ERM t 1 (5.10) and MKT t RF t = λ 0 + λ 1 DEF t 1 + λ 2 DIV t 1 + λ 3 T B t 1 + λ 4 T ERM t 1 (5.11) Notice that Petkova and Zhang assume that the beta of HML depends on the same four variables which we found to be the predictors of the market risk premium in Chapter 4, Section 1. This is not a coincidence: as discussed in Section 1.3 of this chapter, the extra explanatory power of the Conditional CAPM compared to the static CAPM is proportional to the correlation between the asset s beta and the market risk premium (see equation (5.4)). Petkova and Zhang are trying to capture as much of this correlation as possible. Empirical Advice: When you estimate Conditional CAPM, assume that the beta depends only on the macroeconomic variables that predict the market risk premium. Putting the variables that do not in (5.10) gets you no extra mileage.
11 88 CHAPTER 5. CONDITIONAL CAPM The Conditional CAPM Petkova and Zhang estimate requires running the regression HML t = α + β t (MKT t RF t ) (5.12) If the intercept α is insignificantly different from zero, then the Conditional CAPM is capable of explaining the value effect. Given their specification of β t, Petkova and Zhang estimate the following regression: HML t = α+(γ 0 +γ 1 DEF t 1 +γ 2 DIV t 1 +γ 3 T B t 1 +γ 4 T ERM t 1 ) (MKT t RF t ) or, after rearranging, (5.13) HML t = α + γ 0 (MKT t RF t ) + γ 1 DEF t 1 (MKT t RF t ) +γ 2 DIV t 1 (MKT t RF t ) + γ 3 T B t 1 (MKT t RF t ) (5.14) +γ 4 T ERM t 1 (MKT t RF t ) which means regressing the HML return not only on the excess market return, as in the simple CAPM, but also on the products of the excess market return with the macro variables. When Petkova and Zhang estimate (5.15), they get, with rearranging back to the form of (5.13), the following result that we discuss in the next subsection: HML t = ( 0.36 (0.115) (0.09) (0.08) 0.11 DEF t (0.03) DIV t (0.02) T B t (0.03) T ERM t 1) (MKT t RF t ) (5.15)
12 5.2. CONDITIONAL CAPM IN THE DATA Interpreting the Results What do we conclude from the regression above? First, the good news: the macro variables we use predict the market beta of the value minus growth strategy in a reasonable way. If the Conditional CAPM is to explain the value effect, the market beta of the value minus growth strategy has to increase during recessions. In recessions, the dividend yield, the default premium, and the term premium are high, so they should be positively related to the market beta of HML and have positive coefficients in the regression estimated above. The default premium and the term premium, as we see in (5.15), have negative, but insignificant coefficients. In regression (5.15), the only significant coefficient out of the three is the coefficient on the dividend yield, and it has the correct positive sign. Its magnitude suggests that if the dividend yield increases by 1%, the market beta of the value minus growth strategy increases by 0.2. Given that the dividend yield changes by up to 2% from peak to trough, the impact of dividend yield on the beta seems economically sizeable. Also, the Treasury bill rate (the measure of expected inflation) is low during recessions, hence it should be negatively related with the market beta of HML, if the market beta is to increase in recessions. In (5.15), the coefficient on the Treasury bill rate is significantly different from zero and economically large. It implies that the decrease in the Treasury bill rate by 1% per year triggers, on average, the increase in the market beta differential between value and growth by Given that the Treasury bill rate can vary easily by 3% to 5% within one business cycle, the coefficient in (5.15) suggests that the impact of expected inflation can cause the beta differential between value firms and growth firms change by up to Now the bad news: the alpha is still highly significant (0.45/0.115 = 3.9 2),
13 90 CHAPTER 5. CONDITIONAL CAPM meaning that the Conditional CAPM cannot handle the value effect. Compared to (5.6), where we estimate the ordinary CAPM, the alpha decreases by only 13 bp per month (1.6% per year). This is consistent with the Lewellen-Nagel critique - it seems that, despite the seemingly strong dependence of the beta on the macro variables in (5.15), the variation of the beta and the expected risk premium are not enough to make a big impact. To show that the variation in the beta is not large enough, I perform the following experiment: first, I use (5.11) to estimate expected market risk premium and partition the sample into the months with the expected market risk premium (predicted values from (5.11)) in the top 25% (recession) and the months with the expected market risk premium in the bottom 25% (boom). I use (5.10) with coefficients from (5.15) to form the series of the market beta of the value minus growth strategy and average the beta in the recession months and the boom months (as defined above). I find that during recessions the market beta of the HML is , and during booms it is -0.41, consistent with the estimates in (5.15) Conditional CAPM Works, but Not by Enough The results in the previous paragraph bring us to two conclusions. First, while it is true that following the value minus growth strategy is riskier in recessions than in booms, growth is always riskier than value, and therefore growth stocks should have higher average returns (whereas in the data they earn by 46 bp per month less than value firms). Hence, there is no way the Conditional CAPM can explain the value effect. Second, the variation in the market betas is indeed too small. We should not add up the coefficients in (5.15) and conclude that if both expected inflation and dividend
14 5.2. CONDITIONAL CAPM IN THE DATA 91 yield can move the market beta of HML by 0.4, it will change by 0.8 from recession to expansion. In many instances, the macro variables pull in different directions - e.g., in the 70s both the dividend yield and the Treasury bill rate were high. We can even perform a back-of-envelope calculation based on the beta differential computed in the end of the last subsection. Recessions and booms in the definition of this paragraph take 50% of the sample, the expected risk premium varies between recessions and booms by 1% per month at most (see our exercises in the long-run predictability sections or just obtain the expected risk premium from (5.11) and average it in recessions and booms). Hence, if we are to explain the value effect of about 0.6% per month, the difference in the market beta of the HML portfolio between recessions and booms should be 1.2 (0.5 1% 1.2 = 0.6%). The beta differential of we observe in the data gives us the chance to explain at most 15 bp of the value effect, close to the change in the alphas we observe as we go from (5.6) to (5.15). What have we learned about the Conditional CAPM? Good news: the Conditional CAPM shows that following the value minus growth strategy is relatively more risky during recessions, which is an important observation. We can perform the same sort of estimation for any asset we consider (e.g., a mutual fund offered in 401(k)), and it will give us a heads-up on the potential risks we may face. Bad news: according to the Conditional CAPM, risk and risk exposure do not change by enough to make an economically large impact. In particular, the slopes in (5.15) are sizeable, but the model as a whole does not work well. Hence, if we need a precise quantitative answer about whether the risk discovered by the Conditional CAPM is fairly compensated by the observed return, we may want to try something else, which will be the point of the next sections.
Models of Risk and Return
Models of Risk and Return Aswath Damodaran Aswath Damodaran 1 First Principles Invest in projects that yield a return greater than the minimum acceptable hurdle rate. The hurdle rate should be higher for
Review for Exam 2. Instructions: Please read carefully
Review for Exam Instructions: Please read carefully The exam will have 1 multiple choice questions and 5 work problems. Questions in the multiple choice section will be either concept or calculation questions.
Chapter 11, Risk and Return
Chapter 11, Risk and Return 1. A portfolio is. A) a group of assets, such as stocks and bonds, held as a collective unit by an investor B) the expected return on a risky asset C) the expected return on
Market Efficiency and Behavioral Finance. Chapter 12
Market Efficiency and Behavioral Finance Chapter 12 Market Efficiency if stock prices reflect firm performance, should we be able to predict them? if prices were to be predictable, that would create the
CHAPTER 11: ARBITRAGE PRICING THEORY
CHAPTER 11: ARBITRAGE PRICING THEORY 1. The revised estimate of the expected rate of return on the stock would be the old estimate plus the sum of the products of the unexpected change in each factor times
Module 7 Asset pricing models
1. Overview Module 7 Asset pricing models Prepared by Pamela Peterson Drake, Ph.D., CFA Asset pricing models are different ways of interpreting how investors value investments. Most models are based on
Chapter 10. Chapter 10 Topics. Recent Rates
Chapter 10 Introduction to Risk, Return, and the Opportunity Cost of Capital Chapter 10 Topics Rates of Return Risk Premiums Expected Return Portfolio Return and Risk Risk Diversification Unique & Market
Equity Risk Premiums: Looking backwards and forwards
Equity Risk Premiums: Looking backwards and forwards Aswath Damodaran Aswath Damodaran 1 What is the Equity Risk Premium? Intuitively, the equity risk premium measures what investors demand over and above
1. Portfolio Returns and Portfolio Risk
Chapter 8 Risk and Return: Capital Market Theory Chapter 8 Contents Learning Objectives 1. Portfolio Returns and Portfolio Risk 1. Calculate the expected rate of return and volatility for a portfolio
Portfolio Performance Measures
Portfolio Performance Measures Objective: Evaluation of active portfolio management. A performance measure is useful, for example, in ranking the performance of mutual funds. Active portfolio managers
Capital Market Equilibrium and the Capital Asset Pricing Model
Capital Market Equilibrium and the Capital Asset Pricing Model Econ 422 Investment, Capital & Finance Spring 21 June 1, 21 1 The Risk of Individual Assets Investors require compensation for bearing risk.
Trading Strategies and Financial Models. Alexander Barinov
Trading Strategies and Financial Models Alexander Barinov This version: July 2014 c 2014 Alexander Barinov Contents 1 Topics in Market Efficiency 17 1.1 EMH and Expected Returns.......................
Optimal Debt-to-Equity Ratios and Stock Returns
Utah State University DigitalCommons@USU All Graduate Plan B and other Reports Graduate Studies 3-2014 Optimal Debt-to-Equity Ratios and Stock Returns Courtney D. Winn Utah State University Follow this
Chapter 7 Portfolio Theory and Other Asset Pricing Models
Chapter 7 Portfolio Theory and Other sset Pricing Models NSWERS TO END-OF-CHPTER QUESTIONS 7-1 a. portfolio is made up of a group of individual assets held in combination. n asset that would be relatively
The Risk Return Trade off
Risk and Return The Risk Return Trade off All else equal, people. All else equal, people. Calculating Percent and Dollar Returns On, Home Depot stock closed at $. It paid dividends of. It is currently
CAPM, Arbitrage, and Linear Factor Models
CAPM, Arbitrage, and Linear Factor Models CAPM, Arbitrage, Linear Factor Models 1/ 41 Introduction We now assume all investors actually choose mean-variance e cient portfolios. By equating these investors
Chapter 6 The Tradeoff Between Risk and Return
Chapter 6 The Tradeoff Between Risk and Return MULTIPLE CHOICE 1. Which of the following is an example of systematic risk? a. IBM posts lower than expected earnings. b. Intel announces record earnings.
Key Concepts and Skills
Chapter 10 Some Lessons from Capital Market History Key Concepts and Skills Know how to calculate the return on an investment Understand the historical returns on various types of investments Understand
The CAPM & Multifactor Models
The CAPM & Multifactor Models Business Finance 722 Investment Management Professor Karl B. Diether The Ohio State University Fisher College of Business Review and Clarification In the last few lectures
Econ 422 Summer 2006 Final Exam Solutions
Econ 422 Summer 2006 Final Exam Solutions This is a closed book exam. However, you are allowed one page of notes (double-sided). Answer all questions. For the numerical problems, if you make a computational.
CHAPTER 7: OPTIMAL RISKY PORTFOLIOS
CHAPTER 7: OPTIMAL RIKY PORTFOLIO PROLEM ET 1. (a) and (e).. (a) and (c). After real estate is added to the portfolio, there are four asset classes in the portfolio: stocks, bonds, cash and real estate..
7. Bonds and Interest rates
7. Bonds and Interest rates 1 2 Yields and rates I m thinking of buying a bond that has a face value of $1000, pays semiannual coupons of $40 and has 7 years to maturity. The market price is $943. Fixed
Despite more than half a century of research on forecasting stock market returns,
Rosenberg Institute of Global Finance GLOBAL FINANCE BRIEF To predict the equity market, consult economic theory Davide Pettenuzzo, Assistant Professor of Economics March 2014 Despite more than half a
CAPITAL STRUCTURE AND DIVIDEND POLICY
CAPITAL STRUCTURE AND DIVIDEND POLICY Capital Structure In the section of the notes titled Cost of Capital, we examined how the cost of capital is determined. From those notes, you should have discovered
Mean-Variance Portfolio Analysis and the Capital Asset Pricing Model
Mean-Variance Portfolio Analysis and the Capital Asset Pricing Model 1 Introduction In this handout we develop a model that can be used to determine how a risk-averse investor can choose an optimal asset
Capital Asset Pricing Model Homework Problems
Capital Asset Pricing Model Homework Problems Portfolio weights and expected return 1. Consider a portfolio of 300 shares of firm A worth $10/share and 50 shares of firm B worth $40/share. You expect a
DESCRIPTION OF FINANCIAL INSTRUMENTS AND INVESTMENT RISKS
DESCRIPTION OF FINANCIAL INSTRUMENTS AND INVESTMENT RISKS A. General The services offered by Prochoice Stockbrokers cover a wide range of Financial Instruments. Every type of financial instrument carries
CHAPTER 11: THE EFFICIENT MARKET HYPOTHESIS
CHAPTER 11: THE EFFICIENT MARKET HYPOTHESIS PROBLEM SETS 1. The correlation coefficient between stock returns for two non-overlapping periods should be zero. If not, one could use returns from one period
Instructor s Manual Chapter 12 Page 144
Chapter 12 1. Suppose that your 58-year-old father works for the Ruffy Stuffed Toy Company and has contributed regularly to his company-matched savings plan for the past 15 years. Ruffy contributes $0
RISKS IN MUTUAL FUND INVESTMENTS
RISKS IN MUTUAL FUND INVESTMENTS Classification of Investors Investors can be classified based on their Risk Tolerance Levels : Low Risk Tolerance Moderate Risk Tolerance High Risk Tolerance Fund Classification
FIN 432 Investment Analysis and Management Review Notes for Midterm Exam
FIN 432 Investment Analysis and Management Review Notes for Midterm Exam Chapter 1 1. Investment vs. investments 2. Real assets vs. financial assets 3. Investment process Investment policy, asset allocation,
Lecture 2: Equilibrium
Lecture 2: Equilibrium Investments FIN460-Papanikolaou Equilibrium 1/ 33 Overview 1. Introduction 2. Assumptions 3. The Market Portfolio 4. The Capital Market Line 5. The Security Market Line 6. Conclusions
Midterm Exam:Answer Sheet
Econ 497 Barry W. Ickes Spring 2007 Midterm Exam:Answer Sheet 1. (25%) Consider a portfolio, c, comprised of a risk-free and risky asset, with returns given by r f and E(r p ), respectively. Let y be the
YieldCo Cost of Capital
by Josh Lutton and Shirley You Large renewable energy project developers often use a type of financing vehicle colloquially known as a YieldCo to finance portfolios of assets that are expected to have
Disentangling value, growth, and the equity risk premium
Disentangling value, growth, and the equity risk premium The discounted cash flow (DCF) model is a theoretically sound method to value stocks. However, any model is only as good as the inputs and, as JASON
Tilted Portfolios, Hedge Funds, and Portable Alpha
MAY 2006 Tilted Portfolios, Hedge Funds, and Portable Alpha EUGENE F. FAMA AND KENNETH R. FRENCH Many of Dimensional Fund Advisors clients tilt their portfolios toward small and value stocks. Relative
1 Capital Asset Pricing Model (CAPM)
Copyright c 2005 by Karl Sigman 1 Capital Asset Pricing Model (CAPM) We now assume an idealized framework for an open market place, where all the risky assets refer to (say) all the tradeable stocks available
Distinction Between Interest Rates and Returns
Distinction Between Interest Rates and Returns Rate of Return RET = C + P t+1 P t =i c + g P t C where: i c = = current yield P t g = P t+1 P t P t = capital gain Key Facts about Relationship Between Interest
Financial Evolution and Stability The Case of Hedge Funds
Financial Evolution and Stability The Case of Hedge Funds KENT JANÉR MD of Nektar Asset Management, a market-neutral hedge fund that works with a large element of macroeconomic assessment. Hedge funds
Chapter 10 Capital Markets and the Pricing of Risk
Chapter 10 Capital Markets and the Pricing of Risk 10-1. The figure below shows the one-year return distribution for RCS stock. Calculate a. The expected return. b. The standard deviation of the return.
Learn about bond investing Investor education The dual roles bonds can play in your portfolio Bonds can play an important role in a welldiversified investment portfolio, helping to offset the volatility
CHAPTER 13: EMPIRICAL EVIDENCE ON SECURITY RETURNS
CHAPTER 13: EMPIRICAL EVIDENCE ON SECURITY RETURNS Note: For end-of-chapter-problems in Chapter 13, the focus is on the estimation procedure. To keep the exercise feasible the sample was limited to returns
Using Duration Times Spread to Forecast Credit Risk
Using Duration Times Spread to Forecast Credit Risk European Bond Commission / VBA Patrick Houweling, PhD Head of Quantitative Credits Research Robeco Asset Management Quantitative Strategies Forecasting
Interpreting Market Responses to Economic Data
Interpreting Market Responses to Economic Data Patrick D Arcy and Emily Poole* This article discusses how bond, equity and foreign exchange markets have responded to the surprise component of Australian Uncertainty and Consumer Behavior
Chapter 5 Uncertainty and Consumer Behavior Questions for Review 1. What does it mean to say that a person is risk averse? Why are some people likely to be risk averse while others are risk lovers? A risk-averse
Wel Dlp Portfolio And Risk Management
1. In case of perfect diversification, the systematic risk is nil. Wel Dlp Portfolio And Risk Management 2. The objectives of investors while putting money in various avenues are:- (a) Safety (b) Capital
Regression Analysis. Pekka Tolonen
Regression Analysis Pekka Tolonen Outline of Topics Simple linear regression: the form and estimation Hypothesis testing and statistical significance Empirical application: the capital asset pricing model
I. Estimating Discount Rates
I. Estimating Discount Rates DCF Valuation Aswath Damodaran 1 Estimating Inputs: Discount Rates Critical ingredient in discounted cashflow valuation. Errors in estimating the discount rate or mismatching 5. Risk and Return. Copyright 2009 Pearson Prentice Hall. All rights reserved.
Chapter 5 Risk and Return Learning Goals 1. Understand the meaning and fundamentals of risk, return, and risk aversion. 2. Describe procedures for assessing and measuring the risk of a single asset. 3.
Analyzing the Effect of Change in Money Supply on Stock Prices
72 Analyzing the Effect of Change in Money Supply on Stock Prices I. Introduction Billions of dollars worth of shares are traded in the stock market on a daily basis. Many people depend on the stock market
FRBSF ECONOMIC LETTER
FRBSF ECONOMIC LETTER 213-23 August 19, 213 The Price of Stock and Bond Risk in Recoveries BY SIMON KWAN Investor aversion to risk varies over the course of the economic cycle. In the current recovery,
Practice Set #4 and Solutions.
FIN-469 Investments Analysis Professor Michel A. Robe Practice Set #4 and Solutions. What to do with this practice set? To help students prepare for the assignment and the exams, practice sets with solutions
U.S. SMALL CAP EQUITY: WHICH BENCHMARK IS BEST?
EXECUTIVE SUMMARY We find persistent performance disparities when comparing three leading benchmarks for U.S. small cap equity, with the MSCI U.S. Small Cap 1750 and the S&P Small Cap 600 outperforming | http://docplayer.net/20428190-Chapter-5-conditional-capm-5-1-conditional-capm-theory-5-1-1-risk-according-to-the-capm-the-capm-is-not-a-perfect-model-of-expected-returns.html | CC-MAIN-2018-47 | en | refinedweb |
Being Green With Your Raspberry Pi and Python
Being green is never easy, but perhaps a Raspberry Pi can help us cut down on our carbon emissions and save the polar bears.
Why do this?
- This is a great cross-curricular exercise for schools
- Learn Python
- Learn to use the Energenie wireless socket controller
- Learn a little Minecraft hacking
- Build a GUI in Python
- Learn to work with sensors in Python
Tools required:
- A Raspberry Pi Model Pi 2 or B+
- An Energenie
- For project 1 – A mobile phone charger
- For project 2 and 3 a lamp
- For project 3 a breadboard, 2 female to male jumper leads and 1 momentary switch
- Python 2 installed on your machine
Electricity is something that we take for granted: we just turn it on and off, and only really think about how much we’re using when the bill arrives. In this tutorial we will use a device called Energenie to wirelessly connect our Raspberry Pi to a wall socket and control devices attached to it. We will conduct three projects to interface with the Energenie.
- Project 1 Mobile phone charging station
- Project 2 Minecraft user interface
- Project 3 Remote control switch
Each of the projects can be completed in a one-hour computing lesson with time for class to explore possibilities of expanding the projects to meet their needs in the curriculum. These projects can be enhanced with cross-curricular activities.
Project 1 – mobile phone charging station
The Energenie is a brilliant gadget, available for £20 from.
Typically we leave our phone on charge overnight, but that really isn’t an energy-efficient solution. In this project we’ll use the Energenie power outlet and matching Raspberry Pi add-on to create a timed charging station. We will use a graphical user interface (GUI) using the EasyGUI library. Connect your Raspberry Pi as normal and gently insert the Energenie add-on onto the GPIO (General Purpose Input Output). It will fit over the first 26 pins from the SD card and it will overlap with the Raspberry Pi. With the board fitted, insert the power and boot your Raspberry Pi to the desktop.
We’ll be using EasyGUI to create an interface for our project, but it is not installed as standard so to install this library open a terminal and type the following followed by Enter.
sudo apt-get install python-easygui
We also need to install the Energenie library; helpfully Ben Nuttall from the Raspberry Pi Foundation has already created a handy package for us to install. You can find Ben’s code at. In the terminal enter the following lines of code and press Enter after each line.
sudo apt-get install python-pip
sudo pip install energenie
With that installed, keep the terminal open and type sudo idle to launch the Idle editor. We need to do this so that we can access the GPIO, as only a user with root privileges can use the GPIO.
Careful when fitting the Energenie add-on to the Pi: GPIO pins can bend.
So let’s start coding!
In Idle, open a new file by going to File > New. I like to import the libraries necessary at the top of the script, as this means I only have one place to look for problems when I’m debugging the code.
from energenie import switch_on, switch_off
from time import sleep
import easygui as eg
Our first import brings two functions from the energenie library into our code, switch_on and switch_off (I think you can guess what they do). Our second import sees us bring the sleep function into our code; we will use this to time how long the charging station will operate. Our last import sees us import the easygui library and rename it to eg for easier use.
Next we shall create a function called timer. A function enables us to group a section of code under one name and then call the function by its name and have all of the code run in sequence, similar to a macro in office applications.
def timer():
You will see at the end of the line that there is a colon :, which instructs Python that this is the end of declaring the functions name and that the next lines will be the code that is contained therein.
t = float(eg.enterbox(title="Linux Voice Phone Charging?", msg="How long shall I charge your phone for (in minutes)?"))
Our first line of code for the function sees us create a variable called t, and in there we store the answer to the question “How long shall I charge your phone for?” We capture this using an enterbox from EasyGUI. This is a dialog box that can ask a question to the user and capture the answer. We give the dialog box a title and a message msg to the user to give us an answer in minutes. You will see that this is wrapped in a float function; this converts the answer given to a float value (a value that can have a decimal place).
t = t * 60
Our next line of code performs a little maths. We take the current value of t and then multiply it by 60 to give us the time in minutes but counted as seconds, so two minutes is 120 seconds.
switch_on()
sleep(t)
switch_off()
The next three lines of code turn on the Energenie unit, then it waits for the value of t before switching the unit off, and thus our phone stops charging. This is the end of the function, so now let’s look at the main body of code.
while True:
We start with an infinite loop (in Scratch this is called a forever loop), and this loop will go round and round until we break the loop or turn off the Raspberry Pi.
choice = eg.choicebox(title="Linux Voice Phone Charging",msg="Would you like to charge your phone?", choices=("Yes","No"))
The next line handles asking the user if they would like to charge their phone, and we use another dialog box from EasyGUI, this time the choicebox, which uses the same title and msg syntax as the enterbox, but you can see an extra value of choices that will appear as menu items in the dialog box.
Now we start a conditional statement, and it works like this.
If the value of choice is NOT equal to “No”
Then run the function called timer()
if choice != "No":
timer()
else:
print("All off")
switch_off()
break
Our last section of code handles the user selecting not to charge their phone. It prints All off to the shell and then makes sure that the Energenie unit is turned off before finally breaking the infinite loop and stopping the application.
So that’s the code – now make sure that your mobile phone is plugged into its charger and that is plugged into the Energenie.
Run the code by going to Run > Run Module. Answer the questions correctly and you should see your phone charging. If for some reason nothing happens, press and hold the green button of your Energenie for five seconds and then run the script again. We’ve taken our first step to saving the planet!
Our finished phone charger application isn’t pretty, but it will save you electricity.
Wireless communication
Connecting to a Raspberry Pi remotely can be accomplished in many different ways. To remotely control your Raspberry Pi on the command line (often called “Headless” mode) you can set up an SSH server on your Pi. In a terminal type sudo raspi-config and choose the SSH option from the Advanced menu.
To control your Pi over a network and use your mouse and screen there is a technology called VNC that can send the video from your Pi down a network. Head over to for more information. Please note that Minecraft does not work with VNC.
It’s also possible to connect to your Pi over radio using the Slice of Radio gadget from electronics vendor Ciseco and an SRF dongle from the Ciseco store:. This can have a range of many hundreds of metres, depending on line of sight.
The Energenie uses 433MHz transmitters to send a signal over radio from your Pi to the unit. 433MHz units can be found on eBay for a few pounds.
You could also set up a direct cable connection between your Raspberry Pi and computer via a cheap Ethernet cable. When used with SSH and VNC this enables you to use your Pi anywhere. Take a look at this great resource: for a guide on how to use it.
Project 2 – Minecraft controlled lights
We’re going to use Minecraft to create an interface based on our player’s location. Specifically, we’re going to use the game to make a light come on in the real world. Open LXTerminal and type
sudo idle
Open a new file in Idle File > New.
Just like Project 1 we shall start our code with importing the libraries that enable us to do more with Python.
from mcpi import minecraft
from energenie import switch_on, switch_off
from time import sleep
Our first import is the Minecraft library, which contains all of the functions that we will need to interface with a running Minecraft game. Our next import handles the Energenie interface, and finally we import the sleep function from the time library. In this tutorial we do not use it, but it can be used as an extension activity in class or at home.
mc = minecraft.Minecraft.create()
As of December 2014 Raspbian comes with Minecraft installed as standard. If your version is older then you will need to update your distro.
Next we create a variable called mc, and in there we store a connection to the Minecraft game running. By prefacing any of our functions with mc we instruct Python to replace mc with the full text.
while True:
We start the main body of code with an infinite loop (again, in Scratch this is called a forever loop), and this loop will go round and round until we break the loop or turn off the Raspberry Pi.
pos = mc.player.getTilePos()
In order to constantly search for the player’s location we create a variable called pos, in which we store the player’s position in the Minecraft world. This is an X Y Z coordinate system based on blocks being 1 metre cubed. The getTilePos function rounds up our position so this gives us a coarse location, but one that is easier to work with.
if pos.x == -7.0:
Now we use an if statement to compare the location of Steve, our character in Minecraft, with a hard-coded value of -7.0 (this was a position near to where the game dropped me off at the start of the game). If this condition is true, then the following code is executed, turning on the lamp in the real world.
mc.postToChat("Light On")
switch_on()
PostToChat is a method of sending text to users in a game, in this case us. We then call the switch_on function from Energenie to turn on the lamp attached to the unit.
else:
switch_off()
Finally, we set the condition to say that when we are not at the coordinates, turn the lamp off.
So that is the code complete. Before you run it, open Minecraft and start a new world. You can find Minecraft in the Games menu. Once it has loaded, switch back to Idle, release the mouse with the Tab key, and run the code using Run > Run Module.
Plug a lamp into your Energenie and make sure it is set to come on if it has a switch. Move Steve to the -7.0 coordinate (you can see your current position in the top-left of the screen). Once you find the right square the lamp will light up.
If you’re having a little difficulty finding the square, edit this line
if pos.x == -7.0:
To read
if pos.y > 5.0:
Save and run the code again. Now in Minecraft double-tap the Space bar to fly and then hold on to it for a few seconds. Steve will fly into the air and your light will come on.
Project 3 – push-button lamp
The low voltages in the Pi mean you’re safe when connecting components, but do be careful to avoid short circuits.
For our final project we will use a few cheap electronic components to create a simple remote switch to turn on the lamp. Physical computing is a great way for classes to understand the links between the real and virtual worlds. In this project we use a simple push button as our input, but we could use other types of inputs such as sensors.
To start the project you should have already set up your Raspberry Pi as per the instructions in Project 1.
Open LXTerminal and type sudo idle to start the Idle editor, then open a new file.
Just like the previous projects, we shall start our code with importing the libraries that enable us to do more with Python.
import RPi.GPIO as GPIO
from time import sleep
from energenie import switch_on, switch_off
We start our imports with RPi.GPIO, the library that enables Python to talk to the GPIO pins. We rename the library to GPIO, as it is easier to type.
The next two imports we have already used in the previous projects.
In order for us to use the GPIO pins we need to instruct Python as to how they are laid out. The Raspberry Pi has two pin layouts: BOARD and BCM.
BOARD relates to the physical layout on the board, with odd numbered pins on the left, and even on the right. Pin 1 is the top-left pin nearest the micro SD card slot.
BCM is short for Broadcom (the company that makes the Pi’s System-on-Chip (SoC)). This layout appears random, but the pins are labelled according to their internal reference on the SoC, which controls the Pi. BCM is considered the standard by the Raspberry Pi Foundation.
GPIO.setmode(GPIO.BCM)
In the next step we instruct Python that pin 26 is an input (GPIO.IN) and that it’s starting state should pulled high, in other words power is going to the pin.
GPIO.setup(26, GPIO.IN, GPIO.PUD_UP)
The next two lines of code handle resetting the light connected to our Energenie so that it starts in an off state. We then create a variable called status that stores the value off. We will use this to toggle the light.
switch_off()
status = "off"
We start the main body of code with an infinite loop and this loop will go round and round until we break the loop or turn off the Raspberry Pi.
while True:
In this line of code we instruct Python to wait for the button press as this will cause pin 26 to go from a high to low state, in other words the power will flow from pin 26 to Ground causing a change of state on the pin.
GPIO.wait_for_edge(26, GPIO.FALLING)
When this happens the next line of code is executed
switch_on()
status = "on"
sleep(0.5)
As before, switch_on will trigger the lamp to turn on, and the next line changes the value of our status variable to on. We shall use this value in a moment. The last line for this section instructs Python to wait for half a second.
if status == "on":
So now we have an if condition that compares the value of the variable status with the hard-coded value on, and if the condition evaluates as True then the last four lines of code are executed.
GPIO.wait_for_edge(26, GPIO.FALLING)
switch_off()
status = "off"
sleep(0.5)
So our light is on and the value of the status variable is on. This triggers Python to wait for another button press to occur, and when it happens it will turn off the light, change the status variable’s value to off and then wait for half a second before the loop starts again and waits for our button press once again.
That’s all the code completed. Save your work, but before running the code you’ll need to attach your button as per the photo above.
When ready, run the code using Run > Run Module and press the button on your breadboard. It should light up the lamp. Now go forth and build!
Renaming modules when you import them can save a lot of tricky typing later on the code.
Code for this project
All of the code for this project is housed in a GitHub repository. GitHub uses the Git version control framework to enable you to work on your code and then push it to the cloud; changes made on your machine can be pushed when ready, updating the code in the cloud. Others can “fork” your code and work on “branches” for example creating new features. These are then submitted to you for approval and when ready you can merge them with the main branch.
You can download the code for this project from if you are a Github user, if not you can download a ZIP archive containing all of the files used from.
Les Pounder divides his time between tinkering with hardware and travelling the United Kingdom training teachers in the new IT curriculum. | https://www.linuxvoice.com/being-green-with-your-raspberry-pi-and-python/ | CC-MAIN-2018-47 | en | refinedweb |
Get the size of the file descriptor table
#include <unistd.h> int getdtablesize( void );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Each process has a fixed size descriptor table, which is guaranteed to have at least 20 slots. The entries in the descriptor table are numbered with small integers starting at 0. The getdtablesize() returns the size of this table.
This function is equivalent to getrlimit() with the RLIMIT_NOFILE option.
The size of the file descriptor table. | http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.neutrino.lib_ref/topic/g/getdtablesize.html | CC-MAIN-2018-47 | en | refinedweb |
Get the "ignored signals" attribute from a spawn attributes object
#include <spawn.h> int posix_spawnattr_getsigignore( const posix_spawnattr_t *_Restrict attrp, sigset_t *_Restrict sigset_p);
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.(). | http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.neutrino.lib_ref/topic/p/posix_spawnattr_getsigignore.html | CC-MAIN-2018-47 | en | refinedweb |
WiPy 2.0 to send data to dweet.io and then display the data into freeboard.io
- dgzgonzalez last edited by
Hi All,
I'm trying to send data from my WiPy device to the dweet.io site using a "post" call.
I'm using the following lib:
And I wrote the following code (Note, the indentation does not work here and I used .... instead)
import urequests
import json
myData = {'Value_1': 20, 'Value_2': 300}
try:
....response = urequests.post("", data = json.dumps(myData))
....print(response.text)
except Exception as e:
.....print(e)
I'm receiving back the following message
{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing":"TheThing","created":"2017-07-19T16:52:41.547Z","content":{},"transaction":"5c436c5d-c772-4ab7-8dbd-b05321a47265"}}
As you can see the payload ({'Value_1': 20, 'Value_2': 300}) is not passed through and I'm running out of idea on why this is happening.
Does anyone has an idea or suggestion ?
Thank you in advance for your help.
Diego | https://forum.pycom.io/topic/1521/wipy-2-0-to-send-data-to-dweet-io-and-then-display-the-data-into-freeboard-io | CC-MAIN-2018-47 | en | refinedweb |
If you've installed tmux via homebrew
brew install tmux
And then you noticed that it just exists immediately after start
tmux
or any other command
tmux list-session > failed to connect to server: Connection refused
Then you just need to install
reattach-to-user-namespace script
Thankfully, homebrew makes this easy:
brew install reattach-to-user-namespace | https://coderwall.com/p/u3lhfa/tmux-exists-immediately | CC-MAIN-2018-47 | en | refinedweb |
[
]
Ted Yu commented on HBASE-4862:
-------------------------------
{code}
+ if (fileName.endsWith(HLog.RECOVERED_LOG_TMPFILE_SUFFIX))
+ fileName = fileName.split(HLog.RECOVERED_LOG_TMPFILE_SUFFIX)[0];
{code}
Please enclose the second line above in curly braces.
w.r.t. fs.rename() call, here is javadoc from ClientProtocol.rename(which is called by fs.rename):
{code}
* @return true if successful, or false if the old name does not exist
* or if the new name already belongs to the namespace.
{code}
We should check the return value along with catching exception.
>: | http://mail-archives.apache.org/mod_mbox/hbase-issues/201111.mbox/%3C1703561937.13116.1322289580779.JavaMail.tomcat@hel.zones.apache.org%3E | CC-MAIN-2017-43 | en | refinedweb |
Writes an implementation-defined message to
stderr which must include the string pointed to by
msg and calls
abort().
A pointer to this function can be passed to set_constraint_handler_s to establish a runtime constraints violation handler. As with all bounds-checked functions,
abort_handler_s is only guaranteed to be available if
__STDC_LIB_EXT1__ is defined by the implementation and if the user defines
__STDC_WANT_LIB_EXT1__ to the integer constant
1 before including
<stdlib.h>.
none; this function does not return to its caller.
If
set_constraint_handler_s is never called, the default handler is implementation-defined: it may be
abort_handler_s,
ignore_handler_s, or some other implementation-defined handler.
#define __STDC_WANT_LIB_EXT1__ 1 #include <string.h> #include <stdio.h> #include <stdlib.h> int main(void) { #ifdef __STDC_LIB_EXT1__ char dst[2]; set_constraint_handler_s(ignore_handler_s); int r = strcpy_s(dst, sizeof dst, "Too long!"); printf("dst = \"%s\", r = %d\n", dst, r); set_constraint_handler_s(abort_handler_s); r = strcpy_s(dst, sizeof dst, "Too long!"); printf("dst = \"%s\", r = %d\n", dst, r); #endif }
Possible output:
dst = "", r = 22 abort_handler_s was called in response to a runtime-constraint violation. The runtime-constraint violation was caused by the following expression in strcpy_s: (s1max <= (s2_len=strnlen_s(s2, s1max)) ) (in string_s.c:62) Note to end users: This program was terminated as a result of a bug present in the software. Please reach out to your software's vendor to get more help. Aborted
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0. | http://docs.w3cub.com/c/error/abort_handler_s/ | CC-MAIN-2017-43 | en | refinedweb |
This HTML version of is provided for convenience, but it
is not the best format for the book. In particular, some of the
symbols are not rendered correctly.
You might prefer to read
the PDF version.
People often describe programming languages as either compiled,
which means that programs are translated into machine language and
then executed by hardware, or interpreted, which means that programs
are read and executed by a software interpreter.
For example, C is considered a compiled language and Python is
considered an interpreted language. But the distinction is not always
clear-cut.
First, many languages can be either compiled or interpreted. For
example, there are C interpreters and Python compilers.
Second, there are languages like Java that use a hybrid
approach, compiling programs into an intermediate language and then
running the translated program in an interpreter. Java uses an
intermediate language called Java bytecode, which is similar to
machine language, but it is executed by a software interpreter, the
Java virtual machine (JVM).
So being compiled or interpreted is not an intrinsic
characteristic of a language; nevertheless, there are some general
differences between compiled and interpreted languages.
Many interpreted languages support dynamic types, but compiled
languages are usually limited to static types. In a statically-typed
language, you can tell by looking at the program what type each
variable refers to. In a dynamically-typed language,
you don’t always know the type of a variable until the
program is running. In general, “static” refers to things that
happen at compile time, and “dynamic” refers to things that happen
at run time.
For example, in Python you can write a function like this:
def add(x, y):
return x + y
Looking at this code, you can’t tell what type x and y
will refer to. At run time, this function might be called several
times, each time with values with different types. Any values that
support the addition operator will work; any other types will cause an
exception or “run time error.”
In C you would write the same function like this:
int add(int x, int y) {
return x + y;
}
The first line of the function includes “type declarations” for the
parameters and the return value: x and y are declared to
be integers, which means that we can check at compile time
whether the addition operator is legal for this type (it is). The
return value is also declared to be an integer.
Because of these declarations, when this function is called elsewhere
in the program, the compiler can check whether the arguments provided
have the right type, and whether the return value is used correctly.
These checks happen before the program starts executing, so errors can
be found more quickly. More importantly, errors can be found in parts
of the program that have never run. Furthermore, these checks don’t
have to happen at run time, which is one of the reasons compiled
languages generally run faster than interpreted languages.
Declaring types at compile time also saves space. In dynamic
languages, variable names are stored in memory while the program runs,
and they are often accessible by the program. For example, in Python
the built-in function locals returns a dictionary that contains
variable names and their values. Here’s an example in a Python
interpreter:
>>> x = 5
>>> print locals()
{'x': 5, '__builtins__': <module '__builtin__' (built-in)>,
'__name__': '__main__', '__doc__': None, '__package__': None}
This shows that the name of the variable is stored in memory while
the program is running (along with some other values that are part
of the default run-time environment).
In compiled languages, variable names exist at compile-time but not at
run time. The compiler chooses a location for each variable and
records these locations as part of the compiled program.1 The
location of a variable is called its “address”. At run time, the
value of each variable is stored at its address, but the names of the
variables are not stored at all (unless they are added by the compiler
for purposes of debugging).
As a programmer, you should have a mental model of what happens
during compilation. If you understand the process, it will help
you interpret error messages, debug your code, and avoid
common pitfalls.
The steps of compilation are:
#include
Normally when you run gcc, it runs all of these steps and
generates an executable file. For example, here is a minimal C
program:
#include <stdio.h>
int main()
{
printf("Hello World\n");
}
If you save this code in a file called
hello.c, you can compile and run it like this:
$ gcc hello.c
$ ./a.out
By default, gcc stores the executable code in a file
called a.out (which originally stood for “assembler output”).
The second line runs the executable. The prefix ./ tells
the shell to look for it in the current directory.
./
It is usually a good idea to use the -o flag to provide a
better name for the executable:
$ gcc hello.c -o hello
$ ./hello
The -c flag tells gcc to compile the program and
generate machine code, but not to link it or generate an executable:
$ gcc hello.c -c
The result is a file named hello.o, where the o stands for
“object code”, which is the compiled program. Object code is not
executable, but it can be linked into an executable.
The UNIX command nm reads an object file and generates
information about the names it defines and uses. For example:
$ nm hello.o
0000000000000000 T main
U puts
This output indicates that hello.o defines the name main
and uses a function named puts, which stands for “put string.”
In this example, gcc performs an optimization by replacing
printf, which is a large and complicated function, with
puts, which is relatively simple.
You can control how much optimization gcc does with
the -O flag. By default, it does very little optimization, which
can make debugging easier. The option -O1 turns on the most
common and safe optimizations. Higher numbers turn on additional
optimizations that require longer compilation time.
In theory, optimization should not change the behavior of the program,
other than to speed it up. But if your program has a subtle bug,
you might find that optimization makes the bug appear or disappear.
It is usually a good idea to turn off optimization while you are developing
new code. Once the program is working and passing appropriate tests,
you can turn on optimization and confirm that the tests still pass.
Similar to the -c flag, the -S flag tells gcc
to compile the program and generate assembly code, which is basically
a human-readable form of machine code.
$ gcc hello.c -S
The result is a file named hello.s, which might look something like
this:
.file "hello.c"
.section .rodata
.LC0:
.string "Hello: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3"
.section .note.GNU-stack,"",@progbits
gcc is usually configured to generate code for the machine you
are running on, so for me it generates x86 assembly language,
which runs on a wide variety of processors from Intel, AMD, and
others. If you are running on a different architecture, you might
see different code.
Taking another step backward through the compilation process, you
can use the -E flag to run the preprocessor only:
$ gcc hello.c -E
The result is the output from the preprocessor. In this example,
it contains the included code from stdio.h, and all the files
included from stdio.h, and all the files included from those
files, and so on. On my machine, the total is more than 800 lines
of code. Since almost every C program includes stdio.h, those
800 lines of code get compiled a lot. If, like many C programs,
you also include stdlib.h, the result is more than 1800 lines
of code.
Now that we know the steps in the compilation process, it is easier
to understand error messages. For example, if there is an error
in a #include directive, you’ll get a message from the
preprocessor:
hello.c:1:20: fatal error: stdioo.h: No such file or directory
compilation terminated.
If there’s a syntax error, you get a message from the compiler:
hello.c: In function 'main':
hello.c:6:1: error: expected ';' before '}' token
If you use a function that’s not defined in any of the standard
libraries, you get a message from the linker:
/tmp/cc7iAUbN.o: In function `main':
hello.c:(.text+0xf): undefined reference to `printff'
collect2: error: ld returned 1 exit status
ld is the name of the UNIX linker, so named because “loading”
is another step in the compilation process that is closely related
to linking.
Once the program starts, C does very little run-time checking,
so there are only a few run-time errors you are likely to see. If you
divide by zero, or perform another illegal floating-point operation, you
will get a “Floating point exception.” And if you try to read or
write an incorrect location in memory, you will get a “Segmentation
fault.”
Think Bayes
Think Python
Think Stats
Think Complexity | http://greenteapress.com/thinkos/html/thinkos002.html | CC-MAIN-2017-43 | en | refinedweb |
A simple XHTML document, with the minimum of required tags:
The xmlns attribute specifies the xml namespace for a document.
Note: The xmlns attribute is required in XHTML, invalid in HTML 4.01, and optional in HTML5.
Note: The HTML validator at does not complain when the xmlns attribute is missing in an XHTML document. This is because the namespace "xmlns=" is default, and will be added to the <html> tag even if you do not include it. | http://www.w3schools.com/tags/att_html_xmlns.asp | CC-MAIN-2015-06 | en | refinedweb |
30 April 2013 23:17 [Source: ICIS news]
MEDELLIN, Colombia (ICIS)--Mexichem’s Q1 net income fell by 54% to Mexican pesos (Ps) 836m ($67m, €51m) as a result of higher production costs and currency exchange loss, the Mexico-based chemical conglomerate said on Tuesday.
Quarterly revenues were up by 14% to Ps15.5bn, driven by higher prices in the chlorine-vinyl chain and the integration of Wavin in the consolidated results.
Mexichem acquired the PVC pipe maker in June 2012.
Increased revenue was partially offset by reduced sales in the company’s chlorine-vinyl and fluorine chains, which were down by 20% and 24%, respectively.
The company’s earnings before interest, taxes, depreciation and amortization (EBITDA) stood at Ps2.7bn, down by about 7% from 2.9bn in the prior-year quarter.
Mexichem, the largest producer of polyvinyl chloride (PVC), vinyl resins and compounds in ?xml:namespace>
The company confirmed the acquisition of the PVC resin operations of US firm PolyOne, adding that the sale was awaiting approval by US regulatory authorities.
The company also said that it was awaiting conclusion of a feasibility study for the construction of an ethane cracker in the
In August, Occidental Chemical (OxyChem) and Mexichem signed a memorandum of understanding to evaluate the creation of a joint venture to build a 500,000 tonne/year ethane cracker. OxyChem would use nearly all of the ethylene as feedstock to produce 1m tonnes of vinyl chloride monomer (VCM) at its complex in
OxyChem would then sell the VCM to Mexichem under a long-term contract.
The cracker could begin operations in 2016, Mexichem said.
($1 = €0.76; $1 = Ps12.13) | http://www.icis.com/Articles/2013/04/30/9663987/mexicos-mexichem-q1-income-halved-on-higher-costs-strong.html | CC-MAIN-2015-06 | en | refinedweb |
This was great. Thanks.
your java codes are very good .. and eASy to understand for me.
It is making more time than bubble sort.
hello,
How can we implement the max heap, by using only pointers and not arrays?
Thanks in advance.
You are unnecessarily running two for loops inside the fnSortHeap(). You can remove one of them.
Post....
Example of Heap Sort in Java:
public class eap_Sort{
public static void main...\sorting>Javac heap_Sort.java
C:\array\sorting>java heap_Sort
Heap Sort
Insertion Sort In Java
Insertion Sort In Java
.... There are more efficient algorithms such as
quick sort, heap sort, or merge sort...
In this example we are going to sort integer values of an array using
insertion
sort
Quick Sort in Java
Quick sort in Java is used to sort integer values of an array...
in comparison to other sorting algorithms like bubble sort, insertion sort, heap... into a sorted array.
Example of Quick Sort in Java:
public class QuickSort
Sort
Sort program to sort a list of numbers in decendimg order
Hi Friend,
Try the following code:
import java.util.*;
class SortListInDescendingOrder{
public static void main(String[] args
Bidirectional Bubble Sort in Java
Bidirectional Bubble Sort in Java
Introduction : Bidirectional Bubble Sort
In this example we are going to sort integer values
AwesomeBiggy April 15, 2011 at 8:40 PM
This was great. Thanks.
advance computer programmingmehwish May 26, 2013 at 12:35 AM
your java codes are very good .. and eASy to understand for me.
Some thing with this codeManohar Reddy December 1, 2011 at 3:57 PM
It is making more time than bubble sort.
max heap with pointerssam Evans January 17, 2013 at 2:22 AM
hello, How can we implement the max heap, by using only pointers and not arrays? Thanks in advance.
This code is incorrectChinmay August 1, 2013 at 4:44 AM
You are unnecessarily running two for loops inside the fnSortHeap(). You can remove one of them.
Post your Comment | http://www.roseindia.net/discussion/19927-Heap-Sort-in-Java.html | CC-MAIN-2015-06 | en | refinedweb |
23 October 2013 14:36 [Source: ICIS news]
HOUSTON (ICIS)--?xml:namespace>
Methanex is relocating two methanol plants from
Entergy Gulf States Louisiana said that under the deal it will supply Methanex's Geismar site with up to 30 megawatts of power.
The companies’ power contract is for an initial 10-year term and will continue thereafter on a year-to-year basis. Entergy plans to upgrade its electric transmission system to meet the increased demand from Geismar, it added.
Gustavo Parra, Methanex’s vice president for “Global Excellence and Projects”, added: “Methanex selected Entergy as the sole source for their power needs because of Entergy’s ability to provide safe, clean, reliable and affordable power within the required timeframe.”
Financial details were not disclosed.
Entergy added that Methanex’s first plant is expected to be operational by the end of 2014, and the second plant is expected to be operational | http://www.icis.com/Articles/2013/10/23/9718196/methanex-secures-power-supply-deal-for-louisiana-methanol-site.html | CC-MAIN-2015-06 | en | refinedweb |
07 November 2012 03:21 [Source: ICIS news]
WASHINGTON (ICIS)--President Barack Obama appears to have won some key ?xml:namespace>
In addition to traditionally Democrat states such as
In Wisconsin, Romney was thought to have a bit of an advantage over the sitting president because Wisconsin Republican Governor Scott Walker earlier beat back a Democrat effort to have him removed from office.
But the vote outcome in other key states remained uncertain late on Tuesday, with final tallies in
Conventional wisdom says that if Romney is to win the presidency, he must take
Although it is a small state, both geographically and in terms of its | http://www.icis.com/Articles/2012/11/07/9611588/obama-appears-to-have-won-key-us-states-in-national-vote.html | CC-MAIN-2015-06 | en | refinedweb |
03 March 2011 19:58 [Source: ICIS news]
TORONTO (ICIS)--?xml:namespace>
The call came after Germany’s refining trade group MWV said demand for E10 was “dramatically low" as drivers feared the fuel could damage their cars.
Refiners were left with unsold stock of E10 and needed “to adjust production” to the low demand, the group said.
Adding to the uncertainty on Thursday were media reports that cited MWV head Klaus Picard as saying refiners wanted to pull E10 from the market.
MWV dismissed those reports, saying it had no plans to pull E10, which so far had been introduced at about 45% of
Economics minster Rainer Bruderle said he was calling a “gasoline summit” with industry to clarify matters and reassure drivers as to the suitability of E10.
According to MWV, about 90% of all cars on
In related news, the US Environmental Protection Agency recently authorised the use of 15% ethanol (E15) blends for older-model passenger cars. | http://www.icis.com/Articles/2011/03/03/9440677/German-minister-summons-industry-as-E10-launch-hits.html | CC-MAIN-2015-06 | en | refinedweb |
I created a variable for the scanner called serena. Serena variable is equal to what the user inputs. My if statement says that if the answer the user enters is not equal to the actual answer then it is to display "wrong". It is a basic math game I am working on. NetBeans is telling me that I cannot use the scanner in an if statement? I am confused. Please take a look and help.
package pkgnew;
import java.util.Scanner;
public class New{
public static void main(String args[]){
Scanner serena = new Scanner(System.in);
double fnum, snum, answer;
fnum = 6;
snum = 6;
answer = fnum + snum;
System.out.println("6 + 6");
serena.nextLine();
if (serena = answer){
System.out.println("Correct!");
}else
System.out.println("Wrong!The answer is:" answer);{
}
}
--- Update ---
Do I have to define Serena as whatever number the user inputs? If so, how? | http://www.javaprogrammingforums.com/whats-wrong-my-code/37676-scanner-cannot-used-variable-if-statements.html | CC-MAIN-2015-06 | en | refinedweb |
This is revision 1.5612. 2-to-1.
This occurs when a browsing context is navigated from the initial
about:blank
Document to another, with
replacement enabled. Second, a
Document
can end up being reused for several
Window objects when
the
document.open() method is
used, such that the mapping is then 1-to-many..
Each unit of related similar-origin browsing
contexts also has a running mutation observers
flag, which must initially be false. It is used to prevent reentrant
invocation of the algorithm to invoke
MutationObserver
objects. For the purposes of
MutationObserver
objects, each unit of related similar-origin browsing
contexts is a distinct scripting environment., "maybe new" means the same as "new" but the requirements for those cases encourage user agents to treat it more like "none", and "none" means that by default nothing will happen.
† This case is only possible if the
sandbox attribute also allows
scripts.
An algorithm is allowed to show a pop-up — it is determined by the rules given for the first applicable option from the following list: [TreatNonCallableAsNull] attribute Function? onabort; [TreatNonCallableAsNull] attribute Function? onafterprint; [TreatNonCallableAsNull] attribute Function? onbeforeprint; [TreatNonCallableAsNull] attribute Function? onbeforeunload; [TreatNonCallableAsNull] attribute Function? onblur; [TreatNonCallableAsNull] attribute Function? oncanplay; [TreatNonCallableAsNull] attribute Function? oncanplaythrough; [TreatNonCallableAsNull] attribute Function? onchange; [TreatNonCallableAsNull] attribute Function? onclick; [TreatNonCallableAsNull] attribute Function? oncontextmenu; [TreatNonCallableAsNull] attribute Function? oncuechange; [TreatNonCallableAsNull] attribute Function? ondblclick; [TreatNonCallableAsNull] attribute Function? ondrag; [TreatNonCallableAsNull] attribute Function? ondragend; [TreatNonCallableAsNull] attribute Function? ondragenter; [TreatNonCallableAsNull] attribute Function? ondragleave; [TreatNonCallableAsNull] attribute Function? ondragover; [TreatNonCallableAsNull] attribute Function? ondragstart; [TreatNonCallableAsNull] attribute Function? ondrop; [TreatNonCallableAsNull] attribute Function? ondurationchange; [TreatNonCallableAsNull] attribute Function? onemptied; [TreatNonCallableAsNull] attribute Function? onended; [TreatNonCallableAsNull] attribute Function? onerror; [TreatNonCallableAsNull] attribute Function? onfocus; [TreatNonCallableAsNull] attribute Function? onhashchange; [TreatNonCallableAsNull] attribute Function? oninput; [TreatNonCallableAsNull] attribute Function? oninvalid; [TreatNonCallableAsNull] attribute Function? onkeydown; [TreatNonCallableAsNull] attribute Function? onkeypress; [TreatNonCallableAsNull] attribute Function? onkeyup; [TreatNonCallableAsNull] attribute Function? onload; [TreatNonCallableAsNull] attribute Function? onloadeddata; [TreatNonCallableAsNull] attribute Function? onloadedmetadata; [TreatNonCallableAsNull] attribute Function? onloadstart; [TreatNonCallableAsNull] attribute Function? onmessage; [TreatNonCallableAsNull] attribute Function? onmousedown; [TreatNonCallableAsNull] attribute Function? onmousemove; [TreatNonCallableAsNull] attribute Function? onmouseout; [TreatNonCallableAsNull] attribute Function? onmouseover; [TreatNonCallableAsNull] attribute Function? onmouseup; [TreatNonCallableAsNull] attribute Function? onmousewheel; [TreatNonCallableAsNull] attribute Function? onoffline; [TreatNonCallableAsNull] attribute Function? ononline; [TreatNonCallableAsNull] attribute Function? onpause; [TreatNonCallableAsNull] attribute Function? onplay; [TreatNonCallableAsNull] attribute Function? onplaying; [TreatNonCallableAsNull] attribute Function? onpagehide; [TreatNonCallableAsNull] attribute Function? onpageshow; [TreatNonCallableAsNull] attribute Function? onpopstate; [TreatNonCallableAsNull] attribute Function? onprogress; [TreatNonCallableAsNull] attribute Function? onratechange; [TreatNonCallableAsNull] attribute Function? onreset; [TreatNonCallableAsNull] attribute Function? onresize; [TreatNonCallableAsNull] attribute Function? onscroll; [TreatNonCallableAsNull] attribute Function? onseeked; [TreatNonCallableAsNull] attribute Function? onseeking; [TreatNonCallableAsNull] attribute Function? onselect; [TreatNonCallableAsNull] attribute Function? onshow; [TreatNonCallableAsNull] attribute Function? onstalled; [TreatNonCallableAsNull] attribute Function? onstorage; [TreatNonCallableAsNull] attribute Function? onsubmit; [TreatNonCallableAsNull] attribute Function? onsuspend; [TreatNonCallableAsNull] attribute Function? ontimeupdate; [TreatNonCallableAsNull] attribute Function? onunload; [TreatNonCallableAsNull] attribute Function? onvolumechange; [TreatNonCallableAsNull] attribute Function? onwaiting; };
window
frames
self
These attributes all return window.
document
Returns the active document.
defaultView
Returns the
Window object of the active document.
The
Window interface must not exist if the
interface's relevant namespace object is not a
Window object. [WEBIDL] the method is not allowed to show a pop-up and url is
"
about:blank",.
It is possible that this will change. Browser vendors are considering limiting this behaviour to quirks mode. Read more...
To determine the value of a named property name when the
Window object is indexed for property retrieval, | http://www.w3.org/TR/2012/WD-html5-20120329/browsers.html | CC-MAIN-2015-06 | en | refinedweb |
Agenda
See also: IRC log
rssagent, make log public
<markbirbeck> running a couple of minutes late....sorry
<markbirbeck> be there shortly
<wing> elias should be along in a few minutes as well; he got stuck in traffic
<scribe> Scribe: Steven
-> Previous minutes
<mhausenblas> an inital step XMLLiteral
<scribe> ACTION: Ben to add issue to issues list and start discussion with previous reference and issue reference [recorded in] [PENDING]
<scribe> ACTION: Ben start a list of RDF/XML features that are not supported by RDFa [recorded in] [PENDING]
<scribe> ACTION: Ben to include agenda item for approval of existing tests [recorded in] [DONE]
<scribe> ACTION: Ben to look into Science Commons use case [recorded in] [PENDING]
<scribe> ACTION: Elias to look for cases where plain literal is more of a common use. [recorded in] [PENDING]
<scribe> ACTION: Elias to send email to list with use case from IBM [recorded in] [PENDING]
<scribe> ACTION: Mark produce more examples of applicability of n-ary relations from IPTC documents [recorded in] [PENDING]
<scribe> ACTION: MarkB to work rdf:label back into RDFa syntax when using @content [recorded in] [PENDING]
<scribe> ACTION: Steven to put together sample XHTML2 doc with all mime type, etc. [recorded in] [ONGOING]
<scribe> ACTION: Wing add a property to the test case schema for tracking origin and approval of an individual test [recorded in] [PENDING]
<scribe> ACTION: Ben to take a look at to see if issue has been resolved [recorded in] [ONGOING]
<mhausenblas> RDFa TC status
Mh: Still need some time to finalize
<mhausenblas> RDFa TC status
Mh: happy for feedback
Ben: The partitioning is great
... great to partition along host language types
... might need a grid HTML4/XHTML 1.1/XHTML 2.0
... and SVG might be another column in time
Shane: I think partitioning is great, I have an SGML DTD for HTML 4.01
Mh: Public available?
Shane: For small values of public, sure
<ShaneM> html401+rdfa SGML DTD is at
Ben: About conformance of existing
implementations:
... the bookmarklets are almost uptodate
... Elias's parser is not up-to-date
... but we need to track which implementations are following the latest version
... Do we have an XSLT guru on the team?
... since we could update Fabian's XSLT version
Mh: I'd be happy to do it
Ben: I'm thrilled!
ACTION Michael to update Fabian's XSLT
<scribe> ACTION: Michael to update Fabian's XSLT [recorded in]
Ben: Do we agree with the hybrid solution?
... where mixed content gives XML Literal, otherwise a plain literal
... with an attribute to override
Mark: The hybrid isn't as good as I had
originally thought
... for instance the <table> example
Ben: This is the case with RDFa attribute on the <tr>, and you don't want the <td>s. Isn't the override then the solution?
Mark: Yes, could be
... The solution has to be consistent
Ben: I don't want to reopen the whole issue. I don't see what the problem is with your current example
<tr property="foaf:name"><td>Fred</td><td>Bloggs</td></tr>
Mark: I would like the markup to be preserved, but the query to work
<EliasT> <> foaf:name "<td>Fred</td><td>Bloggs</td>"^^rdfs:XMLLiteral ?
Ben: That's what the hybrid gives us
... I don't get the problem
Elias: I agree that you can write the SPARQL
queries in a defensive manner
... I don't think it should be a driver for the design of RDFa
... why is the snippet above useful to me?
Mark: Why is it not useful?
Elias: I'm OK with that output
... I don't want to go in circles again
<Zakim> mhausenblas, you wanted to ask about the procedure
Mh: I thought we were going to investigate
APIs
... I don't see the problem here.
Ben: I agree with Mark that RDFa brings in a whole new world of semantic markup
Elias: The question is about what should the
default be. Plain, or XML literal.
... but the hybrid solution seems to make this question moot
Mark: My remaining issue is not with the markup
but with the people writing the queries
... if we agree that defensive queries is the solution, then I am happy
<EliasT> Ben, could you please write a PROPOSAL text so we can agree on that and have that on the minutes?
PROPOSAL: Use the hybrid approach, and query defensively
<EliasT> Steven, but I need more explicit text...
<EliasT> :-)
<ShaneM> It would be great if the Primer could capture an example of a defensive query
<benadida> PROPOSAL: we use a hybrid approach: no markup gives a plain literal by default, markup gives an XMLLiteral by default, and datatype can override it in either direction with shorthands.
<EliasT> <> foaf:name "<td>Elias</td>"
<EliasT> <> foaf:name "Elias"^^rdfs:XMLLiteral
Ben: This is not our problem
... i.e. reserialising RDF triples as X/HTML
<benadida> PROPOSAL: we use a hybrid approach: no markup gives a plain literal by default, markup gives an XMLLiteral by default, and datatype can override it in either direction with shorthands. datatype=plain either explicit or by default strips the markup (in some way).
Mark: We need to be explicit what happens when mixed content gets recorded as Plain
<ShaneM> I would like to see whatever the decision is reflected in the description of @datatype in the xhtml-rdfa draft.
<ShaneM> if there are reserved values in the xhtml namespace for @datatype, we need todocument those.
Ben: We still need to resolve what happens when markup gets stripped
<benadida> PROPOSAL:).
Mark: I think we need all text nodes to be concatenated
<EliasT> Second
<mhausenblas> +1
<Simone> +1
<wing> +1
<ShaneM> abstain
RESOLUTION:).
<benadida>
Ben: Opposed?
[none]
<EliasT> +1
Ben: Opposed?
[None]
Ben: href on all elements. Opposed?
[None]
<scribe> ACTION: Ben to update issues list [recorded in]
<ShaneM> coming back.... arrgh
Ben: an earlier proposal had src representing
subject
... we rejected this
... as an object was another proposal
Mark: I sent a private email on this
... the reason src is different, is because the relationship to the document is obvious
<ShaneM> let's debate in e-mail?
Ben: We have opened the discussion, we need to discuss it, and should debate in email
<ShaneM> gotta run - on html call in 3 minutes
Ben: no resolution yet
ADJOURN
Meeting next week, Monday
This is scribe.perl Revision: 1.128 of Date: 2007/02/23 21:38:13 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/Done/Pending/ Succeeded: s/--/-- / Succeeded: s/is/is not/ Succeeded: s/Y/T/ Succeeded: s/tion/tion?/ Succeeded: s/Liet/Lit/ Succeeded: s/irlc/ircl/ Succeeded: s/vb/v/ Succeeded: s/ oc/doc/ Succeeded: s/6// Found Scribe: Steven Inferring ScribeNick: Steven Default Present: mhausenblas, McCarron, Simone, Steven, Ben_Adida, MarkB, ShaneM, wing, EliasT Present: mhausenblas McCarron Simone Steven Ben_Adida MarkB ShaneM wing EliasT Regrets: Ralph Agenda: Got date from IRC log name: 11 Apr 2007 Guessing minutes URL: People with action items: ben elias mark markb michael steven wing[End of scribe.perl diagnostic output] | http://www.w3.org/2007/04/11-rdfa-minutes.html | CC-MAIN-2015-06 | en | refinedweb |
#include <Xm/Xm.h> XmString XmStringConcatAndFree( XmString s1, XmString s2);.
Returns a new compound string.
XmStringConcat(3), XmStringCreate(3), and XmStringFree(3). | http://www.makelinux.net/man/3/X/XmStringConcatAndFree | CC-MAIN-2015-06 | en | refinedweb |
You need to sign in to do that
Don't have an account?
StandardSetController and Controller Extensions
Hello,
I am trying to take advantage of the new StandardSetController functionality with a custom data set (not driven through a predefined listview filter). I am having difficulty finding the right syntax within the controller to enable this.
I have the following page:
Code:
<apex:page <apex:form <apex:sectionHeader <apex:pageBlock > <apex:pageBlockTable <apex:column <apex:column </apex:pageBlockTable> </apex:pageBlock> </apex:sectionHeader> </apex:form> </apex:page>
And my most recent cut of the controller extension is as follows:
Code:
public class ListPOC_Controller { public ListPOC_Controller(ApexPages.StandardSetController stdSetController) { // what static var do I need to bind— } public List <Account> getAccts() { return [select id, name from Account limit 25];
}
Is this even possible? Can anyone help me fill in the gaps on the controller extension?
Thanks in advance.
Message Edited by mtbclimber on 10-04-2008 12:10 PM
What you need to do is construct a new StandardSetController object in your Apex controller using the querylocator based constructor. The one you get from the extension is going to be based on the predefined listview filter.
Check out the section titled "Building a Custom List Controller" on page 64 of the Winter '09 Visualforce Developer Guide.
Thanks Andrew, however when I copy the example from the developer's guide straight into a Winter 09 sandbox, I receive an error when I attempt to save the page indicating: 'Unknown Property: Sobject.Name'.
Has anyone else been able to get the sample from the book to work?
Message Edited by ForceDev on 10-06-2008 06:52 AM
Message Edited by ForceDev on 10-06-2008 06:54 AM
Thanks for the quick response Andrew, I will try that and respond to the thread what I find. Before I do that, in looking at your suggestion I am trying to understand if I would be able to take advantage of any of the available StandardListController functionality if what I return to the page is simply a list of Opportunities. What I am trying to do is essentially present a custom data set within the enhanced list view user interface module, where users can select 0 or more records then click on a custom button to perform an action against the selected records.
Am I barking up the wrong tree?
In order to present a selection column you'll actually want to return a collection of wrapper objects instead of sobjects (casted) directly, something like this:
Then you can bind the selection column inputCheckbox to the boolean property and subsequent postbacks will set the value on each respective row accordingly.
Ok, thanks - was afraid of this. Since you allow folks to present this interface along with the filter selection dropdown....I was hoping that you could simply not present the drop down and dictate to the enhanced list view controller what the dataset should be within the controller...would be a nice feature (to take advantage of pagination, robust UI controls, etc.)
I understand the direction I need to go in.
Thanks again for your attention and responses.
Hi,
Is it possible to use this approach to display the output of a dynamic SOQL query on a custom object in an enhanced list. I can't find anything in the documentation that explicitly says this is not possible, but I've had a number of my developers say it can't be done...but it's only enhanced lists that have this problem.
Has anyone ever managed to do this?
Thanks. | https://developer.salesforce.com/forums/?id=906F000000094xQIAQ | CC-MAIN-2021-31 | en | refinedweb |
@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Import(value=TransactionManagementConfigurationSelector.class) public @interface EnableTransactionManagement
<tx:*>XML namespace. To be used on @
Configurationclasses as follows:
@Configuration @EnableTransactionManagement public class AppConfig { ()); } }
For reference, the example above can be compared to the following Spring XML configuration:
In both of the scenarios above,In both of the scenarios above,
<beans> <tx:annotation-driven/> <bean id="fooRepository" class="com.foo.JdbcFooRepository"> <constructor-arg </bean> <bean id="dataSource" class="com.vendor.VendorDataSource"/> <bean id="transactionManager" class="org.sfwk...DataSourceTransactionManager"> <constructor-arg </bean> </beans>
@EnableTransactionManagementand
<tx:annotation-driven/>are responsible for registering the necessary Spring components that power annotation-driven transaction management, such as the TransactionInterceptor and the proxy- or AspectJ-based advice that weave the interceptor into the call stack when
JdbcFooRepository's
@Transactionalmethods are invoked.
A minor difference between the two examples lies in the naming of the
PlatformTransactionManager bean: In the
@Bean case, the name is
"txManager" (per the name of the method); in the XML case, the name is
"transactionManager". The
<tx:annotation-driven/> is hard-wired to
look for a bean named "transactionManager" by default, however
@EnableTransactionManagement is more flexible; it will fall back to a by-type
lookup for any
PlatformTransactionManager bean in the container. Thus the name
can be "txManager", "transactionManager", or "tm": it simply does not matter.
For those that wish to establish a more direct relationship between
@EnableTransactionManagement and the exact transaction manager bean to be used,
the
TransactionManagementConfigurer callback interface may be implemented -
notice the
implements clause and the
@Override-annotated method below:
@Configuration @EnableTransactionManagement public class AppConfig implements TransactionManagementConfigurer { ()); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return txManager(); } }This approach may be desirable simply because it is more explicit, or it may be necessary in order to distinguish between two.
TransactionManagementConfigurer,
TransactionManagementConfigurationSelector,
ProxyTransactionManagementConfiguration,
AspectJTransactionManagementConfiguration
public abstract boolean proxyTargetClass
true) as opposed to standard Java interface-based proxies (
false). The default is
false. Applicable only if
mode()is set to
AdviceMode.PROXY.
Note that setting this attribute to
true will affect all
Spring-managed beans requiring proxying, not just those marked with
@Transactional. For example, other beans marked with Spring's
@Async. | https://docs.spring.io/spring-framework/docs/4.1.0.RC1/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html | CC-MAIN-2021-31 | en | refinedweb |
In versions of Unity earlier than Unity 5, assets dependencies had to be defined using editor scripts alone. (In Unity 5 we provide tools in the editor to assign assets to specific Bundles and dependency handling is automatic). This information is provided for those working on legacy projects in Unity 4, and speaks assuming you are using Unity 4.
Any given asset in a bundle may depend on other assets. For example, a model may incorporate materials which in turn make use of textures and shaders. It is possible to include all an asset’s dependencies along with it in its bundle. However, several assets from different bundles may all depend on a common set of other assets (eg, several different models of buildings may use the same brick texture). If a separate copy of a shared dependency is included in each bundle that has objects using it, then redundant instances of the assets will be created when the bundles are loaded. This will result in wasted memory.
To avoid such wastage, it is possible to separate shared dependencies out into a separate bundle and simply reference them from any bundles with assets that need them. First, the referencing feature needs to be enabled with a call to BuildPipeline.PushAssetDependencies. Then, the bundle containing the referenced dependencies needs to be built. Next, another call to PushAssetDependencies should be made before building the bundles that reference the assets from the first bundle. Additional levels of dependency can be introduced using further calls to PushAssetDependencies. The levels of reference are stored on a stack, so it is possible to go back a level using the corresponding BuildPipeline.PopAssetDependencies function. The push and pop calls need to be balanced including the initial push that happens before building.
At runtime, you need to load a bundle containing dependencies before any other bundle that references them. For example, you would need to load a bundle of shared textures before loading a separate bundle of materials that reference those textures.
If you anticipate needing to rebuild asset bundles that are part of a dependency chain then you should build them with the BuildAssetBundleOptions.DeterministicAssetBundle option enabled. This guarantees that the internal ID values used to identify assets will be the same each time the bundle is rebuilt.
When building the asset bundle with this method, the objects in it are assigned a 32 bit hash code that is calculated using the name of the asset bundle file, the GUID of the asset and the local id of the object in the asset. For that reason make sure to use the same file name when rebuilding. Also note that having a lot of objects might cause hash collisions preventing Unity from building the asset bundle.
Whenever shaders are directly referenced as parameters in BuildPipeline.BuildAssetBundle, or indirectly with the option BuildAssetBundleOptions.CollectDependencies the shader’s code is included with the asset bundle. This could cause a problem if you use BuildAssetBundle alone to create several asset bundles, since referenced shaders will be included in every generated bundle. There could be conflicts, i.e. when you mix different versions of a shader, so you will have to rebuild all your bundles after modifying the shaders. The shader’s code will also increase the size of bundles. To avoid these problems you can use BuildPipeline.PushAssetDependencies to separate shaders in a single bundle, and that will allow you to update the shader bundle only. As an example of how to achieve this workflow, you can create a prefab that includes references to the required shaders:
using UnityEngine; public class ShadersList : MonoBehaviour { public Shader[] list; }
Create an empty object, assign the script, add the shaders to the list and create the prefab, i.e. “ShadersList”. Then you can create an exporter that generates all the bundles and updates the bundle of shaders:
using UnityEngine; using UnityEditor; public class Exporter : MonoBehaviour { [MenuItem("Assets/Export all asset bundles")] static void Export() {.PushAssetDependencies(); BuildPipeline.BuildAssetBundle(AssetDatabase.LoadMainAssetAtPath("Assets/Scene1.prefab"), null, "Data/Scene1.unity3d", options); BuildPipeline.BuildAssetBundle(AssetDatabase.LoadMainAssetAtPath("Assets/Scene2.prefab"), null, "Data/Scene2.unity3d", options); BuildPipeline.PopAssetDependencies(); BuildPipeline.PopAssetDependencies(); } [MenuItem("Assets/Update shader bundle")] static void ExportShaders() {.PopAssetDependencies(); } }
Bear in mind that you must load the shader bundle first. One drawback of this method is that the option BuildAssetBundleOptions.DeterministicAssetBundle can produce conflicts due to colliding hashes when the amount of objects is too large. In this case the build will fail, and it won’t be possible to update the shader bundle alone. In this case you will have to remove that option and rebuild all the asset bundles. | https://docs.unity3d.com/ru/2019.4/Manual/AssetBundleDependencies4x.html | CC-MAIN-2021-31 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.