text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
We.
Measuring real-world performance of websites is difficult and error prone today. Developers are forced to use hacks, such as injecting low resolution JavaScript timestamps throughout their code, which slows down the pages for end users, introduces an observer effect, and provides inaccurate results which can drive the wrong behavior.
The browser knows exactly how long it takes to load and execute a webpage, so we believe the right solution is for the browser to provide developers an API to access these performance results. Web developers shouldn’t have to think about how to measure performance – it should just be available for them.
It’s important for this API to be interoperable across all browsers and platforms so that developers can consistently rely on these results. The Web Timing specification at the W3C is a good foundation for solving this problem in an interoperable manner. The implementation that you’ll find in the latest IE9 platform preview is based off the navigation section of Web Timings and we’ve started conversations with the W3C and other browser manufacturers about working together to get Web Timing chartered and broadly supported.
Let’s take a closer look at how developers are forced to measure performance today and what the new API’s enable.
How Developers Measure Performance Today
Today, in order to collect performance metrics a web developer has to instrument their code with specific timing markers at strategic places on their web page. This can result in code that opposes performance best practices. Developers write something like this:
<html> <head> <script type=”text/javascript”> var start = (new Date).getTime(); </script> </head> <body> <script type=”text/javascript”> /* do work here */ var pageLoad = (new Date).getTime() - start; </script> </body> </html>
This approach has several problems. It forces the JavaScript engine to load earlier than normal. It forces the HTML and JavaScript parsers to switch contexts. It may block parallel requests to load the remaining resources.
Something else to mention is that this JavaScript approach does not capture network latency timings, which is the time associated from when the document is initially requested from the server to the time it arrives and is displayed to the end-user.
Additionally, while the Date function is available across all browsers, the results vary in precision. John Resig has a nice blog post in which he goes to some lengths to determine that the time from
(new Date).getTime(); is as precise as 7.5ms on average across browsers, half the interval for the Windows system timer at 15ms. Many operations can execute in under 1ms which means that some measurements can have an error range of 750%!
How Developers can Measure Performance with Internet Explorer 9
The third Internet Explorer 9 platform preview contains a prototype implementation of the Web Timings NavigationTiming interface called
window.msPerformance.timing. Following convention, we use a vendor prefix (ms) on the namespace because the spec is under development. There are no other implementations yet, and therefore no interoperability with other browsers. This interface captures key timing information about the load of the root document with sub-millisecond accuracy, which is immediately available from the DOM once the page had loaded.
window.msPerformance.timing
interface MSPerformanceTiming{ readonly attribute unsigned longlong navigationStart; readonly attribute unsigned longlong fetchStart; readonly attribute unsigned longlong unloadStart; readonly attribute unsigned longlong unloadEnd; readonly attribute unsigned longlong domainLookupStart; readonly attribute unsigned longlong domainLookupEnd; readonly attribute unsigned longlong connectStart; readonly attribute unsigned longlong connectEnd; readonly attribute unsigned longlong requestStart; readonly attribute unsigned longlong requestEnd; readonly attribute unsigned longlong responseStart; readonly attribute unsigned longlong responseEnd; readonly attribute unsigned longlong domLoading; readonly attribute unsigned longlong domInteractive; readonly attribute unsigned longlong domContentLoaded; readonly attribute unsigned longlong domComplete; readonly attribute unsigned longlong loadStart; readonly attribute unsigned longlong loadEnd; readonly attribute unsigned longlong firstPaint; readonly attribute unsigned longlong fullyLoaded; }
For the first time, web developers can accurately understand how long it takes to load their page on their customer’s machines. They have access to when the end-user starts navigation (
navigationStart), the network latency related to loading the page (
responseEnd - fetchStart), and the elapsed time to load the page within the browser.
Developers can use this information to adapt their applications at runtime for maximum performance, and they can use their favorite serialization interface to package these timings and store them on the server to establish performance trends.
With JSON, this would look something like this:
JSON.Stringify(window.msPerformance);
Another useful feature of
window.msPerformance is the ability to only query for the elapsed time taken in important time phases of loading the document called
timingMeasures.
window.msPerformance.timingMeasures
interface MSPerformanceTimingMeasures{ readonly attribute unsigned longlong navigation; readonly attribute unsigned longlong fetch; readonly attribute unsigned longlong unload; readonly attribute unsigned longlong domainLookup; readonly attribute unsigned longlong connect; readonly attribute unsigned longlong request; readonly attribute unsigned longlong response; readonly attribute unsigned longlong domLoading; readonly attribute unsigned longlong domInteractive; readonly attribute unsigned longlong domContentLoaded; readonly attribute unsigned longlong domComplete; readonly attribute unsigned longlong load; readonly attribute unsigned longlong firstPaint; readonly attribute unsigned longlong fullyLoaded; }
Simply access
window.msPerformance.timingMeasures.navigation after the page has been loaded and you have the time taken to perform the navigation to the loaded document.
Finally, the
window.msPerformance.navigation interface contains information such as the type of navigation and additional network activity that occurred on the page to help describe the overall navigation experience.
window.msPerformance.navigation
interface MSPerformanceNavigation{ const unsigned short NAVIGATION = 0; const unsigned short RELOAD_BACK_FORWARD = 1; readonly attribute unsigned longlong type; readonly attribute unsigned longlong redirectedCount; readonly attribute unsigned longlong uniqueDomains; readonly attribute unsigned longlong requestCount; readonly attribute unsigned longlong startTime; }
Let’s look at it in action
On the IE9 Test Drive site, you can try the
window.msPerformance Test Drive demo. There you see a visualization of the time to load the demo page as shown below.
In this example, the overall navigation took 111ms to go from when the link is clicked to the time the contents are loaded within the platform preview.
Check it out!
Everything described here is available now in the third platform preview. Check it out at and try out the
window.msPerformance Test Drive demo. This interface is a prototype of a working draft. The API may change, but we want to release this early so that developers can begin to use the API and provide feedback. Please give
window.msPerformance interface a try and let us know what you think by providing feedback through the Connect.
Anderson Quach
Program Manager
Edit 6/29 – correction in sentence describing demo page load time. Overall navigation took 111ms, not 72ms.
If you're interested in setting good examples for other developers, that timing code should really be
(new Date()).getTime()
Very nice! This is something we the devlopers have needed for a loooong time! I'm really looking forward to IE9. Can you say something about when you think IE9 will be ready? 🙂
What does the firstPaint process stand for?
hAI: Maybe when the render starts.
IETeam: This is a very usefull feature! Are you planing to standardize this in BOM? Hope other browsers will implement this feature as well with same(!) interface.
It is a great idea. How about a memory and processor profiler too?
Performance is good, but despite what IE touts, it's HTML5 support in the previews is still rather pathetic in comparison to Webkit or Gecko.
Last I checked, the Firefox nightly got 199/300, and Webkit got 220/300. IE is still not to 100, last I checked.
Maybe my morning coffee hasn't kicked in yet, but where does that 72ms come from? Shouldn't it be 111ms?
This system is absolutely fantastic. I don't expect it to come from Microsoft, but I would absolutely love to see someone explain what all of the timings mean and provide recommendations on how to improve times for various configurations (classic LAMP stack, IIS, etc.)
Additionally, none of my comments seem to be showing up in Firefox. Do they need to be approved? Can the system at least acknowledge that somehting was sent and that it needs that or something? I keep thinking the system failed. What is up with that?
@Timothy J Warren
html5test page has several issues. For instance it portraits WebGL as part of HTML5 which is it isn't. It isn'tr even a W3C spec but a private initiative.
Great!
Can this be submitted as a standard that other browser would support? I would be great to compare timings from browser to browser. I wonder what Steve Souders would have to say…
@Jean-Philippe– As mentioned in the post itself, the Web Timing spec is in the W3C. And as he said at Velocity, Steve is very happy to see this in IE9.
These measurements are an excellent development.
Now, I'm not sure where to log this (does this belong in IE bugs?) but if I log out of MSDN, I get a message telling me that to finish signing out, I must "try clearing all of your browser cookies, and then close all browser windows"! Now that is absolutely ludicrous: why I should I have to lose all my cookies and close all my browser windows, just to log out of MSDN? Similarly, if I log out of my bank, I get a message telling me to close all my browser windows (which, obviously, is a hugely inconvenient thing for me to have to do – especially if this era of multi-tabbed windows).
Shouldn't IE have a feature that allows you to close the session(s) belonging to a particular website without having to close all browser windows (and definitely without having to clear all sites' cookies)?
With all the speed improvements in IE9 and other competing browsers, the performance range is going to vary wildly depending on the browser, the OS and/or the device. If we are to abide to your commendable "same markup" drive, and renounce any sort of browser detection, it's hard to risk exploiting all the capabilities of IE9 if this might expose some of our users to a bad experience (like some 1FPS animation we get from some examples on the test drive page).
It would be useful to have some kind of performance index (à la Windows) so we can either tone down animations and effects to a usable level or, as a last resort, warn the user that the page might be unusable on their browser/platform/hardware. Is there any work or standard being made on that front? If not, what approach would you recommend?
@MarioCossi: Don't forget that performance might suddenly decline because of background tasks or energy-saving throttling. The best way to go is to build scalable applications.
@Brian LePore: Yes, that was an editing mistake based on an earlier version of this post. The proper value is 111ms not 72ms.
Excellent work! And great to see Internet Explorer take the lead in a specific area instead of lagging behind! 🙂
This will result in more accurate <a href="stevesouders.com/…/a> measurements and also more <em>extensive</em> <a href="wimleers.com/…/master-thesis-proposal-web-performance-optimization-analytics">my master thesis: 'Web Performance Optimization: Analytics'</a>.
Those who are interested, feel free to <a href="wimleers.com/contact">contact me</a>!
And thanks again for this tremendous step forward, IE team! 🙂
Ok, so apparently this blog doesn't work very well. No instructions on commenting imply that simple HTML is allowed most of the time. But not here. Here's my comment again:
Excellent work! And great to see Internet Explorer take the lead in a specific area instead of lagging behind! 🙂
This will result in more accurate Episodes [1] measurements and also more *extensive* my master thesis, which is titled "Web Performance Optimization: Analytics" [2].
Those who are interested, feel free to contact me [3]!
And thanks again for this tremendous step forward, IE team! 🙂
[1] stevesouders.com/episodes
[2] wimleers.com/…/master-thesis-proposal-web-performance-optimization-analytics
[3]
In IE9 will it remove flash support? And what about VP8 codec? Is IE 9 having a homepage protection or will it alerts on the default homepage change, by different programs/viruses/worms??? One important thing is that the toolbars are creating huge problems for the browser and to the system. There should be security system in installing the toolbars. The security may be like the driver signing and security certificates. Please the remove the setting to "remembering the username and passwords on forms". This setting is harmful to common user. Remembering form data may be useful but it is not safe to remember the password.
OK, thanks for the new development.
Hoping better security and a speedy browser (IE9).
bcdalai
@bcdalai: No, IE9 will not remove support for browser add-ons like Flash. IE9 will not ship with a VP8/WebM codec but if one is installed the VIDEO tag can use it. If your computer is compromised by a "virus/worm" then having homepage protection won't help you (if you're running malicious code on your computer, it's not your computer anymore). Non-virus programs which violate your preferences by changing your homepage will typically be blocked by Windows Defender and/or IE's "Bad add-on" blocker. Any user who wants to disable saving of passwords can easily do so using the appropriate checkbox; administrators can do so using Group Policy. For most users, the convenience outweighs the risk.
EricLaw[MSFT]
I was wondering if you guys will link to a VP8/WebM codec once you guys show off IE9 beta.
The VP8 codec is terribly inefficient and is not a standard.
Please support the WMV-HD/VC-1 standard codec which is at least as efficient and has the best decoding footprint so that it can be easily played on mobile devices.
Also I request you support the WMA-Pro 10.x audio codec as it is an highly efficient codec.
Supporting Microsofts own codecs would respect your customers that invested in your technologie.
VP8 as released by Google requires 50% more data for the same quality video compared to h.264 main profile and the codec perfoemcnace is even slower. That mean the VP8 is a terrible waste of bandwith and storage. Microsoft should not support putting some inferior and non standardized codec over it's own formats.
hAl, as much sense as your post may make, Microsoft has explained what they're going to do in the codec space (h264, WebM only if installed), and they're not going to change that plan now. They're only "supporting WebM if installed" in the hope that somebody (aka Google) would be stupid enough to ship that codec and subsequently get sued for billions.
@Not-A-Democracy
That still leaves a big question why Microsoft is not supporting the formats tehy devloped and that they are using in a lot of their existing software and for which a lot of their customers would like support in the browser as well a lot more than they would some fairly inferior non standardized codec like VP8.
@hAl
Well, since Windows has built-in codecs for those formats, IE9 will be able to play them…or am I wrong ?
Please post a memory consumption graph for each of the page events in your test. Browsers memory consumption affects performance from URL request to viewing the page especially when you have multiple tabs open.
@Aethec
De IE team has not indicated that would be the case.
@hAl: the IE team has been touting "Same Markup" left and right (which, for them, includes code in general: markup, script…), interoperability and so on, and you're proposing that they support codecs that other browsers or OSes won't be able to support? Awesome idea! To get very bad press, that is. Something IE can't afford anymore.
@Stifu
Many companies already publish their video in WMV/VC-1 (an official standard) and would like to continue doing so.
They might use them for internal use or for target groups that have no problem with WMV video.
HTML 5 test (300 Full Test):
Chrome 6.0.447.0 -> 219 / 300 (+ 10 bonus points)
Chrome 5.0.375.86.Final -> 197 / 300 (+ 7 bonus points)
Safari 5.0 -> 165 / 300
Opera 10.60 -> 159 / 300 (+ 7 bonus points)
Firefox 3.6.6 -> 139 / 300 (+ 4 bonus points)
IE 9 P.3 -> 84 / 300 (+ 1 bonus points)
IE 8.0 -> 37 / 300
@Ali
That was already discussed before. The "HTML5 Test" is not testing any kind of standard compliance. (e.g. WebGL is not a standard, but included in the test…)
@Aethec:
To be fair, WebGL is under the heading "Related Specifications".
@Wurst
Several W3C specifications are related to HTML5 and state so in the introduction of the W3C specifications but WebGL is not one of them
Please,
Form validator:…/common-input-element-attributes.html
Input element type:…/the-input-element.html
Section elements:…/semantics.html
Geolocation:
dev.w3.org/…/spec-source.html
Web SQL Database:…/webdatabase
Geolocation API is only really usefull for mobile browsers on devices with gps capabilities is it not?
A mobile browser which IE9 is not planned to be.
But if Windows phone in the future gets based on an IE9 version than geolocation API might be usefull.
Geolocation is also potentially useful on netbooks/laptops, and GPS capability is only needed if you need a very accurate position. A lot of the potential uses for geolocation work fine with the less accurate location worked out by services like Google Location Service. | https://blogs.msdn.microsoft.com/ie/2010/06/28/measuring-web-page-performance/ | CC-MAIN-2017-09 | en | refinedweb |
Hi guys,
I'm working on this problem I've been struggling with for a while now. I'm still confused about parameters and I'm getting all these error messages, saying that a lot of my variables are undefined. I'm sorry, I know this probably looks like a mess right now, but if anyone could help me out as to what I need to change around to get this working, I would be so appreciative.
I'm also not sure if I need the prototypes?
The assignment is in the comments at the top:
// Write a program that can be used to calculate the federal tax. The tax calculated as follows:
// For single people, the standard exemption is $4000; for married people, the standard exemption
// is $7000. A person can also put up to 6% of his or her gross standard income in a pension plan.
// The tax rates are as follows: If the taxable income is
// 1) Between $0 and $15000, the tax rate is 15%
// 2)between $15001 and $40000, the tax is $2250 plus 25% of the taxable income over $15000
// 3)Over $40,000, the tax is $8460 plus 35% of the taxable income over $40000
// Prompt the user to enter the following information:
// 4)Martial status
// 5)If the marital status is "married", ask for the number of children under the age of 14
// 6)Gross salary(if the martial status is "married" and both spouses have income, enter the combined salary.)
// 7) Percentage of gross income contributed to a pension fund.
//The program must consist of at least the following functions:
//a) function getData: this function asks the user to enter the relevant data.
//b) function taxAmount: this function computes and returns the tax owned.
//To calculate the taxable income, subtract the sum of the standard exemption, the amount contributed
//to a pension plan, and the personal exemption, which is $1500 per person.
#include <iostream> #include <string> #include <iomanip> using namespace std; void getData(char marital, int numChild, int& exempt, int& noOfPeople, double& groSalary, double& penAmt); double taxAmount(double taxIncome, int perExempt, double taxRate); int main() { double groSalary; //variable for gross salary double penAmt; //variable for percent contributed to pension plan int exempt; //variable for standard exemption int noOfPeople; //variable for number of people double taxIncome; //variable for taxable income double taxRate; //variable for federal tax amount owed getData(char marital, int numChild, int& exempt, int& noOfPeople, double& groSalary, double& penAmt); double taxAmount(double, int, double); cout << "Your federal tax owed is: " << taxRate << endl; return 0; } void getData(char marital, int numChild, int& exempt, int& noOfPeople, double& groSalary, double& penAmt) { char marital; //variable for marital status int numChild; //variable for the number of children under 14 cout << fixed << showpoint; cout << setprecision(2); cout << "Enter your marital status: 'M' for Married or 'S' for Single: "; cin >> marital; cout << endl; if (marital == 'M' || marital == 'm') { cout << "Enter number of children under the age of 14 years: "; cout <<endl; cin >> numChild; exempt = 7000; noOfPeople = 2 + numChild; } else if (marital == 'S' || marital == 's') { exempt = 4000; numChild = 0; noOfPeople = 1; } cout << "Enter gross salary. (Enter combined salary for both spouses"; cout << "if married): "; cout << endl; cin >> groSalary; cout << "Enter the percentage of your gross income which you have"; cout << " contributed to a pension fund (Only enter the amount if 6%"; cout << " or less of your combined gross income: "; cout << endl; cin >> penAmt; if (penAmt > 6) { cout << "You may only enter a percentage which is greater or equal"; cout << " to 6. Enter the percentage of your gross income which you have"; cout << " contributed to a pension fund. (Only enter the amount if 6%"; cout << " or less of your combined gross income: "; cout << endl; cin >> penAmt; } } double taxAmount(double taxRate, int perExempt, int noOfPeople, double taxRate) { double taxRate; //variable to store taxRate double taxAmt; //variable to store total tax amount int perExempt //variable for personal Exemptions taxRate = 0; perExempt = (noOfPeople * 1500) + exempt; taxIncome = groSalary - (groSalary * (penAmt * .01)) - perExempt); if (taxIncome <= 15000) {taxRate = .15 * taxIncome; } else if (taxIncome > 15000 && taxIncome <= 40000) {taxRate = ((taxIncome - 15000) * .25) + 2250;} else{ taxRate = ((taxIncome - 40000) * .35) + 8460; } return taxRate; } | https://www.daniweb.com/programming/software-development/threads/120888/c-beginner-struggling-with-parameters | CC-MAIN-2017-09 | en | refinedweb |
I am using irb/ruby1.9.1.
def isUppercase
self>= ?A && self<= ?Z
end
class String
def abbreviate
abbr = ""
each_byte do |c|
if c.isUppercase
abbr += c.chr
end
end
abbr
end
end
"Unidentified Flying Object".abbreviate
irb(main):044:0> load("abbrevi.rb")
=> true
irb(main):045:0> "Unidentified Flyng Object".abbreviate ArgumentError: comparison of Fixxnum with String failed
from C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:4:in >=' from
C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:4:in isUppercase' from
C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:12:in block in abbreviate' from
C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:11:in each_byte' from
C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:11:in abbreviate' from (irb):45 from
C:/Ruby192/bin/irb:12:in <main>
Try this:
class Fixnum def isUppercase self.chr >= ?A && self.chr <= ?Z #note use of `chr` to avoid error that occurs when #comparing a Fixnum to a String end end class String def abbreviate abbr = "" each_byte do |c| if c.isUppercase abbr += c.chr.to_s #note this usage as well end end abbr end end
Note that you cannot add a string to a number, or compare, so the below will generate errors:
irb> 1 >= "A" # => ArgumentError: comparison of Fixnum with String failed
UPDATE: @coreyward's answer is the better way to do what you're doing overall, but my answer is only pointing out how to fix your code and the reason for you error. A yet better way might be to use Regular Expressions. | https://codedump.io/share/qOwz1CMsvuwg/1/what-is-wrong-my-code-trying-to-abbreviate | CC-MAIN-2017-09 | en | refinedweb |
.
Setup SSH and sudo
I started with a blank application, and "capified" it. If you don't have Capistrano installed, install it via RubyGems.
sudo gem install capistrano --no-ri --no-rdoc rails slicehost cd slicehost/ capify .
Open up config/deploy.rb and start configuring it as you would for any other Rails application. Just make sure you have the same "default_run_options" line as I do. Here's what mine looks like:
default_run_options[:pty] = true set :application, "slicehost" set :repository, "git://github.com/mig/cthulhu.git" set :deploy_to, "/home/deploy/#{application}" set :user, "deploy" set :scm, :git role :app, "myslice.com" role :web, "myslice.com" role :db, "myslice.com", :primary => true
I've listed "deploy" as my user. This is important – the only bit of manual configuration we will do is to create this user account.
Now I will ssh into my brand new slice, change my password, and create the "deploy" user:
ssh myslice.com -l root passwd adduser deploy
The "deploy" user should get sudo privileges. To make things easier for this example, don't require a password. While this is fine for my DMZ-like slice, you should not leave the NOPASSWD flag on your user after finishing – you have been warned.
visudo
Add this line to the bottom:
deploy ALL=(ALL) NOPASSWD: ALL
One last thing, add your public key to the deploy user's authorized_keys file:
On your local machine:
scp ~/.ssh/id_rsa.pub deploy@myslice.com: ssh myslice.com -l deploy
On your slice:
mkdir .ssh cat id_rsa.pub >> .ssh/authorized_keys rm id_rsa.pub chmod 600 .ssh/authorized_keys chmod 700 .ssh
Now on to the fun stuff...
Installing the Basics
Open up config/deploy.rb and create a custom namespace for our tasks:
namespace :slicehost do # tasks go here end
I'm going to use Ubuntu's apt-get to install some of the basic necessities. Put these tasks in our :slicehost namespace. I've included tasks for git and sqlite3 here, you might want something different like subversion and postgres. Look at the attached file at the end for more examples.
desc "Update apt-get sources" task :update_apt_get do sudo "apt-get update" end desc "Install Development Tools" task :install_dev_tools do sudo "apt-get install build-essential -y" end desc "Install Git" task :install_git do sudo "apt-get install git-core git-svn -y" end desc "Install SQLite3" task :install_sqlite3 do sudo "apt-get install sqlite3 libsqlite3-ruby -y" end
To run any of these, drop to your shell and issue a cap command:
cap slicehost:update_apt_get
To see a list of available cap commands, including our custom ones:
cap -T
Install the Rails Stack
The next example is only a little more complex, the thing you should note is the use of sudo within the command string itself. Include the && between commands if you need a command to run in a directory other than the default.
Let's install Ruby and Rails:
desc "Install Ruby, Gems, and Rails" task :install_rails_stack do [ "sudo apt-get install ruby ruby1.8-dev irb ri rdoc libopenssl-ruby1.8 -y", "mkdir -p src", "cd src", "wget", "tar xvzf rubygems-1.0.1.tgz", "cd rubygems-1.0.1/ && sudo ruby setup.rb", "sudo ln -s /usr/bin/gem1.8 /usr/bin/gem", "sudo gem install rails --no-ri --no-rdoc" ].each {|cmd| run cmd} end
Just run the new installer task and you should be ready to go:
cap slicehost:install_rails_stack
That was easy! We've got a full Rails stack running on our slice. From here we could go a few different routes. I've been eager to try the new mod_rails Passenger out, so let's set that up!
Apache and Passenger (aka mod_rails)
First, we need to install Apache:
desc "Install Apache" task :install_apache do sudo "apt-get install apache2 apache2.2-common apache2-mpm-prefork apache2-utils libexpat1 apache2-prefork-dev libapr1-dev -y" end
And now the Passenger install. This part is trickiest, because it requires our input on the remote server. This is where the "default_run_options" setting comes in handy.
desc "Install Passenger" task :install_passenger do run "sudo gem install passenger --no-ri --no-rdoc" input = '' run "sudo passenger-install-apache2-module" do |ch,stream,out| next if out.chomp == input.chomp || out.chomp == '' print out ch.send_data(input = $stdin.gets) if out =~ /enter/i end end
Here's what's happening: the run command is passed a block, the block is telling the run command to step through all output while printing everything to the screen. Any time the words "Enter" or "ENTER" are encountered in the output, the execution waits for our input. Any input is then redirected back into the Passenger installer running on the remote server.
So, we've finished installing all the software we need (for the moment). All that's needed is to configure Apache to use Passenger, and to set up a virtual host for our application.
Apache Configuration
Here is the Apache configuration, taken directly from the output of the Passenger install:
desc "Configure Passenger" task :config_passenger do passenger_config =<<-EOF EOF put passenger_config, "src/passenger" sudo "mv src/passenger /etc/apache2/conf.d/passenger" end desc "Configure VHost" task :config_vhost do vhost_config =<<-EOF <VirtualHost *:80> ServerName blog.pggbee.com DocumentRoot #{deploy_to}/public </VirtualHost> EOF put vhost_config, "src/vhost_config" sudo "mv src/vhost_config /etc/apache2/sites-available/#{application}" sudo "a2ensite #{application}" end
That looks more complicated that it really is. The trick to these tasks is the "put" method – it takes a string and a remote filename and uploads the contents of the string to the file on the remote server.
This allows us to generate the configurations locally, create them on the remote server, and then use sudo to move them into their proper place.
That's it. Our slice is ready for us to deploy as normal. I am not going to cover that here, as it's been covered elsewhere and in much more depth than I can go into here.
Wrapping Up
Once you've created all your custom tasks and verify that they work, it's a good idea to put them all together in one setup method (I use :setup_env in my :slicehost namespace). All I have to do is run the task, sit back, and watch:
cap slicehost:setup_env
Try it out for yourself. Download the entire deploy.rb.txt file, remove the .txt extension and drop it into your project. | https://www.viget.com/articles/building-an-environment-from-scratch-with-capistrano-2 | CC-MAIN-2017-09 | en | refinedweb |
Check buttons are used to be able to select which task to be edited/deleted. Unless someone comes up with something easier/simple i will stick with this.
I have already started working on it. Its not much but this is what i have til now:
- Code: Select all
import sys
from Tkinter import *
mGui = Tk()
mGui.geometry("450x450+400+100")
mGui.title("Task manager")
def inputl():
ltext = firstT.get()
label1 = Label(mGui,text=ltext).pack()
return
firstT=StringVar()
message = "Enter task"
Label(mGui, text=message).pack()
entry1= Entry(mGui, textvariable=firstT).pack()
Button1 = Button(mGui, text='OK', command=inputl).pack()
Button(mGui, text="Add", command=inputl).pack(side=TOP, ipadx=50)
Button(mGui, text="Edit").pack(side=TOP, ipadx=51)
Button(mGui, text="Delete").pack(side=TOP, ipadx=44)
mGui.mainloop()
I would appreciate it if I could get some help to finish this program ASAP. Thanks a lot ! | http://www.python-forum.org/viewtopic.php?f=12&t=3277 | CC-MAIN-2017-09 | en | refinedweb |
I wrote “what’s up with containers: Docker and rkt” a while ago. Since then I have learned a few new things about containers! We’re going to talk about running containers in production, not on your laptop for development, since I’m trying to understand how that works in September 2016. It’s worth noting that all this stuff is moving pretty fast right now.
The concerns when you run containers in production are pretty different from running it on a laptop – I very happily use Docker on my laptop and I have no real concerns about it because I don’t care much if processes on my laptop crash like 0.5% of the time, and I haven’t seen any problems.
Here are the things I’ve learned so far. I learned many of these things with @grepory who is the best. Basically I want to talk about what some of the things you need to think about are if you want to run containers, and what is involved in “just running a container” :)
At the end I’m going to come back to a short discussion of Docker’s current architecture. (tl;dr: @jpetazzo wrote a really awesome gist)
Docker is too complicated! I just want to run a container
So, I saw this image online! (comes from this article)
And I thought “that rkt diagram looks way easier to operate in production! That’s what I want!”
Okay, sure! No problem. I can use
runC! Go to runc.io, follow the
direction, make a
config.json file, extract my container into a tarball, and now I can
run my container with a single command. Awesome.
Actually I want to run 50 containers on the same machine.
Oh, okay, that’s pretty different. So – let’s say all my 50 containers share a bunch of files (shared libraries like libc, Ruby gems, a base operating system, etc.). It would be nice if I could load all those files into memory just once, instead of 3 times.
If I did this I could save disk space on my machine (by just storing the files once), but more importantly, I could save memory!
If I’m running 50 containers I don’t want to have 50 copies of all my shared libraries in memory. That’s why we invented dynamic linking!
If you’re running just 2-3 containers, maybe you don’t care about a little bit of copying. That’s for you to decide!
It turns out that the way Docker solves this is with “overlay filesystems” or “graphdrivers”. (why are they called graphdrivers? Maybe because different layers depend on each other like in a directed graph?) These let you stack filesystems – you start with a base filesystem (like Ubuntu 14.04) and then you can start adding more files on top of it one step at a time.
Filesystem overlays need some Linux kernel support to work – you need to use a filesystem that supports them. The Brutally Honest Guide to Docker Graphdrivers by the fantastic Jessie Frazelle has a quick overview. overlayfs seems to be the most normal option.
At this point, I was running Ubuntu 14.04. 14.04 runs a 3.13 Linux kernel! But to use overlayfs, you need a 3.18 kernel! So you need to upgrade your kernel. That’s fine.
Back to
runC.
runC does not support overlay filesystems. This is an intentional design choice – it lets runC run on older kernels, and lets you separate out the concerns. But it’s not super obvious right now how to use runC with overlay filesystems. So what do I do?
I’m going to use rkt to get overlay filesystem support
So! I’ve decided I want overlay filesystem support, and gotten a Linux kernel newer than 3.18. Awesome. Let’s try rkt, like in that diagram! It lives at coreos.com/rkt/
If you download
rkt and run
rkt run docker://my-docker-registry/container, This
totally works. Two small things I learned:
--net=host will let you run in the host network namespace
Network namespaces are one of the most important things in container land. But if you want to run containers using as few new things as possible, you can start out by just running your containers as normal programs that run on normal ports, like any other program on your computer. Cool
--exec=/my/cool/program lets you set which command you want rkt to execute inside the image
systemd: rkt will run a program called
systemd-nspawn as the init (PID 1) process inside your container. This is because it can be bad to run an arbitrary process as PID 1 – your process isn’t expecting it and will might react badly. It also run some systemd-journal process? I don’t know what that’s for yet.
The systemd journal process might act as a syslog for your container, so that programs sending logs through syslog end up actually sending them somewhere.
There is quite a lot more to know about rkt but I don’t know most of it yet.
I’d like to trust that the code I’m running is actually my code
So, security is important. Let’s say I have a container registry. I’d like to make sure that the code I’m running from that registry is actually trusted code that I built.
Docker lets you sign images to verify where they came from. rkt lets you run Docker images. rkt does not let you check signatures from Docker images though! This is bad.
You can fix this by setting up your own rkt registry. Or maybe other things! I’m going to leave that here. At this point you probably have to stop using Docker containers though and convert them to a different format.
Supervising my containers (and let’s talk about Docker again)
So, I have this Cool Container System, and I can run containers with overlayfs and I can trust the code I’m running. What now?
Let’s go back to Docker for a bit. So far I’ve been a bit dismissive about Docker, and I’d like to look at its current direction a little more seriously. Jérôme Petazzoni wrote an extremely informative and helpful discussion about how Docker got to its architecture today in this gist. He says (which I think is super true) that Docker’s approach to date has done a huge amount to drive container adoption and let us try out different approaches today.
The end of that gist is a really good starting point for talking about how “start new containers” should work.
Jérôme very correctly says that if you’re going to run containers, you need a way to tell boxes which containers to run, and supervise and restart containers when they die. You could supervise them with daemontools, supervisord, upstart, or systemd, or something else!
“Tell boxes which containers to run” is another nontrivial problem and I’m not going to talk about it at all here. So, back to supervision.
Let’s say you use systemd. Then that’ll look like (from the diagram I posted at the top):
- systemd -+- rkt -+- process of container X | \- other process of container X +- rkt --- process of container Y \- rkt --- process of container Z
I don’t know anything about systemd, but it’s pretty straightforward to tell daemontools “hey, here’s a new process to start running, it’s going to run a container”. Then daemontools will restart that container process if it crashes. So this is basically fine.
My understanding of the problem with Docker in production historically is that – the process that is responsible for this core functionality of process supervision was the Docker engine, but it also had a lot of other features that you don’t necessarily want running in production.
The way Docker seems to be going in the future is something like: (this diagram is from jpetazzo’s gist above)
- init - containerd -+- shim for container X -+- process of container X | \- other process of container X +- shim for container Y --- process of container Y \- shim for container Z --- process of container Z
where containerd is a separate tool, and the Docker engine talks to containerd but isn’t as heavily coupled to it. Right now containerd’s website says it’s alpha software, but they also say on their website that it’s used in current versions of Docker, so it’s not totally obvious what the state is right now.
the OCI standard
We talked about how
runC can run containers just fine, but cannot do overlay filesystems or fetch + validate containers from a registry. I would be remiss if I didn’t mention the OCID project that @grepory told me about last week, which aims to do those as separate components instead of in an integrated system like Docker.
Here’s the article: Red Hat, Google Engineers Work on a Way for Kubernetes to Run Containers Without Docker .
Today there’s skopeo which lets you fetch and validate images from Docker registries
what we learned
here’s the tl;dr:
- you can run Docker containers without Docker
- runC can run containers… but it doesn’t have overlayfs
- but overlay filesystems are important!
- rkt has overlay filesystem support.
- you need to start & supervise the containers! You can use any regular process supervisor to do that.
- also you need to tell your computers which containers to run
- software around the OCI standard is evolving but it’s not there yet
As far as I can tell running containers without using Docker or Kubernetes or anything is totally possible today, but no matter what tools you use it’s definitely not as simple as “just run a container”. Either way going through all these steps helps me understand what the actual components of running a container are and what all these different pieces of software are trying to do.
This landscape is pretty confusing but I think it’s not impossible to understand! There are only a finite number of different pieces of software to figure out the role of :)
If you want to see more about running containers from scratch, see Cgroups, namespaces, and beyond: what are containers made from? by jpetazzo. There’s a live demo of how to run a container with 0 tools (no docker, no rkt, no runC) at this point in the video which is super super interesting.
Thanks to Jérôme Petazzoni for answering many questions and to Kamal Marhubi for reading this. | https://jvns.ca/blog/2016/10/02/i-just-want-to-run-a-container/ | CC-MAIN-2017-09 | en | refinedweb |
I have a computer with an Iwill VD133 motherboard doingUSB-to-PS/2 keyboard emulation (built into the chipset somewhere)for a BTC 7932M USB keyboard. Under this configuration, theSETLEDS command in atkbd_probe fails (the first atkbd_sendbytein atkbd_command fails), but the keyboard otherwise works ifthat failure is ignored. I noticed this when my keyboard stopped working in 2.5.32.I have verified that 2.5.31 (and probably all kernels before it)also do not set the LEDs on my USB-emulating-PS/2 keyboard. I cannot say whether the problem occurs with other USBkeyboards because I don't have one handy. One cannot run the USB keyboard "natively" via Linux USB on thismotherboard because the BIOS does not seem to set an IRQ line for the USBcontroller. I've tried booting with "pci=biosirq", and I think I've triedall the relevant BIOS menu options, and I'm running the latest BIOS,and the VD133 product has been terminated. So the patch does seem to be"necessary" to support some configurations, at least for now.--."--- linux-2.5.33/drivers/input/keyboard/atkbd.c 2002-08-31 15:05:31.000000000 -0700+++ linux/drivers/input/keyboard/atkbd.c 2002-09-09 06:29:04.000000000 -0700@@ -359,13 +359,13 @@ #endif /*- * Next we check we can set LEDs on the keyboard. This should work on every- * keyboard out there. It also turns the LEDs off, which we want anyway.+ * Turn off LEDs. This command fails on at least a BTC 7932M USB keyboard+ * connected to an Iwill VD133 motherboard that is configured to emulate+ * a PS/2 keyboard via USB. */ param[0] = 0;- if (atkbd_command(atkbd, param, ATKBD_CMD_SETLEDS))- return -1;+ atkbd_command(atkbd, param, ATKBD_CMD_SETLEDS); /* * Then we check the keyboard ID. We should get 0xab83 under normal conditions. | https://lkml.org/lkml/2002/9/9/92 | CC-MAIN-2017-09 | en | refinedweb |
Friday
Dec092016
Stuff The Internet Says On Scalability For December 9th, 2016
Hey, it's HighScalability time:
Here's a 1 TB hard drive in 1937. Twenty workers operated the largest vertical letter file in the world. 4000 SqFt. 3000 drawers, 10 feet long. (from @BrianRoemmele)
If you like this sort of Stuff then please support me on Patreon.
- 98%~ savings in green house gases using Gmail versus local servers; 2x: time spent on-line compared to 5 years ago; 125 million: most hours of video streamed by Netflix in one day; 707.5 trillion: value of trade in one region of Eve Online; $1 billion: YouTube's advertisement pay-out to the music industry; 1 billion: Step Functions predecessor state machines run per week in AWS retail; 15.6 million: jobs added over last 81 months;
- Quotable Quotes:
- Gerry Sussman~ in the 80s and 90s, engineers built complex systems by combining simple and well-understood parts. The goal of SICP was to provide the abstraction language for reasoning about such systems...programming today is more like science. You grab this piece of library and you poke at it. You write programs that poke it and see what it does. And you say, ‘Can I tweak it to do the thing I want?
- @themoah: Last year Black Friday weekend: 800 Windows servers with .NET. This year: 12 Linux servers with Scala/Akka. #HighScalability #Linux #Scala
- @swardley: If you're panicking over can't find AWS skills / need to go public cloud - STOP! You missed the boat. Focus now on going serverless in 5yrs.
- @jbeda: Nordstrom is running multitenant Kubernetes cluster with namespace per team. Using RBAC for security.
- Tim Harford: What Brailsford says is, he is not interested in team harmony. What he wants is goal harmony. He wants everyone to be focused on the same goal. He doesn’t care if they like each other and indeed there are some pretty famous examples of people absolutely hating each other.
- @brianhatfield: SUB. MILLISECOND. PAUSE. TIME. ON. AN. 18. GIG. HEAP. (Trying out Go 1.8 beta 1!)
- haberman: If you can make your system lock-free, it will have a bunch of nice properties: - deadlock-free - obstruction-free (one thread getting scheduled out in the middle of a critical section doesn't block the whole system) - OS-independent, so the same code can run in kernel space or user space, regardless of OS or lack thereof
- Neil Gunther: The world of performance is curved, just like the real world, even though we may not always be aware of it. What you see depends on where your window is positioned relative to the rest of the world. Often, the performance world looks flat to people who always tend to work with clocked (i.e., deterministic) systems, e.g., packet networks or deep-space networks.
- @yoz: I liked Westworld, but if I wanted hours of watching tech debt and no automated QA destroy a virtual world, I’d go back to Linden Lab
- @adrianco: I think we are seeing the usual evolution to utility services, and new higher order (open source) functionality emerges /cc @swardley
- Neil Gunther: a buffer is just a queue and queues grow nonlinearly with increasing load. It's queueing that causes the throughput (X) and latency (R) profiles to be nonlinear.
- Juho Snellman: I think [QUIC] encrypting the L4 headers is a step too far. If these protocols get deployed widely enough (a distinct possibility with standardization), the operational pain will be significant.
- @Tobarja: "anyone who is doing microservices is spending about 25% of their engineering effort on their platform" @jedberg
- @cdixon: 2016 League of Legends finals: 43M viewers 2016 NBA finals: 30.8M viewers
- @mikeolson: 7 billion people on earth; 3 billion images shared on social media every day. @setlinger at #StrataHadoop
- @swardley:.
- Jakob Engblom: hardware accelerators for particular common expensive tasks seems to be the right way to add performance at the smallest cost in silicon area and power consumption.
- Joe Duffy: The future for our industry is a massively distributed one, however, where you want simple individual components composed into a larger fabric. In this world, individual nodes are less “precious”, and arguably the correctness of the overall orchestration will become far more important. I do think this points to a more Go-like approach, with a focus on the RPC mechanisms connecting disparate pieces
- @cmeik: AWS Lambda is cool if you never had to worry about consistency, availability and basically all of the tradeoffs of distributed systems.
- prions: As a Civil Engineer myself, I feel like people don't realize the amount of underlying stuff that goes into even basic infrastructure projects. There's layers of planning, design, permitting, regulations and bidding involved. It usually takes years to finally get to construction and even then there's a whole host of issues that arise that can delay even a simple project.
- Netflix: If you can cache everything in a very efficient way, you can often change the game.
- The Attention Merchants: One [school] board in Florida cut a deal to put the McDonald’s logo on its report cards (good grades qualified you for a free Happy Meal). In recent years, many have installed large screens in their hallways that pair school announcements with commercials. “Take your school to the digital age” is the motto of one screen provider: “everyone benefits.” What is perhaps most shocking about the introduction of advertising into public schools is just how uncontroversial and indeed logical it has seemed to those involved.
- Just how big is Netflix? The story of the tape is told in Another Day in the Life of a Netflix Engineer. Netflix runs way more than 100K EC2 instances and more than 80,000 CPU cores. They use both predictive and reactive autoscaling, aiming for not too much or too little, just the right amount. Of those 100K+ instances they will autoscale up and down 20% of that capacity everyday. More than 50Gbps ELB traffic per region. More than 25Ggps is telemetry data from devices sending back customer experience data. At peak Netflix is responsible over 37% of Internet traffic. The monthly billing file for Netflix is hundreds of megabytes with over 800 million lines of information. There's a hadoop cluster at Amazon whose only purpose is to load Netflix's bill. Netflix considers speed of innovation to be a strategic advantage. About 4K code changes are put into production per day. At peak over 125 million hours of video were streamed in a day. Support for 130 countries was added in one day. That last one is the kicker. Reading about Netflix over all these years you may have got the idea Netflix was over engineered, but going global in one day was what it was all about. Try that if you are racking and stacking.
- Oh how I miss stories that began Once upon a time. The start of so many stories these days is The attack sequence begins with a simple phishing scheme. This particular cautionary tale is from Technical Analysis of Pegasus Spyware, a very, almost lovingly, detailed account of the total ownage of the "secure" iPhone. The exploit made use of three zero-day vulnerabilities: CVE-2016-4657: Memory Corruption in WebKit, CVE-2016-4655: Kernel Information Leak, CVE-2016-4656: Kernel Memory corruption leads to Jailbreak. Do not read if you would like to keep your Security Illusion cherry intact.
- Composing RPC calls gets harder has the graph of calls and dependencies explodes. Here's how Twitter handles it. Simplify Service Dependencies with Nodes. Here's their library on GitHub. It's basically just a way to setup a dependency graph in code and have all the RPCs executed to the plan. It's interesting how parallel this is to setting up distributed services in the first place. They like it: We have saved thousands of lines of code, improved our test coverage and ended up with code that’s more readable and friendly for newcomers. Also, AWS Step Functions.
- Love posts like this. Building The Buffer Links Service. An easy to understand problem that explores multiple implementations in detail. The problem: track the number of posts containing a URL. They tried three solutions. Amazon RDS (Aurora) + Node + Redis. Problem: MySQL queries too slow with a lot of data. Elasticsearch. Problem: too expensive at scale. Redis + S3. The winner: even with 100% of production traffic, average response times stayed below one millisecond.
- Videos from SICS Software Week 2016 - Multicore Day are now available. And here's a review from Jakob Engblom. Interesting: each power of two of cores required a re-architecting and tackling a new set of problems. It seems there is a similar effect at play in large systems – maybe each power of 10 you have to rethink radically how you do things.
- Humans so clever in their iniquity. Or why interpreters can never be trusted. For two years, criminals stole sensitive information using malware hidden in individual pixels of ad banners:.
- Joe Duffy, his amazing Midori series is a true geek pleasure, dispenses the wisdom in 15 Years of Concurrency: The real big miss, in my opinion, was mobile. This was precisely when the thinking around power curves, density, and heterogeneity should have told us that mobile was imminent, and in a big way. Instead of looking to beefier PCs, we should have been looking to PCs in our pockets. Instead, the natural instinct was to cling to the past and “save” the PC business. This is a classical innovator’s dilemma although it sure didn’t seem like one at the time. And of course PCs didn’t die overnight, so the innovation here was not wasted, it just feels imbalanced against the backdrop of history. Anyway, I digress.
- Relational database still rule in this DB-Engines Ranking. #1: Oracle. #2: MySQL. #3: Microsoft SQL Server. #4: PostgreSQL. #5 MongoDB. Over the years the rankings have been remarkably stable.
- Microprocessors have so many transistors these days parts of chips must be turned off to dissipate heat. Not all the transistors can be used at the same time. This is called Dark silicon. It turns out the brain uses a similar strategy. Why? We don't know yet. Portions of the brain fall asleep and wake back up all the time:.
- BMW remotely locks a thief inside a car. What does ownership mean these days? Our things are no longer just our things. They are jointly controlled, which means they are also jointly owned.
- Instance stacking is installing multiple instances of a product on the same server. I can save a lot of money in licensing costs, but it's harder to tune performance. Rudy Panigas has some good advice on how to instance stack SQL server: Only same versions of SQL server; Properly allocate memory (MAX and MIN settings) and CPUs per instance; Have them on the same patching levels; Assign different disk per each instance.
- Videos from GTAC (Google Test Automation Conference) 2016 are now available.
- Finding similarities between texts is something required for spam detection, for example. How to calculate 17 billion similarities is an exploration of how to determine how similar recipes are to one another. It's a juicy topic. Good discussion on reddit. Here's how Google does it: Detecting Near-Duplicates for Web Crawling. jones1618 explains: The basic idea is that you generate an N-bit "feature hash" for each document (or in your case a recipe). You already have a nice feature set for that. If you numerically sort your recipes by this SimHash, more similar documents are always near each other in the sort order. The only trick is that if you have an N-bit SimHash, you need to repeat the sort for N bitwise rotations of the hash. Still calculating F hashes once for all your recipes and then sorting them N times has got to be much faster than 400M floating point multiplies of your method.
- Some interesting stats on GitHub diffs. Most are small. How we made diff pages three times faster: 81% of viewed diffs contain changes to fewer than ten files; 52% of viewed diffs contain only changes to one or two files; 80% of viewed diffs have fewer than 20KB of patch text; 90% of viewed diffs have fewer than 1000 lines of patch text.
- It turns out async scales better than sync after all. Why My Synchronous API Scaled Better Than My Asynchronous API. A good demonstration of the differences between async and sync approaches to parallelization. One observation is that with a thread pool approach you can limit the number of simultaneous requests so as not to overwhelm a target service. Firing off 200 simulatenous operations might bring a service to its knees and it could spike your memory use quite a bit and cause swapping/paging.
- Eve Online has their own monthly Economic Report. Intriguing, but there's no dang explanation! The Internet Provides. Brendan ‘Nyphur’ Drain in EVE EVOLVED: ANALYSING EVE’S NEW ECONOMIC REPORTS brings the graphs to life, explaining just of some of the intricacies of this dynamic economy. And the reddit group has extensive discussions. Fascinating how real is the virtual. Someday this is the way a democracy may govern.
- Batching requests, giving performance improvements since....forever? 10x speedup utilizing Nagle Algorithm in business application:.
- Great summary. Observations from 2016 AWS re:Invent.
- James Hamilton: Vertically-integrated networking equipment, where the ASICs, the hardware, these protocol stacks [were] supplied by single companies, is [like] the way the mainframe used to dominate servers. If you look at where the networking world is, it’s sort of where the server world was 20 or 30 years ago. It started out with, you buy a mainframe. . . and that’s it. And it comes from all one company. The networking world is the same place. And we know what happened in the server world: As soon as you chop up these vertical stacks, you’ve got companies focused on every layer, and they’re innovating together, and they’re all competing. You can get great things happening.
- Just in case you thought we were lacking for distributed queue options. Cherami: Uber Engineering's Durable and Scalable Task Queue in Go:.
- Very cool story of how AI helped solve a problem that wasn't solvable with earlier approaches. They had been trying since 2001. Deep Learning Reinvents the Hearing Aid. And it doesn't just help the hearing impaired. We'll all have super hero hearing in the bright bright future.
- Sometimes life just fits together like a jigsaw puzzle. Pieces slide together of their own accord. A while ago I read The Master of Disguise: My Secret Life in the CIA, good book BTW, which talked a lot about the crucial role make-up artistry played in the spy game. They had these amazing sounding make-up kits and I was just burning to know what looked like. And here it is: Peter Jackson and Adam Savage Open John Chambers' CIA Make-Up Kit!
- A fun list. 52 things I learned in 2016. I like the one about the Australian musicians have performed with a synthesiser controlled by a petri dish of live human neurons.
- Here's the database version of "Fast, Good or Cheap. Pick two." The SNOW theorem and latency-optimal read-only transactions. S is for Strict Serializability. N is for Non-blocking. O is for One response per read. W is for Write transactions. No, you can't have it all: in every combination of three out of the four properties is possible. You can have read-only transaction algorithms that satisfy S+O+W, N+O+W, and S+N+O.
- Would you like a better internet? BBR: Congestion-Based Congestion Control: Rethinking congestion control pays big dividends. Rather than using events such as loss or buffer occupancy, which are only weakly correlated with congestion, BBR starts from Kleinrock's formal model of congestion and its associated optimal operating point...BBR is deployed on Google's B4 backbone, improving throughput by orders of magnitude compared with CUBIC. It is also being deployed on Google and YouTube.
- An interesting List of Tech Migrations, companies that have switch technologies. Lots of switching away from X to Go. PostgreSQL and MySQL are also common switch targets.
- Wayfair with an extensive analysis of early flushing and switching to http/2: Bottom line, we got a 15-20% decrease in the metrics we care about, from early flush, 5-10% from h2.
- Programmers on hearing this just nod sagely. It's always about powers of two. Brain Computation Is Organized via Power-of-Two-Based Permutation Logic:.
- The devil is in the interaction between the details. How Complex Systems Fail: complex systems are always ridden with faults, and will fail when some of these faults conspire and cluster. In other words, complex systems constantly dwell on the verge of failures/outages/accidents.
- Oh great. Now I'm going to have nightmares. Meet the World’s First Completely Soft Robot.
- You can have your very own open source research processor: OpenPiton - an expandable manycore platform which includes RTL,thousands of tests, and implementation scripts. This work: rethinks the design of microprocessors specifically for data center use along with how microprocessors are affected by the novel economic models that have been popularized by IaaS clouds
- github/orchestrator: a MySQL replication topology management and visualization tool, allowing for: Discovery, Refactoring, Recovery.
- donnemartin/awesome-aws: A curated list of awesome AWS libraries, open source repos, guides, blogs, and other resources.
- deepmind/lab: a 3D learning environment based on id Software's Quake III Arena via ioquake3 and other open source software.
- OpenHFT: Open Source components originating from the HFT world.
- stevenringo/reinvent-2016-youtube.md: Links to YouTube recordings of AWS re:Invent sessions
- anywhichway/reasondb: A 100% native JavaScript automatically synchronizing object database: SQL like syntax, swapable persistence engines, asynchronous cursors, streaming analytics, 18 built-in plus in-line fat arrow predicates, predicate extensibility, indexed computed values, joins, nested matching, statistical sampling and more.
- Service-Oriented Sharding with Aspen: a sharded blockchain protocol designed to securely scale with increasing number of services. Aspen shares the same trust model as Bitcoin in a peer-to-peer network that is prone to extreme churn containing Byzantine participants. It enables introduction of new services without compromising the security, leveraging the trust assumptions, or flooding users with irrelevant messages.
Reader Comments (1)
Regarding "Portions of the brain fall asleep and wake back up all the time". I'm surprised that the authors draw the conclusions they do. It's as if the authors weren't aware of how cortical columns are used by the brain. See: and also | http://highscalability.com/blog/2016/12/9/stuff-the-internet-says-on-scalability-for-december-9th-2016.html | CC-MAIN-2017-09 | en | refinedweb |
get_end(3) get_end(3)
NAME
get_end, get_etext, get_edata - get values of UNIX link editor defined symbols
SYNOPSIS
#include <mach-o/getsect.h> unsigned long get_end(); unsigned long get_etext(); unsigned long get_edata();
DESCRIPTION
These routines provide a stopgap measure to programs that use the UNIX link-editor defined symbols. Use of these routines is very strongly discouraged. The problem is that any program that is using UNIX link editor defined symbols (_end, _etext or _edata) is making assumptions that the program has the memory layout of a UNIX program. pro- gram, some things may work by using the values returned by these rou- tines in place of the addresses of their UNIX link-editor defined sym- bols. So use at your own risk, and only if you know what your doing. Or better yet, convert the program to use the appropriate Mach or Mach- O functions. If you are trying to allocate memory use vm_allocate(2), if you are trying to find out about your address space use vm_region(2) and if you are trying to find out where your program is loaded use the dyld(3) functions. (__TEXT,__text) section, note this my or may not be the only section in the __TEXT segment. get_edata returns the first address after the (__DATA,__data) section, note this my or may not be the last non-zero fill section in the __DATA segment. get_end returns the first address after the last segment in the executable, note a shared library may be loaded at this address.
SEE ALSO
ld(1), dyld(3) Apple Computer, Inc. April 10, 1998 get_end(3)
Mac OS X 10.11.6 - Generated Sat Feb 4 07:27:36 CST 2017 | http://www.manpagez.com/man/3/end/ | CC-MAIN-2017-09 | en | refinedweb |
User account creation filtered due to spam.
The following program should print true, but prints false when compiled with gcj -C because the wrong field o is selected in the anonymous inner class (the protected field named o in the super class is more specific than the field o in the enclosing method).
public class t
{
static abstract class a
{
protected Object o = new Object();
abstract void print(Object input);
}
static class b
{
void m()
{
final Object o = new Object();
a x = new a()
{
void print(Object input)
{
System.out.println(o != input);
}
};
x.print(o);
}
}
public static void main(String[] args)
{
new b().m();
}
}
Since this is pretty hard to see why this code works/doesn't work in the first place (the super class could be in a completely different file and the field in the outer class certainly looks like it would be the one that is used in the inner class) a warning for this kind of usage would be nice.
gcj (GCC) 4.1.2 20070626 (Red Hat 4.1.2-13)
I tried this with svn trunk and got 'false'.
If there is a bug here it is in ecj, not gcj.
I'm not sure I agree with your interpretation here.
I don't see how specificity applies. Isn't that term only used
for overload resolution? It's been a while since I was completely
familiar with the JLS, though ... where are you reading?
IMO the JLS could be clearer here, but I believe the local 'o'
shadows the field a.o. See:
Anyway, I suggest filing against ecj or perhaps the JDK for resolution.
Subject: Re: Wrong selection of field in inner class when
outer class and super class have a relevant filed named the same
> ------- Comment #1 from tromey at gcc dot gnu dot org 2007-07-05 17:31 -------
> I tried this with svn trunk and got 'false'.
> If there is a bug here it is in ecj, not gcj.
Wow, that is interesting. Which ecj version are you using?
v_686_R32x, 3.2.2 release gives "true".
> I'm not sure I agree with your interpretation here.
> I don't see how specificity applies. Isn't that term only used
> for overload resolution? It's been a while since I was completely
> familiar with the JLS, though ... where are you reading?
I am using the completely wrong terms, sorry about that. I got the idea
from JLS second edition 8.3 Field Declarations (but admit to not have
had it handy when I filed the bug report, it actually took me some time
to find it back):
If the class declares a field with a certain name, then the
declaration of that field is said to hide any and all accessible
declarations of fields with the same name in superclasses, and
superinterfaces of the class. The field declaration also shadows
(§.
A class inherits from its direct superclass and direct
superinterfaces all the non-private fields of the superclass and
superinterfaces that are both accessible to code in the class
and not hidden by a declaration in the class.
Since it mentions that the field declaration shadows the local variables
of the enclosing block (the method) and not the enclosing class and that
it inherits the fields (which I take to mean also shadows) I believe my
interpretation is correct.
> IMO the JLS could be clearer here, but I believe the local 'o'
> shadows the field a.o. See:
>
>
>
> Anyway, I suggest filing against ecj or perhaps the JDK for resolution.
Yeah, it certainly is confusing. I need all my language lawyer skills to
even defend my bug report :) All I really want is a big fat warning from
the compiler for this type of usage because it clearly is something that
takes a long debate to even see who is right and why.
Closing as won't fix as the Java front-end has been removed from the trunk. | https://gcc.gnu.org/bugzilla/show_bug.cgi?id=32638 | CC-MAIN-2017-34 | en | refinedweb |
Using.
There is already a blog post dealing with using Unity.MVC5 and Unity.WebAPI in the same project but this will not be enough to get Umbraco working 100%. Your own controllers should all function correctly but if you run the /umbraco admin area and try navigating, you will soon come across the following:
Failed to retrieve data for child nodes undefined
An error occurred when trying to create a controller of type 'LegacyTreeController'. Make sure that the controller has a parameterless public constructor.
The error message is not hugely helpful. If we look up LegacyTreeController, it does have a parameterless public constructor but for reasons outlined below, it is not being called by Unity when resolving the controller.
When it comes to resolving components, Unity takes a greedy approach, preferring that largest constructor when there are multiple. If we take a look at LegacyTreeController, we find two constructors - a parameterless one and a complicated one which we want to stay away from.
public class LegacyTreeController : TreeControllerBase { public LegacyTreeController(); public LegacyTreeController(XmlTreeNode xmlTreeNode, string treeAlias, string currentSection, UrlHelper urlHelper); }
If the default convention does not work (as is the case here), it is very easy to tell Unity which constructor we want to use. All we need is an additional registration (in UnityConfig.cs by default):
container.RegisterType<LegacyTreeController>(new InjectionConstructor());
Restart the application and everything should work once again and you can now inject dependencies into all your SurfaceControllers, UmbracoApiControllers and RenderMvcControllers in the same way as a regular ASP.NET application.
Useful or Interesting?
If you liked the article, I would really appreciate it if you could share it with your Twitter followers.Share on Twitter | https://www.devtrends.co.uk/blog/using-unity.mvc5-and-unity.webapi-in-umbraco | CC-MAIN-2017-34 | en | refinedweb |
Password Hashing Using JAAS
Integrating authentication services into your Web apps is a serious business. Serious both in terms of demand and repercussions of doing a sloppy job. For best results, it's best to use a tried and true library. If you're working with Java, the Java Authentication and Authorization Services (JAAS) is well worth considering. In the Implementing Java-based User Authentication with JAAS article, we learned some of the nuts and bolts of JAAS. Although that was a good introduction, in the real world, you need something a bit more robust. In today's article, we'll write a utility for storing the user credentials into a database with a hashed password.
About the Database
For the purposes of today's tutorial, we'll be using the outstanding and completely free MySQL database. The user ID and password will be saved to a table named "users", which resides in a database named "test". Any database will work, so feel free to substitute another. Here is my CREATE statement:
CREATE TABLE 'test'.'users' ( 'id' INT NOT NULL, 'username' VARCHAR(10) NOT NULL, 'password' VARCHAR(45) NOT NULL, PRIMARY KEY (id));
The id primary key is required for JPA.
The persistence.xml File
This file includes definitions for one or more Persistence Units, which each in turn contain a number of properties and attributes that are necessary to connect to the underlying data store. I already spoke at length on the subject in my Defining JPA Persistence Units in your Java Enterprise Applications article, but I would like to reiterate that you must include the persistence.xml file on the classpath in a folder named "META-INF". I recommend creating a separate source folder named "resources" and add the META-INF folder under that:
Figure 1: Project structure
Here are the contents of my persistence.xml file. It includes the persistence-unit name, my Entity class, MySQL driver and database info, and login credentials.
<persistence xmlns: <persistence-unit <class>com.robgravelle.jaasdemo.User</class> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/test" /> <property name="javax.persistence.jdbc.user" value="user_admin" /> <property name="javax.persistence.jdbc.password" value="UserAdm1nPa$$90" /> <property name="eclipselink.ddl-generation" value="create-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> </properties> </persistence-unit> </persistence>
Configuring the Driver
Whatever database you use, Java requires a driver to connect to it. For instance, MySQL requires the Com.Mysql.Jdbc.Driver contained in the Mysql-Connector-Java-5.1.25-Bin.Jar file (the exact name may differ depending on the latest version). Download it and add it to your project libraries.
Java and Project Requirements
JPA is packaged with Java Enterprise Edition (EE) so you should develop in the Eclipse IDE for Java EE Developers. Moreover, your project has to be a "Dynamic Web Project." That will automatically include the JPA libraries.
Saving the User Credentials
You could just add new users to the "users" table as you would with any data, but that would leave the passwords in clear text. The secure approach is to encrypt it by using a hash and compare user logins to it after first running the input field through the very same algorithm. For that reason, we'll use a class that does the hashing by using the MD5 algorithm. Our UserCredentialsUtility calls it to hash the user password before committing it to the database.
package com.robgravelle.jaasdemo; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class UserCredentialsUtility { // The factory that produces entity manager. private static EntityManagerFactory mEmf = Persistence.createEntityManagerFactory("user"); // The entity manager that persists and queries the DB. private static EntityManager mEntityManager = mEmf.createEntityManager(); public static EntityManager getEntityManager() { return mEntityManager; } public UserCredentialsUtility() {} public static void main(String[] args) { User user = null; try { mEntityManager.getTransaction().begin(); user = new User("myName", "myPassword"); mEntityManager.persist(user); mEntityManager.getTransaction().commit(); System.out.println("User successfully saved."); } catch (Exception e) { System.err.println("Couldn't save the user info: " + e.getMessage()); } } }
The User Entity class is a typical model class, but with the extra getMD5Hash() method. It employs the native Java MessageDigest class to produce the hash.
package com.robgravelle.jaasdemo; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "users") public class User implements Serializable { private static final long serialVersionUID = -7015126518949115540L; @Id @GeneratedValue private Long id; private String username; private String password; public User() {} public User(String username, String pw) throws NoSuchAlgorithmException { this.username = username; this.password = getMD5Hash(pw); } public long getId() { return this.id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public void setPassword(String pw) { this.password = pw; } public String getPassword() { return this.password; } public static String getMD5Hash(String input) { StringBuffer sb = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); byte[] mdbytes = md.digest(); //convert the byte to hex format for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.exit(-1); } return sb.toString(); } }
The UserCredentialsUtility in Action
Barring any unexpected glitches, running the UserCredentialsUtility saves our user to the database with a password that is properly obfuscated.
Figure 2: Users table
Conclusion
That takes care of the credentials generation side of things. In the next installment, we'll develop the login code that validates input fields against those of the users table.
About the Author
| http://www.developer.com/java/ent/password-hashing-using-jaas.html | CC-MAIN-2017-34 | en | refinedweb |
This action might not be possible to undo. Are you sure you want to continue?
Reserve Bank of India: Functions and Working
RESERVE BANK OF INDIA
ž¸¸£·¸ú¡¸ ¹£ö¸¨¸Ä ¤¸ÿˆ
2
from the beginning. began operations on April 01. We hope that readers would find the book . managing supply of good currency notes within the country. foreign exchange and reserves management. government debt management. In addition. Over the years. authored by the staff of the Bank. the Reserve Bank has played an active developmental role. on maintaining price and financial stability. financial regulation and supervision. among other things. The Bank today focuses. Sadakkadulla Principal Reserve Bank Staff College Chennai 3 . useful in getting a better appreciation of the policies and concerns of the Reserve Bank. Dr. particularly for the agriculture and rural sectors. The book serves to highlight how the Reserve Bank’s decisions touch the daily lives of all Indians and help chart the country’s economic and financial course. J. It was established with the objective of ensuring monetary stability and operating the currency and credit system of the country to its advantage. and supervising and taking a lead in development of financial markets and institutions.Foreword The Reserve Bank of India. apart from currency management and acting as banker to the banks and to the Government. 1935. Its functions comprise monetary management. these functions have evolved in tandem with national and global developments This book aims to demystify the central bank by providing a simple account of the Reserve Bank’s operations and the multidisciplinary nature of its functions. the nation’s central bank. ensuring credit flow to productive sectors of the economy.
4 .
1 Publications by the Reserve Bank Annex – 2 List of Abbreviations Page No.Contents S. . No. 7 12 21 27 32 35 38 52 55 60 63 67 76 79 107 112 114 5 .
8 8 15 24 28 36 41 53 54 64 73 Improving Banking Services in Comparatively Backward States 74.
the Reserve Bank’s role and functions have undergone numerous changes. The Reserve Bank of India Act of 1934 established the Reserve Bank and set in motion a series of actions culminating in the start of operations in 1935. Since then.1 Overview The origins of the Reserve Bank of India can be traced to 1926. 7 . when the Royal Commission on Indian Currency and Finance – also known as the Hilton-Young Commission – recommended the creation of a central bank for India to separate the control of currency and credit from the Government and to augment banking facilities throughout the country. as the nature of the Indian economy and financial sector changed.
1927: A bill to give effect to the above recommendation was introduced in the Legislative Assembly. crore (rupees fifty million). 1942: The Reserve Bank ceased to be the currency issuing authority of Burma (now Myanmar). The Reserve Bank’s nationalisation aimed at achieving coordination between the policies of the government and those of the central bank. 1949: The Government of India nationalised the Reserve Bank under the Reserve Bank (Transfer of Public Ownership) Act. the Reserve Bank was nationalised in 1949. It then assumed the responsibility to meet the aspirations of a newly independent country and its people.Origins of the Reserve Bank of India 1926: The Royal Commission on Indian Currency and Finance recommended creation of a central bank for India. but was later withdrawn due to lack of agreement among various sections of people. 1948: The Reserve Bank stopped rendering central banking services to Pakistan. forex and government securities markets as also certain financial derivatives Debt and cash management for Central and State Governments Management of foreign exchange reserves Foreign exchange management—current and capital account management Box 2 8 . 1948. including credit information companies Regulation of money. 1947: The Reserve Bank stopped acting as banker to the Government of Burma. Box 1 Starting as a private shareholders’ bank. Functions of the Reserve Bank The functions of the Reserve Bank today can be categorised as follows: Monetary policy Regulation and supervision of the banking and non-banking financial institutions.
specifies its objective as “to regulate the issue of Bank notes and the keeping of reserves with a view to securing monetary stability in India and generally to operate the currency and credit system of the country to its advantage”. 1949 brought cooperative banks and regional rural banks under the Reserve Bank’s jurisdiction. protecting depositors’ interest. changed in tandem with changing national priorities and global developments. and maintaining the overall health of the financial system. expanded to cover other entities. which emerged with the enactment of the Banking Regulation Act. The Reserve Bank designs and implements the regulatory policy framework for banking and non-banking financial institutions with the aim of providing people access to the banking system. non-banking financial companies 9 . A core function of the Reserve Bank in the last 75 years has been the formulation and implementation of monetary policy with the objectives of maintaining price stability and ensuring adequate flow of credit to productive sectors of the economy. in more recent times. Thus. As evident from the multifaceted functions that the Reserve Bank performs today. has over time. the goal of maintaining financial stability. its role and priorities have. amendments to the Banking Regulation Act. The objective of maintaining financial stability has spanned its role from external account management to oversight of banks and non-banking financial institutions as also of money. under which it was constituted. in the span of 75 years. 1934 (the Act). the Reserve Bank has demonstrated dynamism and flexibility to meet the requirements of an evolving economy. Essentially. The objectives outlined in the Preamble hold good even after 75 years. 1949. government securities and foreign exchange markets. To these was added. Its function of regulating the commercial banking sector. Banker to banks Banker to the Central and State Governments Oversight of the payment and settlement systems Currency management Developmental role Research and statistics Continuity with Change The Preamble to the Reserve Bank of India Act. while amendments to the Reserve Bank of India Act saw development finance institutions.
the Reserve Bank undertook a variety of developmental functions to encourage savings and capital formation and widen and deepen the agricultural and industrial credit set-up. The aftermath of the 1991 balance of payments and foreign exchange crisis saw a paradigm shift in India’s economic and financial policies. Subsequently. as the economy matured. setting up administrative machinery to handle customer grievances. was entrusted with a variety of developmental roles. 1939 and later. With the onset of economic planning in 1950-51. The Reserve Bank adopted international best practices in areas.and primary dealers coming under its regulation. The strategy for nearly four decades placed emphasis on the state-induced or state-supported developmental efforts. prudential regulation. Initially. 10 . variety of monetary policy instruments. banking technology. as these entities became important players in the financial system and markets. the Reserve Bank. particularly in the field of credit delivery. globalisation and concerted efforts at strengthening the existing and emerging institutions and market participants. privatisation. Similarly. Institution building was a significant aspect of its role in the sixties and the seventies. focusing on financial inclusion. as the emerging nation tried to meet the aspirations of a large and diversified populace. such as. the role shifted from foreign exchange regulation to foreign exchange management. the role of the financial sector and financial markets was also given an explicit recognition in the development strategy. external sector management and currency management to make the new policy framework effective. under the Foreign Exchange Regulation Act of 1947. The rapid pace of growth achieved by the financial system in the deregulated regime necessitated a deepening and widening of access to banking services. pursuing clean note policy and ensuring development and oversight of secure and robust payment and settlement systems. The new millennium has seen the Reserve Bank play an active role in balancing the relationship between banks and customers. the Reserve Bank carried out the regulation of foreign exchange transactions under the Defence of India Rules. with its experience and expertise. Over the years. the global economic uncertainties during and after the Second World War warranted conservation of scarce foreign exchange reserves by sovereign intervention and allocation. Post-independence. The approach under the reform era included a thrust towards liberalisation.
maintaining financial stability became an important mandate for the Reserve Bank. has brought forth the need for effective coordination and consultation with other regulators within the country and abroad. in turn. The following chapters provide more details on the primary functions of the Reserve Bank. it also exposes India to global shocks. Hence.The last one-and-a-half decades have also seen growing integration of the national economy and financial system with the globalising world. 11 . While rising global integration has its advantages in terms of expanding the scope and scale of growth of the Indian economy. This.
2 Organisation Central Board of Directors Governor Deputy Governors Executive Directors Principal Chief General Manager Chief General Managers General Managers Deputy General Managers Assistant General Managers Managers Assistant Managers Support Staff 12 .
Central Board of Directors The Central Board of Directors is at the top of the Reserve Bank’s organisational Governor supervises and directs the affairs and business of the RBI. The management team also includes Deputy Governors and Executive Directors. The Central Government nominates fourteen Directors on the Central Board, including one Director each from the four Local Boards. The other ten Directors represent different sectors of the economy, such as, agriculture, industry, trade, and professions. All these appointments are made for a period of four years. The Government also nominates one Government official as a Director representing the Government, who is usually the Finance Secretary to the Government of India and remains on the Board ‘during the pleasure of the Central Government’. The Reserve Bank Governor and a maximum of four Deputy Governors are also ex officio Directors on the Central Board. Local Boards The Reserve Bank also has four Local Boards, constituted by the Central Government under the RBI Act, one each for the Western, Eastern, Northern and Southern areas of the country, which are located in Mumbai, Kolkata, New Delhi and Chennai. Each of these Boards has five members appointed by the Central Government for a term of four years. These Boards represent territorial and economic interests of their respective areas, and advise the Central Board on matters, such as, issues relating to local cooperative and indigenous banks. They also perform other functions that the Central Board may delegate to them. Offices and Branches The Reserve Bank has a network of offices and branches through which it discharges its responsibilities. The units operating in the four metros — Mumbai, Kolkata, Delhi and Chennai — are known as offices, while the units located at other cities and towns are called branches. Currently, the Reserve Bank has its offices, including branches, at 27 locations in India. The offices and larger branches are headed by a senior officer in the rank of Chief General Manager, designated as Regional Director while smaller branches are headed by a senior officer in the rank of General Manager. 13
Central Office Departments Over the last 75 years, as the functions of the Reserve Bank kept evolving, the work areas were allocated among various departments. At times, the changing role of the Reserve Bank necessitated closing down of some departments and creation of new departments. Currently, the Bank’s Central Office, located at Mumbai, has twenty-seven departments. (Box No.3) These departments frame policies in their respective work areas. They are headed by senior officers in the rank of Chief General Manager.
14 and Bank
15
Box 3
Central Office Departments
including the findings of on-site supervision and off-site surveillance carried out by the supervisory departments of the Reserve Bank and gives directions for policy formulation. The Reserve Bank Governor is the Chairman of the BFS and the Deputy Governors are the ex officio members. Board for Regulation and Supervision of Payment and Settlement Systems (BPSS) The Board for Regulation and Supervision of Payment and Settlement Systems provides an oversight and direction for policy initiatives on payment and settlement systems within the country. sets standards for existing and future systems. authorises such systems. The Board is required to meet normally once a month. One Deputy Governor. and lays down criteria for their membership. as a committee of the Central Board. The Deputy Governor in charge of regulation and supervision heads the sub-committee and two Directors of the Central Board are its members. the Board for Financial Supervision (BFS) was constituted in November 1994. The Board thus plays a critical role in the effective discharge of the Reserve Bank’s regulatory and supervisory responsibilities.The Central Board has primary authority for the oversight of RBI. boards and sub-committees. The Reserve Bank Governor is the Chairman of the BPSS. Board for Financial Supervision (BFS) In terms of the regulations formulated by the Central Board under Section 58 of the RBI Act. financial institutions and non-banking financial companies (including Primary Dealers). while two Deputy Governors. It deliberates on various regulatory and supervisory policy issues. to undertake integrated supervision of different sectors of the financial system. It delegates specific functions through it’s committees. Entities in this sector include banks. The BPSS lays down policies for regulation and supervision of payment and settlement systems. usually the Deputy Governor in-charge of banking regulation and supervision. is nominated as the Vice-Chairperson and four directors from the Reserve Bank’s Central Board are nominated as members of the Board by the Governor. 16 . three Directors of the Central Board and some permanent invitees with domain expertise are its members. Audit Sub-Committee The BFS has constituted an Audit Sub-Committee under the BFS Regulations to assist the Board in improving the quality of the statutory audit and internal audit in banks and financial institutions.
is one of the wholly owned subsidiaries of the Reserve Bank. the Deposit Insurance Corporation and Credit Guarantee Corporation of India were merged and the present Deposit Insurance and Credit Guarantee Corporation (DICGC) came into existence on July 15. current. 1988 under the National Housing Bank Act.00. 1978.owned subsidiaries: Deposit Insurance and Credit Guarantee Corporation (DICGC) With a view to integrating the functions of deposit insurance and credit guarantee. Deposit Insurance and Credit Guarantee Corporation (DICGC). (v) Any amount due on account of any deposit received outside India. the following objectives: To promote a sound. and recurring deposits) with eligible banks except the following: (i) Deposits of foreign Governments. To make housing credit more affordable. To encourage public agencies to emerge as facilitators and suppliers of serviced land for housing. (iii) Inter-bank deposits. fixed. viable and cost effective housing finance system to all segments of the population and to integrate the housing finance system with the overall financial system. among other things. NHB has been established to achieve. To regulate the activities of housing finance companies based on regulatory and supervisory authority derived under the Act. To augment resources for the sector and channelise them for housing. established under the DICGC Act 1961. which has been specifically exempted by the corporation with the previous approval of Reserve Bank of India. 17 . healthy. (ii) Deposits of Central/State Governments.1.000 (Rupees One Lakh) for both principal and interest amount held by him. The DICGC insures all deposits (such as savings. To encourage augmentation of supply of buildable land and also building materials for housing and to upgrade the housing stock in the country. (iv) Deposits of the State Land Development Banks with the State cooperative bank.Subsidiaries of the RBI The Reserve Bank has the following fully . (vi) Any amount. To promote a network of dedicated housing finance institutions to adequately serve various regions and different income groups. Every eligible bank depositor is insured upto a maximum of Rs. 1987 as a wholly-owned subsidiary of the Reserve Bank to act as an apex level institution for housing. National Housing Bank (NHB) National Housing Bank was set up on July 9.
It also has the mandate to support all other allied economic activities in rural areas. Nearly 46% of the employees were in the officer grade. Training and Development The Reserve Bank attaches utmost importance to the development of human capital and skill upgradation in the Indian financial sector. For this purpose. primarily to its junior and middle-level officers as well as to officers of other central banks. 19% in the clerical cadre and the remaining 35% were sub staff. 2009. 1956 with its Registered and Corporate Office situated at Bengaluru. one at Mysore in Karnataka and the other at Salboni in West Bengal. promote integrated and sustainable rural development and secure prosperity of rural areas. The Reserve Bank Staff College (originally known as Staff Training College). Staff Strength As of June 30.572. in various areas. The BRBNMPL has been registered as a Public Limited Company under the Companies Act. The programmes offered can be placed in four broad categories: Broad Spectrum. handicrafts and other rural crafts. since long. Functional. small-scale industries. put in place several institutional measures for ongoing training and development of the staff of the banking industry as well as its own staff. the Reserve Bank had a total staff strength of 20. National Bank for Agriculture and Rural Development (NABARD) National Bank of Agriculture and Rural Development (NABARD) is one of the subsidiaries where the majority stake is held by the Reserve Bank. it has. offers residential training programmes. Information Technology and Human Resources Management. 3.221 were attached to various Central Office departments. NABARD is an apex Development Bank with a mandate for facilitating credit flow for promotion and development of agriculture. cottage and village industries. While 17. 18 . Training Establishments The Reserve Bank currently has two training colleges and four zonal training centres and is also setting up an advanced learning centre. set up in Chennai in 1963.351 staff members were attached to Regional Offices. The company manages two Presses.
programme in the field of development studies. focuses on training the senior and middle level officers of rural and co-operative credit sectors. it quickly grew into a full-fledged teaching cum research organisation when in 1990 it launched a Ph.The College of Agricultural Banking set up in Pune in 1969. education and training of senior bankers and development finance administrators. Indira Gandhi Institute for Development Research (IGIDR). In recent years. The Reserve Bank is also in the process of setting up the Centre for Advanced Financial Learning (CAFL) replacing the Bankers’ Training College. In addition. International Monetary Fund (IMF). The Institute is engaged in research (policy and operations). Mumbai.D. it has diversified and expanded the training coverage into areas relating to non-banking financial companies. imparting training to over 7. Mumbai (Belapur) and New Delhi. National Institute of Bank Management (NIBM) was established as an autonomous apex institution with a mandate of playing a pro-active role of a ‘think-tank’ of the banking system. Phil programme was also started. Academic Institutions The Reserve Bank has also set up autonomous institutions. Mumbai.D. National Institute of Bank Management (NIBM). However. 19 . energy and environment policies.500 staff. Hyderabad. The institute is fully funded by the Reserve Bank. In 1995 an M. The objective of the Ph. human resource management and information technology. Publication of books and journals is also integral to its objectives. in collaboration with Australian Government Overseas Aid Programme (AUS-AID) and the Reserve Bank. in Chennai. has set-up its seventh international centre. Starting as a purely research institution. programme is to produce analysts with diverse disciplinary background who can address issues of economics. Both these colleges together conduct nearly 300 training programmes every year. primarily for training its clerical and sub-staff. the facilities at the ZTCs are also being leveraged for training the junior officers of the Reserve Bank. the Reserve Bank also has four Zonal Training Centres (ZTCs). of late. and consultancy to the banking and financial sectors. Kolkata. the Joint India-IMF Training Programme (ITP) in NIBM for South Asia and Eastern Africa regions. Pune. The Indira Gandhi Institute of Development Research (IGIDR) is an advanced research institute for carrying out research on development issues. such as. and the Institute for Development and Research in Banking Technology (IDRBT).
While addressing the immediate concerns of the banking sector. research at the Institute is focused towards anticipating the future needs and requirements of the sector and developing technologies to address them. 20 . Training and Development. and the various high-level committees constituted at the industry and national levels.IDRBT was established in 1996 as an Autonomous Centre for Development and Research in Banking Technology. Technology Based Education. Electronic Payments and Settlement Systems. Government of India. Indian Banks’ Association. in coordination with the Reserve Bank of India. The research and development activities of the Institute are aimed at improving banking technology in the country. The Institute is also actively involved in the development of various standards and systems for banking technology. Security Technologies for the Financial Sector. The current focal areas of research in the Institute are: Financial Networks and Applications. Ministry of Communication and Information Technology. Financial Information Systems and Business Intelligence.
1934 are: “to regulate the issue of Bank notes and the keeping of reserves with a view to securing monetary stability in India and generally to operate the currency and credit system of the country to its advantage. The overall goal is to promote economic growth and ensure price stability. monetary policy deals with the use of various policy instruments for influencing the cost and availability of money in the economy. 21 . In the Indian context.3 Monetary Management One of the most important functions of central banks is formulation and execution of monetary policy.” Thus. the Reserve Bank’s mandate for monetary policy flows from its monetary stability objective. a central bank may change the choice of instruments in its monetary policy. As macroeconomic conditions change. the basic functions of the Reserve Bank of India as enunciated in the Preamble to the RBI Act. Essentially.
Based on its assessment of macroeconomic and financial conditions. depending on the evolving situation. This is followed by three quarterly reviews in July. The success of monetary policy depends on many factors. However. financial stability. ensuring adequate flow of credit to productive sectors of the economy for supporting economic growth. such as. financial inclusion and institutional developments. the objectives of monetary policy in India have evolved to include maintaining price stability. interest rates. It also deals with important topics. credit delivery. Faced with multiple tasks and a complex mandate. financial markets. the Reserve Bank emphasises clear and structured communication for effective functioning of the monetary policy. and achieving financial stability. Monetary Policy Framework The monetary policy framework in India. 22 . the Reserve Bank takes the call on the stance of monetary policy and monetary measures. Its monetary policy statements reflect the changing circumstances and priorities of the Reserve Bank and the thrust of policy measures for the future. October and January. Improving transparency in its decisions and actions is a constant endeavour at the Reserve Bank.Monetary Policy in India Over time. However. as it is today. has evolved over the years. Part B provides a synopsis of the action taken and the status of past policy announcements together with fresh policy measures. the First Quarter Review in July and the Third Quarter Review in January consist of only Part ‘A’. the Reserve Bank may announce monetary measures at any point of time. The Monetary Policy in April and its Second Quarter Review in October consist of two parts: Part A provides a review of the macroeconomic and monetary developments and sets the stance of the monetary policy and the monetary measures. The Governor of the Reserve Bank announces the Monetary Policy in April every year for the financial year that ends in the following March. regulatory norms.
The MSS was specifically introduced to manage excess liquidity arising out of huge capital flows coming to India from abroad. credit. are juxtaposed with the output data to assess the underlying trends in different sectors. the Reserve Bank instituted Liquidity Adjustment Facility (LAF) to manage day-to-day liquidity in the banking system. In the late 1990s. output and prices. Cash Reserve Ratio indicates the quantum of cash that banks are required to keep with the Reserve Bank as a proportion of their net demand and time liabilities. with the weakened relationship between money. trade. capital flows. In addition. The repo rate (at which liquidity is injected) and reverse repo rate (at which liquidity is absorbed) under the LAF have emerged as the main instruments for the Reserve Bank’s interest rate signalling in the Indian economy. and such other indicators. SLR prescribes the amount of money that banks must invest in securities issued by the government. the Reserve Bank also uses prudential tools to modulate the flow of credit to certain sectors so as to ensure financial stability. Monetary Policy Instruments The Reserve Bank traditionally relied on direct instruments of monetary control such as Cash Reserve Ratio (CRR) and Statutory Liquidity Ratio (SLR). Such an approach provides considerable flexibility to the Reserve Bank to respond more effectively to changes in domestic and international economic environment and financial market conditions. The availability of multiple instruments and their flexible use in the implementation of monetary policy have enabled the Reserve Bank to successfully influence the liquidity and interest rate conditions in the economy. exchange rate. inflation. While the Reserve Bank prefers 23 . in the early 2000s. In addition. the Reserve Bank restructured its operating framework for monetary policy to rely more on indirect instruments such as Open Market Operations (OMOs). it replaced M3 as a policy target with a multiple indicators approach. the multiple indicators approach looks at a large number of indicators from which policy perspectives are derived. The armour of instruments with the Reserve Bank to manage liquidity was strengthened in April 2004 with the Market Stabilisation Scheme (MSS). As the name suggests. fiscal position.Operating Target There was a time when the Reserve Bank used broad money (M3) as the policy target. These facilities enable injection or absorption of liquidity that is consistent with the prevailing monetary policy stance. Interest rates or rates of return in different segments of the financial markets along with data on currency. However.
How these channels function in an economy depends on its stage of development and its underlying financial structure. in an open economy one would expect the exchange rate channel to be important. credit channel could be a major conduit for monetary transmission. The amendments to the Banking Regulation Act. Box 4 Institutional Mechanism for Monetary Policy-making The Reserve Bank has made internal institutional arrangements for guiding the process of monetary policy formulation. 24 . (c) the exchange rate channel. Monetary Policy Transmission An important factor that determines the effectiveness of monetary policy is its transmission – a process through which changes in the policy achieve the objectives of controlling inflation and achieving growth. similarly. (b) the interest rate channel. 1934 enable a flexible use of CRR for monetary management. it has not hesitated in taking recourse to direct instruments if circumstances warrant such actions. complex situations require varied combination of direct and indirect instruments to make the policy transmission effective. in an economy where banks are the major source of finance as against the capital market. Often. For example. These are (a) the quantum channel relating to money supply and credit. The recent legislative amendments to the Reserve Bank of India Act.indirect instruments of monetary policy. these channels are not mutually exclusive. 1949 also provide further flexibility in liquidity management by enabling the Reserve Bank to lower the SLR to levels below the pre-amendment statutory minimum of 25 per cent of net demand and time liabilities (NDTL) of banks. and there could be considerable feedback and interaction among them. In the implementation of monetary policy. Of course. a number of transmission channels have been identified for influencing real sector activity. without being constrained by a statutory floor or ceiling on the level of the CRR. and (d) the asset price channel.
reaching out to a variety of stakeholders and experts ahead of each Monetary Policy and quarterly Review. and the head of the Monetary Policy Department (MPD) are its members. with the Deputy Governor incharge of monetary policy as the vice-chairman. The TAC normally meets once in a quarter. Heads of various departments dealing with markets. The other Deputy Governors of the Reserve Bank are also members of this Committee. if necessary. The group comprises Executive Directors (EDs) in-charge of different markets departments and heads of other departments. The Committee is chaired by the Governor. foreign exchange and government securities markets. The FMC also makes an assessment of liquidity conditions and suggests appropriate market interventions on a day-to-day basis. five external experts and two Directors from the Reserve Bank’s Central Board. The role of the TAC is advisory in nature. although a meeting could be convened at any other time. Technical Advisory Committee (TAC) on Monetary Policy The Reserve Bank had constituted a Technical Advisory Committee (TAC) on Monetary Policy in July 2005 with a view to strengthening the consultative process in the conduct of monetary policy.Financial Markets Committee (FMC) Constituted in 1997. accountability and time path of the decision making remains entirely with the Reserve Bank. It generally meets twice in a quarter to review monetary and credit conditions and takes a view on the stance of the monetary policy. The Committee has. They meet every morning and review developments in money. central banking. Pre-Policy Consultation Meetings The Reserve Bank aims to make the policy making process consultative. as its members. The external experts are chosen from the areas of monetary economics. the inter-departmental Financial Markets Committee is chaired by the Deputy Governor in-charge of monetary policy formulation. This TAC reviews macroeconomic and monetary developments and advises the Reserve Bank on the stance of the monetary policy and monetary measures that may be undertaken in the ensuing policy reviews. The responsibility. 25 . Monetary Policy Strategy Group The Monetary Policy Strategy Group is headed by the Deputy Governor incharge of MPD. financial markets and public finance.
such as. interest rate environment and monetary and credit developments. developments in different market segments and the direction of interest rates. market participants. This consultative process contributes to enriching the policy formulation process and enhances the effectiveness of monetary policy measures. the Governor also meets economists. 26 . Bankers offer their suggestions for the policy. liquidity position. The feedback received from these meetings is analysed and taken as inputs while formulating monetary policy. non-banking finance companies. In order to further improve monetary policy communication. small and medium enterprises. rural cooperatives and regional rural banks. the Reserve Bank has introduced pre-policy consultation meetings with the Indian Banks’ Association (IBA). urban co-operative banks. These meetings mainly focus on perception and outlook of bankers on the economy.From October 2005. liquidity conditions. Resource Management Discussions The Reserve Bank holds Resource Management Discussions (RMD) meetings with select banks about one and a half months prior to the announcement of the Monetary Policy and the Second Quarter Review. credit outflows. representatives of trade and industry. micro-finance institutions. These discussions are chaired by the Deputy Governor in-charge of monetary policy formulation. credit rating agencies and other institutions. journalists and media analysts. These meetings focus on macroeconomic developments.
In 1935. the Government of India managed the issue of paper currency. thus ending the practice of private and presidency banks issuing currency. 1934. when the Reserve Bank began operations. Government of India. In consultation with the Government. 27 . it took over the function of note issue from the Office of the Controller of Currency. The Paper Currency Act of 1861 conferred upon the Government of India the monopoly of note issues.4 Issuer of Currency Management of currency is one of the core central banking functions of the Reserve Bank for which it derives the necessary statutory powers from Section 22 of the RBI Act. the Reserve Bank routinely addresses security issues and targets ways to enhance security features to reduce the risk of counterfeiting or forgery of currency notes. Along with the Government of India. with the goal of ensuring an adequate supply of clean and genuine notes. production and overall management of the nation’s currency. Between 1861 and 1935. the Reserve Bank is responsible for the design.
in singular and Rs. As per the provisions of Coinage Act.100. and its sub-denomination the Paisa (plural Paise). The reverse is applicable for withdrawals from chests. but not exceeding ten thousand rupees.Currency Unit and Denomination The Indian Currency is called the Indian Rupee (abbreviated as Re. notes in these denominations issued earlier are still valid and in circulation. To facilitate the distribution of notes and rupee coins across the country. the Reserve Bank has authorised selected branches of banks to establish currency chests. The printing of Re. However.000.281 Currency Chests and 4. Rs. five rupees and ten rupees. that the Central Government may specify. Like currency chests.50. Coins up to 50 paisa are called “small coins” and coins of Rupee one and above are called “Rupee coins”.1. coins can be issued up to the denomination of Rs.5.10. The Department of Currency Management makes recommendations on design of bank notes to the Central Government. forecasts the demand for notes. Rs. a state cooperative bank and a regional rural bank.20. 20 paisa.1. one rupee.000. Box 5 Currency Management The Reserve Bank carries out the currency management function through its Department of Currency Management located at its Central Office in Mumbai.044 Small Coin Depots with other banks. a foreign bank. Rs. Currency chests are storehouses where bank notes and rupee coins are stocked on behalf of the Reserve Bank. in plural). there are also small coin depots which have been established by the authorised bank branches to stock small coins. There is a network of 4. 50 paisa. 19 Issue Offices located across the country and a currency chest at its Kochi branch . Rs.2 denominations has been discontinued. Deposits into the currency chest are treated as reserves with the Reserve Bank and are included in the CRR.1 and Rs. Thus. At present. notes in India are issued in the denomination of Rs. 25 paisa. The currency chests have been established with State Bank of India. two rupees. Coin Denomination Coins in India are available in denominations of 10 paisa.500 and Rs. nationalised banks. The Reserve Bank is also authorised to issue notes in the denominations of five thousand rupees and ten thousand rupees or any other denomination. notes in denominations higher than ten thousand rupees cannot be issued. Rs. six associate banks. 28 . The small coin depots distribute small coins to other bank branches in their area of operation. private sector banks. in terms of current provisions of RBI Act 1934. 1906.
and ensures smooth distribution of notes and coins throughout the country. It arranges to withdraw unfit notes, administers the provisions of the RBI (Note Refund) Rules, 2009 (these rules deal with the payment of value of the soiled or mutilated notes) and reviews/rationalises the work systems and procedures at the issue offices on an ongoing basis. The RBI Act requires that the Reserve Bank’s affairs relating to note issue and its general banking business be conducted through two separate departments – the Issue Department and the Banking Department. All transactions relating to the issue of currency notes are separately conducted, for accounting purposes, in the Issue Department. The Issue Department is liable for the aggregate value of the currency notes of the Government of India (currency notes issued by the Government of India prior to the issue of bank notes by the Reserve Bank) and bank notes of the Reserve Bank in circulation from time to time and it maintains eligible assets for equivalent value. The assets which form the backing for note issue are kept wholly distinct from those of the Banking Department. The Issue Department is permitted to issue notes only in exchange for notes of other denominations or against prescribed assets. This Department is also responsible for getting its periodical requirements of notes/coins from the currency printing presses/mints, distribution of notes and coins among the public as well as withdrawal of unserviceable notes and coins from circulation. The mechanism for putting currency into circulation and its withdrawal from circulation (that is, expansion and contraction of currency, respectively) is effected through the Banking Department. Currency Distribution The Government of India on the advice of the Reserve Bank decides on the various denominations of the notes to be printed. The Reserve Bank coordinates with the Government in designing the banknotes, including their security features. Pvt. Ltd. (BRBNMPL), a wholly owned subsidiary of the Reserve Bank, also has set up printing presses at Mysore in Karnataka and Salboni in West Bengal. The Reserve Bank estimates the quantity of notes (denomination-wise) that is likely to be required and places indents with the various presses. The notes received from the presses are then issued for circulation both through remittances to banks as also across the Reserve Bank counters. Currency chests, which are maintained by 29
banks, store soiled and re-issuable notes, as also fresh banknotes. The banks send notes, which in their opinion are unfit for circulation, back to the Reserve Bank. The Reserve Bank examines these notes and re-issues those that are found fit for circulation. The soiled notes are destroyed, through shredding, so as to maintain the quality of notes in circulation. Coin Distribution The Indian Coinage Act, 1906 governs the minting of rupee coins, including small coins of the value of less than one rupee. One rupee notes (no longer issued now) and coins are legal tender in India for unlimited amounts. Fifty paisa coins are legal tender for any sum not exceeding ten rupees and smaller coins for any sum not exceeding one rupee. The Reserve Bank acts as an agent of the Central Government for distribution, issue and handling of the coins (including one rupee note) and for withdrawing and remitting them back to Government as may be necessary. SPMCIL has four mints at Mumbai, Noida (UP), Kolkata and Hyderabad for coin production. Similar to distribution of banknotes, coins are distributed through various channels such as Reserve Bank counters, banks, post offices, regional rural banks and urban cooperative banks. The Reserve Bank offices also sometimes organise special coin melas for exchanging notes into coins through retail distribution. Just as unfit banknotes are destroyed, unfit coins are also withdrawn from circulation and sent to the mint for melting. Special Type of Notes A special Star series of notes in three denominations of rupees ten, twenty and fifty have been issued since August 2006 to replace defectively printed notes at the printing presses. The Star series banknotes are exactly like the existing Mahatma Gandhi Series banknotes, but have an additional character — a (star) in the number panel in the space between the prefix and the number. The packets containing these banknotes will not, therefore, have sequential serial numbers, but contain 100 banknotes, as usual. This facility has been further extended to Rs. 100 notes with effect from June 2009. The bands on such packets indicate the presence of such notes. Exchange of Notes Basically there are two categories of notes which are exchanged between banks and the Reserve Bank – soiled notes and mutilated notes. While soiled notes are notes which have become dirty and limp due to excessive use or a two-piece note, mutilated note means a note of which a portion is missing or which is composed of more than two pieces. While soiled notes can be 30
tendered and exchanged at all bank branches, mutilated notes are exchanged at designated bank branches and such notes can be exchanged for value through an adjudication process which is governed by Reserve Bank of India (Note Refund) Rules, 2009. Under current provisions, either full or no value for notes of denomination up to Rs.20 is paid, while notes of Rs.50 and above would get full, half, or no value, depending on the area of the single largest undivided portion of the note. Special adjudication procedures exist at the Reserve Bank Issue offices for notes which have turned extremely brittle or badly burnt, charred or inseparably stuck together and, therefore, cannot withstand normal handling. Combating Counterfeiting.
31
The Reserve Bank pays agency bank charges to the banks for undertaking the government 32 . the Reserve Bank has undertaken the traditional central banking function of managing the government’s banking transactions. As a banker to the Government. 1934 requires the Central Government to entrust the Reserve Bank with all its money. the Reserve Bank acts as banker to all the State Governments in India. act as the banker to a State Government. remittance. Currently. The Reserve Bank of India Act. by agreement. The Government also deposits its cash balances with the Reserve Bank. The Reserve Bank may also. the Reserve Bank receives and pays money on behalf of the various Government departments. except Jammu & Kashmir and Sikkim.5 Banker and Debt Manager to Government Since its inception. It has limited agreements for the management of the public debt of these two State Governments. As it has offices in only 27 locations. the Reserve Bank appoints other banks to act as its agents for undertaking the banking business on behalf of the governments. exchange and banking transactions in India and the management of its public debt.
For the final compilation of the Government accounts. every ministry and department of the Central Government has been allotted a specific public sector bank for handling its transactions. the Nagpur office of the Reserve Bank has a Central Accounts Section. As banker to the Government. Under a scheme introduced in 1976. Besides. The Reserve Bank also undertakes to float loans and manage them on behalf of the Governments. The banking functions for the governments are carried out by the Public Accounts Departments at the offices / branches of the Reserve Bank. Banker to the Central Government Under the administrative arrangements. while management of public debt including floatation of new loans is done at Public Debt Office at offices / branches of the Reserve Bank and by the Internal Debt Management Department at the Central Office. which is not part of the Consolidated Fund of India. contingency fund. the Reserve Bank does not handle government’s day-to-day transactions as before.10 crore on a daily basis and Rs. It also provides Ways and Means Advances – a short-term interest bearing advance – to the Governments. whenever called upon to do so. custody and disbursement of money from the consolidated fund. The Central Government and State Governments may make rules for the receipt.100 crore on Fridays. The Reserve Bank also acts as adviser to Government. Hence. These rules are legally binding on the Reserve Bank. both of the centre and states. the Central Government is required to maintain a minimum cash balance with the Reserve Bank. and public account. this amount is Rs. except where it has been nominated as banker to a particular ministry or department. Currently. The Reserve Bank maintains a separate MSS cash balance of the Government. a Market Stabilisation Scheme (MSS) was introduced for issuing of treasury bills and dated securities over and above the normal market borrowing programme of the Central Government for absorbing excess liquidity.business on its behalf. to meet the temporary mismatches in their receipts and payments. as also at the end of March and July. the Reserve Bank works out the overall funds 33 . In 2004. it arranges for investments of surplus cash balances of the Governments as a portfolio manager. on monetary and banking related matters. The Reserve Bank has well defined obligations and provides several services to the governments.
Ways and Means Advances granted to the government and investments made from the surplus fund. interest rate. It involves issue and retirement of rupee loans. reducing the roll-over risk. A State Government account can be in overdraft for a maximum 14 consecutive working days with a limit of 36 days in a quarter. the State Government is provided a normal WMA. The daily advices are followed up with monthly statements. After the exhaustion of the special WMA limit. smoothening the maturity structure of debt. the Government and the Reserve Bank take into account a number of factors. The Reserve Bank’s debt management policy aims at minimising the cost of borrowing. and the absorptive capacity of the market. the Reserve Bank provides Ways and Means Advances to the State Governments. While formulating the borrowing programme for the year. and improving depth and liquidity of Government securities markets by developing an active secondary market. timing and manner of raising of loans are influenced by the state of liquidity and the expectations of the market. The Special WMA is extended against the collateral of the government securities held by the State Government. such as. The WMA scheme for the State Governments has provision for Special and Normal WMA. which varies from state to state depending on the relative size of the state budget and economic activity. The union budget decides the annual borrowing needs of the Central Government. Banker to the State Governments All the State Governments are required to maintain a minimum balance with the Reserve Bank. the estimated available resources. such as. To tide over temporary mismatches in the cash flow of receipts and payments. 34 . The rate of interest on WMA is linked to the Repo Rate. the amount of Central and State loans maturing during the year. Parameters. The normal WMA limits are based on three-year average of actual revenue and capital expenditure of the state. The withdrawal above the WMA limit is considered an overdraft. Surplus balances of State Governments are invested in Government of India 14-day Intermediate Treasury bills in accordance with the instructions of the State Governments. Management of Public Debt The Reserve Bank manages the public debt and issues new loans on behalf of the Central and State Governments. interest payment on the loan and operational matters about debt certificates and their registration.position and sends daily advice showing the balances in its books.
Since different persons deal with different banks. Many banks also engage in other financial activities. In order to facilitate a smooth inter-bank transfer of funds. To facilitate smooth operation of this function of banks. banks need a common banker. Settlement of inter-bank obligations thus assumes importance. banks are in the business of accepting deposits and giving loans. such as. or to make payments and to receive funds on their behalf. buying and selling securities and foreign currencies. Further. in order to settle transactions between various customers maintaining accounts with different banks. 35 . they need to exchange funds between themselves. This is usually done through the mechanism of a clearing house where banks present cheques and other such instruments for clearing. an arrangement has to be made to transfer money from one bank to another. these banks have to settle transactions among each other. thus necessitating a need for maintaining accounts with the Bank. Here too.6 Banker to Banks Banks are required to maintain a portion of their demand and time liabilities as cash reserves with the Reserve Bank.
the Reserve Bank focuses on: Enabling smooth. The Reserve Bank also facilitates remittance of funds from a bank’s surplus account at one location to its deficit account at another. enabling these banks to maintain cash reserves as well as to carry out inter-bank transactions through these accounts. This helps banks in their fund management as they can access information on their balances maintained across different 36 . the Reserve Bank provides banks with the facility of opening accounts with itself. the Reserve Bank has also introduced the Centralised Funds Management System (CFMS) to facilitate centralised funds enquiry and transfer of funds across DADs. Inter-bank accounts can also be settled by transfer of money through electronic fund transfer system. As Banker to Banks. in India. The computerisation of accounts at the Reserve Bank has greatly facilitated banks’ monitoring of their funds position in various accounts across different locations on a real-time basis. Since banks need to settle funds with each other at various places in India. Providing an efficient means of funds transfer for banks. swift and seamless clearing and settlement of inter-bank obligations. the Reserve Bank stipulates minimum balances to be maintained by banks in these accounts. Enabling banks to maintain their accounts with the Reserve Bank for statutory reserve requirements and maintenance of transaction balances. The Reserve Bank continuously monitors operations of these accounts to ensure that defaults do not take place. Among other provisions. such as. the Reserve Bank opens current accounts of banks with itself. which is delivered through the Deposit Accounts Department (DAD) at the Regional offices. Such transfers are electronically routed through a computerised system. the Real Time Gross Settlement System (RTGS).In order to meet the above objectives. Acting as a lender of last resort. This is the ‘Banker to Banks’ function of the Reserve Bank. The Department of Government and Bank Accounts oversees this function and formulates policy and issues operational instructions to DAD. Box 6 In addition. they are allowed to open accounts with different regional offices of the Reserve Bank. Reserve Bank as Banker to Banks To fulfill this function.
It can come to the rescue of a bank that is solvent but faces temporary liquidity problems by supplying it with much needed liquidity when no one else is willing to extend credit to that bank. when necessary.DADs from a single location. Lender of Last Resort As a Banker to Banks. As Banker to Banks. 37 . to facilitate lending to specific sectors and for specific purposes. the Reserve Bank provides short-term loans and advances to select banks. The Reserve Bank extends this facility to protect the interest of the depositors of the bank and to prevent possible failure of a bank. which in turn may also affect other banks and institutions and can have an adverse impact on financial stability and thus on the economy. 75 banks are using the system and all DADs are connected to the system. the Reserve Bank also acts as the ‘lender of last resort’. Currently. These loans are provided against promissory notes and other collateral given by the banks.
and to maintain overall financial stability through various policy measures. In respect of banks. The credit information companies are regulated under the provisions of Credit Information Companies (Regulation) Act. 38 . credit information companies and select segments of the financial markets.7 Financial Regulation and Supervision The Reserve Bank’s regulatory and supervisory domain extends not only to the Indian banking system but also to the development financial institutions (DFIs). 1934. As the regulator and the supervisor of the banking system. primary dealers. 1949. The objective of this function is to protect the interest of depositors through an effective prudential regulatory framework for orderly development and conduct of banking operations. non-banking financial companies (NBFCs). 2005. the Reserve Bank has a critical role to play in ensuring the system’s safety and soundness on an ongoing basis. while the other entities and markets are regulated and supervised under the provisions of the Reserve Bank of India Act. the Reserve Bank derives its powers from the provisions of the Banking Regulation Act.
acquired added importance. including the local area banks and all-India financial institutions. and liquidity and solvency of banks. which had seriously impacted several banks and financial institutions in advanced countries. the global financial markets have. various prudential measures were intitated that have. strengthened the Indian banking system over a period of time. However. The Board for Financial Supervision (BFS).India’s financial system includes commercial banks. Improved financial soundness of banks has helped them to show stability and resilience in the face of the recent severe global financial crisis. there is still a need to strengthen the regulatory and supervisory architecture. The Department of Banking Operations and Development (DBOD) frames regulations for commercial banks. The Reserve Bank’s regulatory and supervisory role has. in effect. grown phenomenally in terms of volumes. in the last 75 years. is the principal guiding force behind the Reserve Bank’s regulatory and supervisory initiatives. The Department of Non-Banking Supervision (DNBS) regulates and supervises the Non-Banking Financial Companies (NBFCs) while the Urban Banks Department (UBD) regulates and supervises the Urban Cooperative Banks (UCBs). the Reserve Bank’s regulatory and supervisory policy initiatives are aimed at protection of the depositors’ interests. The banking sector reforms since the 1990s made stability in the financial sector an important plank of the Reserve Bank’s functions. With the onset of banking sector reforms during the 1990s. local area banks. such as. the Basel Committee on Banking Supervision (BCBS) and the Financial Stability Board (FSB). constituted in November 1994. Besides. financial institutions and non-banking financial companies. cooperative banks. Regulatory and Supervisory Functions Traditionally. Rural Planning and Credit Department (RPCD) regulates the Regional Rural Banks (RRBs) and the Rural Cooperative Banks. whereas their supervision has been entrusted to NABARD. regional rural banks. Its presence on such bodies has enabled the Reserve Bank’s active participation in the process of evolving global standards for enhanced regulation and supervision of banks. orderly development and conduct of banking operations. The Department of Banking Supervision (DBS) undertakes supervision of commercial banks. 39 . therefore. There are various departments in the Reserve Bank that perform these regulatory and supervisory functions. The Reserve Bank represents India in various international fora. number of players and instruments.
called Statutory Liquidity Ratio (SLR). 40 . amalgamation and winding up of banks. called Cash Reserve Ratio (CRR) and in the form of investment in unencumbered approved securities. whether by an Indian or a foreign bank. In terms of the guidelines. a licence from the Reserve Bank is required. The opening of new branches by banks and change in the location of existing branches are also regulated as per the Branch Authorisation Policy. small loans up to rupees two lakh. The Reserve Bank also monitors compliance with these requirements by banks in their day-to-day operations. This policy has recently been liberalised significantly and Indian banks no longer require a licence from the Reserve Bank for opening a branch at a place with population of below 50. However. It has issued guidelines stipulating ‘fit and proper’ criteria for directors of banks. The Reserve Bank also has powers to appoint additional directors on the board of a banking company. Statutory Pre-emptions Commercial banks are required to maintain a certain portion of their Net Demand and Time Liabilities (NDTL) in the form of cash with the Reserve Bank. a majority of the directors of banks are required to have special knowledge or practical experience in various relevant areas. export credits and a few other categories of advances. the Reserve Bank regulates the interest rates on savings bank accounts and deposits of non-resident Indians (NRI).The major regulatory functions of the Reserve Bank with respect to the various components of the financial system are as follows: (i) Commercial Banks Licensing For commencing banking operations in India. The Reserve Bank continues to emphasise opening of branches by banks in unbanked and under-banked areas of the country. Corporate Governance The Reserve Bank’s policy objective is to ensure high-quality corporate governance in banks. Interest Rate The interest rates on most of the categories of deposits and lending transactions have been deregulated and are largely determined by banks. The Reserve Bank also regulates merger.000.
Doubtful and Loss Assets depending upon age of the NPAs and value of available securities. Basel II standardised approach is applicable with road map drawn up for advanced approaches. if any. banks are required to maintain adequate capital for credit risk.Prudential Norms The Reserve Bank has prescribed prudential norms to be followed by banks in several areas of their operations. A brief description of these norms is furnished below: Capital Adequacy The Reserve Bank has instructed banks to maintain adequate capital on a continuous basis. Securities under HTM category must be carried at acquisition / amortised cost. The adequacy of capital is measured in terms of Capital to Risk-Weighted Assets Ratio (CRAR). investments portfolio and capital market exposures. the Reserve Bank requires banks to classify their loan assets as performing and non-performing assets (NPA). Banks are also required to have exposure limits in place to prevent credit concentration risk and limit exposures to sensitive sectors. capital markets and real estate. 41 Box 7 . primarily based on the record of recovery from the borrowers. It keeps a close watch on developing trends in the financial markets. and fine-tunes the prudential policies. Prudential Norms In order to strengthen the balance sheets of banks. needs appropriate provisions by banks. Banks are also required to make appropriate provisions against each category of NPAs. asset classification and provisioning. Loans and Advances In order to maintain the quality of their loans and advances. subject to certain conditions. capital adequacy. the Reserve Bank has been prescribing appropriate prudential norms for them in regard to income recognition. The securities held under HFT and AFS categories have to be marked-to-market periodically and depreciation. Available for Sale (AFS) and Held for Trading (HFT). to name a few. operational risk and other risks. NPAs are further categorised into Sub-standard. such as. For Investments The Reserve Bank requires banks to classify their investment portfolios into three categories for the purpose of valuation: Held to Maturity (HTM). Under the recently revised framework. market risk.
operational risk and other risks. on how to measure these risks as well as how to manage them Disclosure Norms Public disclosure of relevant information is an important tool for enforcing market discipline. Supervisory Functions The Reserve Bank undertakes supervision of banks to monitor and ensure compliance by them with its regulatory policy framework. Banks are required to carry out KYC exercise for all their customers to establish their identity and report suspicious transactions to authorities. based on the Basel II capital adequacy framework.1 lakh per depositor per bank. if any. The DICGC provides insurance cover to all eligible bank depositors up to Rs. merchant banking activities. such as. imposed on them by the regulator. also known as para-banking. 42 .Risk Management Banks. Para . asset quality. asset management. earnings aspects and penalties.banking Activities The banking sector reforms and the gradual deregulation of the sector inspired many banks to undertake non-traditional banking activities. Know Your Customer Norms To prevent money laundering through the banking system. in their daily business. mutual funds business. face various kinds of risks. equity participation in venture funds and leasing. among others. off-site surveillance and periodic meetings with top management of banks. the Reserve Bank has strengthened the disclosure norms for banks. Banks are now required to make disclosures in their annual report. venture capital. The Reserve Bank requires banks to have effective risk management systems to cover credit risk. The Reserve Bank has permitted banks to undertake diversified activities. factoring services. Protection of Small Depositors The Reserve Bank has set up Deposit Insurance and Credit Guarantee Corporation (DICGC) to protect the interest of small depositors. insurance business. the Reserve Bank has issued ‘Know Your Customer’ (KYC). It has issued guidelines. card business. Anti-Money Laundering (AML) and Combating Financing of Terrorism (CFT) guidelines. over the years. This is achieved through on-site inspection. Hence. market risk. liquidity. in case of bank failure. about capital adequacy.
banks are assigned supervisory ratings based on the CAMELS (CALCS for foreign banks in India) supervisory model and are required to address the weaknesses identified. the modus operandi and the measures necessary to prevent frauds. asset quality. The roadmap was divided into two phases.On-site Inspection The Reserve Bank undertakes annual on-site inspection of banks to assess their financial health and to evaluate their performance in terms of quality of management.March 2009. it also has quarterly / monthly discussions with them on important aspects based on OSMOS returns and other inputs. Monitoring of Frauds The Reserve Bank regularly sensitises banks about common fraud-prone areas. (ii) Foreign Banks. Further. there are uncertainties surrounding the financial strength of banks around the world. the first phase spanning the period March 2005 . Based on the findings of the inspection. One track was the consolidation of the domestic banking system. earnings. It also cautions banks about unscrupulous borrowers who have perpetrated frauds with other banks. This information is thoroughly analysed by the RBI to assess the health of individual banks and that of the banking system. capital adequacy. and the second track was the gradual enhancement of the presence of foreign banks in a synchronised manner. In addition. and also glean early warning signals which could serve as a trigger for necessary supervisory intervention. both in private and public sectors. Periodic Meetings The Reserve Bank periodically meets the top management of banks to discuss the findings of its inspections. and the second phase beginning April 2009 after a review of the experience gained in the first phase. the 43 . liquidity position as well as internal control systems. In view of the recent global financial market turmoil. Off-site Surveillance The Reserve Bank requires banks to submit detailed and structured information periodically under its Off Site Surveillance and Monitoring System (OSMOS).
export. As in the case of commercial banks.Exim Bank. (iv) Rural Financing Institutions (A) Rural Cooperative Banks Rural cooperatives occupy an important position in the Indian financial system. The legal character. the current policy and procedures governing the presence of foreign banks in India will continue. National Housing Bank (NHB) and Small Industries Development Bank of India (SIDBI) which are under full-fledged regulation and supervision of the Reserve Bank. recovery of the global financial system and a shared understanding on the regulatory and supervisory architecture around the world.regulatory and supervisory policies at national and international levels are under review. Thus far. housing and small industries. (iii) Financial Institutions Financial institutions are an important part of the Indian financial system as they provide medium to long term finance to different sectors of the economy. These institutions have been set up to meet the growing demands of particular segments. and capital adequacy ratio are applicable to these financial institutions as well. clientele and the role of state governments in the functioning of the cooperative banks make these institutions distinctively different from commercial banks. 44 . prudential norms relating to income recognition. Cooperative banks are registered under the respective State Co-operative Societies Act or Multi State Cooperative Societies Act. cooperatives have been a key instrument of financial inclusion in reaching out to the last mile in rural areas. The proposed review will be taken up after consultation with the stakeholders once there is greater clarity regarding stability. such as. National Bank for Agriculture and Rural Development (NABARD). 2002 and governed by the provisions of the respective acts. These were the first formal institutions established to purvey credit to rural India. asset classification and provisioning. ownership. These institutions also are subject to on-site inspection as well as off-site surveillance. management. These institutions have been playing a crucial role in channelising credit to the above sectors and addressing the challenges / issues faced by them. There are four financial institutions . The distinctive feature of the cooperative credit structure in India is its heterogeneity. In view of this. rural.
352 Short-term Rural Cooperative Credit Institutions (STCCIs). asset classification and provisioning norms are applicable as in the case of commercial banks. they are required to disclose the level of CRAR in the ‘notes on accounts’ to their balance sheets every year. The Board of Supervision. A roadmap has been put in place to achieve this position. As on end-March 2008. District Central Cooperative Banks (DCCBs) at the intermediate (district) level and Primary Agricultural Credit Societies (PACS) at the ground (village) level. There were 717 Long Term Rural Cooperative Credit Institutions (LTCCIs) comprising 20 SCARDBs and 697 PCARDBs. Capital Adequacy Norms At present. The short-term cooperative structure is a three-tier structure with State Cooperative Banks (StCBs) at the apex (State) level. since March 31. a Committee of the Board of Directors of NABARD. 371 DCCBs and 94. their supervision is carried out by National Bank for Agriculture and Rural Development (NABARD). The long-term cooperative structure has the State Cooperative Agriculture and Rural Development Banks (SCARDBs) at the apex level and the Primary Cooperative Agriculture and Rural Development Banks (PCARDBs) at the district or block level. Rakesh Mohan and Co-Chairman: Shri Ashok Chawla) had observed that there is a need for a roadmap to ensure that only licenced banks operate in the cooperative space and that banks which fail to obtain a licence by 2012 should not be allowed to operate to expedite the process of consolidation and weeding out of non viable entities from the cooperative space. there were 95. gives directions and guidance in respect of policies and matters relating to supervision and inspection of StCBs and DCCBs. However. The Committee on Financial Sector Assessment (Chairman: Dr. This included 31 StCBs.950 PACS. The shortterm structure caters primarily to the various short / medium-term production and marketing credit needs for agriculture.Structure of Rural Cooperative Credit Institutions Rural cooperatives structure is bifurcated into short-term and long-term structure. The income recognition. These institutions were conceived with the objective of meeting long-term credit needs in agriculture. the CRAR norms are not applicable to StCBs and DCCBs. 2008. Regulatory and Supervisory Framework While regulation of State Cooperative Banks and District Central Cooperative Banks vests with Reserve Bank. A large number of StCBs as well as DCCBs are unlicensed and are allowed to function as banks till they are either granted licence or their applications for licence are rejected. 45 .
The primary (urban) co-operative banks (UCBs). artisans and small entrepreneurs. 1966. With a view to bringing primary (urban) co-operative banks under the purview of the Banking Regulation Act. are registered under the respective State Co-operative Societies Act or Multi State Cooperative Societies Act. As of March 31. 1976 with a view to developing the rural economy by providing credit and other facilities. However. certain provisions of the Banking Regulation Act.(B) Regional Rural Banks Regional Rural Banks were set up under the Regional Rural Banks Act. amalgamation and liquidation are regulated by the State/ Central Governments. 46 . Karnataka. RRBs together with commercial and co-operative banks. The function of financial regulation over RRBs is exercised by Reserve Bank and the supervisory powers have been vested with NABARD. there were 86 RRBs having a total of 15.107 branches. As of March 31. matters related to banking are regulated and supervised by the Reserve Bank under the Banking Regulation Act. The equity of the RRBs was contributed by the Central Government. these banks came under the dual control of respective State Governments/Central Government and the Reserve Bank. With this. Andhra Pradesh. asset classification and provisioning norms as applicable to commercial banks are applicable to RRBs. like other co-operative societies. Being local level institutions. 2009. The UCBs are largely concentrated in a few States. 1949 (as applicable to co-operative societies). particularly to the small and marginal farmers. were assigned a critical role to play in the delivery of agriculture and rural credit. Maharashtra and Tamil Nadu. administration and recruitment. 1949. concerned State Government and the sponsor bank in the proportion of 50:15:35. agricultural labourers. there were 1721 primary (urban) co-operative banks including 53 scheduled banks. 1949 were made applicable to co-operative banks effective March 1. most of the UCBs are often functioning as a unit bank. While the non-banking aspects like registration. 2009. 2002 and governed by the provisions of the respective acts. (v) Urban Cooperative Banks Urban co-operative banks play a significant role in providing banking services to the middle and lower income groups of society in urban and semi urban areas. such as. Gujarat. management. the income recognition. Apart from a few large banks. CRAR norms are not applicable to RRBs.
profitability and compliance with CRR/SLR stipulations. net NPA. NBFCs are 47 . other non-scheduled UCBs are inspected once in two years. insurance or collection of monies. The banks are graded into four categories based on four parameters viz. CRAR. An NBFC is defined as a company engaged in the business of lending. they are subject to (i) on-site inspection. Further UCBs also have to obtain prior authorisation of the Reserve Bank to open a new place of business.(A) Regulatory Framework Licensing UCBs have to obtain a licence from the Reserve Bank for doing banking business. chit fund. (B) Supervisory Framework To ensure that primary (urban) co-operative banks function on sound lines and their methods of operation are consistent with statutory provisions and are not detrimental to the interests of depositors. While all scheduled urban co-operative banks. investment in shares and securities.. and (ii) off-site surveillance. provisioning and capital adequacy ratio are applicable to urban co-operative banks as well. (vi) Non-Banking Financial Companies (NBFCs) Non-banking Financial Companies play an important role in the financial system. Off-site Surveillance In order to have continuous supervision over the UCBs. On-site Inspection The principal objective of inspection of primary (urban) co-operative banks is to safeguard the interests of depositors and to build and maintain a sound banking system in conformity with the banking laws and regulations. Depending upon the line of activity. The unlicensed primary (urban) co-operative banks can continue to carry on banking business till they are refused a licence. the Reserve Bank has supplemented the system of periodic on-site inspection with off-site surveillance (OSS) through a set of periodical prudential returns to be submitted by UCBs. and select non-scheduled urban co-operative banks are inspected on an annual basis. asset classification. Prudential Norms Prudential norms relating to income recognition. hire purchase.
740 NBFCs. Companies which accept public deposits are required to comply with all the prudential norms on income recognition. Additional disclosures in balance sheets have also been prescribed. and the contents of the application forms. they have been directed to limit their investment in real estate. the maximum rate of interest payable on such deposits (presently 12. which should not be less than 12 months and should not exceed 60 months. provisioning for bad and doubtful debts. Further. Recognising the growth in the sector. The non-deposit taking companies are classified as NBFC-ND. as well as the advertisement for soliciting deposits. In order to restrict indiscriminate investment by Non-Banking Financial Companies in real estate and in unquoted shares. initially the regulatory set-up primarily focused on the deposit taking activity in terms of limits and interest rate. a company has to have a minimum level of Net Owned Funds (NoF). except for their own use. capital adequacy. Out of these. credit and investment concentration. The recommendations of the Joint Parliamentary Committee which looked into the stock market scam of early 90s and the Shah Committee (1992) suggested that there was a need to expand the regulatory and supervisory focus also to the asset side of NBFCs’ balance sheet. the period of deposits. asset classification. At end. accounting standards. Legislative amendments were adopted to empower the Reserve Bank to regulate Non-Banking Financial Companies to ensure that they integrate their functioning within the Indian financial system. respectively. brokerage fees and other expenses amounting to a maximum of 2 per cent and 0. (A) Regulatory Framework NBFCs accepting Public Deposits The Reserve Bank issues directions about the quantum of public deposits that can be accepted.June 2009 there were 12. The amended Act provides that for commencing /carrying on the business of Non –Banking Financial Institution(NBFI).5 per cent). 336 have been permitted to accept deposits and are classified as NBFC-D. 48 .categorised into different types.5 per cent of the deposits. up to 10 per cent of their owned funds. a ceiling of 20 per cent has also been prescribed for investment in unquoted shares of other than group / subsidiary companies.
unlike the NBFC-D. been taking significant exposure on the capital market. these entities have. Liquidity and Systems (CAMELS pattern) and identifies the supervisory concerns. Management. they are also required to provide additional information to the Reserve Bank through monthly and annual returns. Asset Quality. These are taken up with the respective institutions for remedial action. 49 . to contain the risks of the NBFC sector spilling over to the banking sector. several returns have been prescribed for NBFCs as part of the off-site surveillance system. non-deposit taking NBFCs with asset size of Rs 100 crore and above were classified as Systemically Important and were required to comply with exposure and capital adequacy norms . their borrowings increased considerably. However. the depositors can lodge their claims against the Company with the Company Law Board (CLB). However. since. the sector has witnessed the entry of some large companies in the category of NBFC-ND. Further.were earlier not subject to prudential norms for capital adequacy and exposures. Since these companies. Earnings.In case an NBFC defaults in the payment of matured deposits. The inspection focuses on Capital. either in the form of credit facilities or in the form of equity contribution has been prudentially capped. Off-Site Surveillance System In order to supplement information between on-site inspections. Further. NBFCs not accepting Public Deposits Non-Banking Financial Companies not accepting public deposits are regulated in a limited manner. the NBFC sector does not have any cap on exposure to the capital market. (B) Supervisory Framework On-Site Inspection All NBFC-D and all large NBFC – NDs are subjected to regular annual inspection to assess their financial performance and the general compliance with the directions issued by the Reserve Bank. as a part of their business. The information provided is analysed to identify potential supervisory concerns and in certain cases serves as a trigger for on-site inspection. with the opening up of foreign direct investment in NBFCs and the opportunities for credit growth in the economy. exposure of banks to the NBFC sector. unlike banks. To facilitate off-site supervision. In view of the above. NBFCs also have to maintain SLR (15 per cent) as a percentage of deposits. there is no CRR prescription for NBFCs as they do not accept demand deposits.
As on June 30. the concerned institution has failed to adhere to the terms of authorisation or any other applicable guideline. In order to broaden the Primary Dealership system. the standalone PDs were permitted to diversify into business activities. banks were permitted to undertake Primary Dealership business departmentally in 2006-07. (vii) Primary Dealers In 1995. other than the core PD business. subject to certain conditions. as well as adherence to the provisions of the RBI Act has also been entrusted to the statutory auditors of the Non-Banking Financial Companies. 50 . 2009. The Reserve Bank reserves the right to cancel the Primary Dealership if. prudential norms and exposure limits. The statutory auditors are required to report to the Reserve Bank about any irregularity or violation of regulations concerning acceptance of public deposits. there were six standalone PDs and eleven banks authorised to undertake PD business departmentally. in 2006-07. maintenance of liquid assets and regularisation of excess deposits held by the companies. in its view.External Auditing The responsibility of ensuring compliance with the directions issued by the Reserve Bank. PDs are expected to join the Primary Dealers Association of India (PDAI) and the Fixed Income Money Market and Derivatives Association (FIMMDA) and abide by the code of conduct and such other actions as initiated by these Associations in the interest of the securities markets. or any other authority. Further. if they undertake any activity regulated by SEBI. Any change in the shareholding pattern / capital structure of a PD needs prior approval of the Reserve Bank. Enforcement Directorate. PDs play an active role in the Government securities market by underwriting and bidding for fresh issuances and acting as market makers for these securities. Income Tax. credit rating. CBI. which comprised independent entities undertaking Primary Dealer activity. SEBI. A Primary Dealer should bring to the Reserve Bank’s attention any major complaint against it or action initiated/taken against it by the Stock Exchanges. Regulation PDs are required to meet registration and such other requirements as stipulated by the Securities and Exchange Board of India (SEBI) including operations on the Stock Exchanges. capital adequacy. the Reserve Bank introduced the system of Primary Dealers (PDs) in the Government Securities Market.
The Reserve Bank. documents and accounts of the PD. records. Credit Information Companies (Regulation) Act 2005 empowers the Reserve Bank to regulate CICs. issued ‘inprinciple approval’ to four companies to set up CICs. the company was a listed company on a recognised stock exchange. Various measures have been taken to deepen these markets over a period of time. The Reserve Bank regulates only certain segments of financial markets. the government securities market and the foreign exchange market. in April 2009. the money market. PDs are required to make available all such documents and records to the Reserve Bank officers and render all necessary assistance as and when required. and (c) preferably. periodic returns which are analysed to identify any concerns. On-site inspection: The Reserve Bank has the right to inspect the books. (ix) Financial Markets Deep and efficient financial markets are essential for realising the growth potential of an economy. 51 . however. The Reserve Bank announced in November 2008 that Foreign Direct Investment up to 49 per cent in CICs would be considered in cases: (a) where the investor was a company with an established track record of running a credit information bureau in a well regulated environment. namely.Supervision Off-site supervision: PDs are required to submit to the Reserve Bank. (viii) Credit Information Companies Credit Information Companies (CIC) play an important role in facilitating credit to various borrowers on the basis of their track record. (b) no shareholder in the investor company held more than 10 per cent voting rights in that company. disorderly financial markets could be a source of risk to both financial institutions and the economy.
The legal provisions governing management of foreign exchange reserves are laid down in the Reserve Bank of India Act.8 Foreign Exchange Reserves Management 1935 A proportional reserve system required gold and forex reserves to be a minimum 40 percent of currency issued 1991 India faces balance of payment crises. The basic parameters of the Reserve Bank’s policies for foreign exchange reserves management are safety. liquidity and returns. the share of foreign currency assets in the balance sheet of the Reserve Bank has substantially increased. pledges gold to shore up reserves 2009 The Reserve Bank purchased 200 mts of gold under IMF’s limited gold sales programme The Reserve Bank. The Reserve Bank’s reserves management function has in recent years grown both in terms of importance and sophistication for two main reasons. the task of preserving the value of reserves and obtaining a reasonable return on them has become challenging. 1934. with the increased volatility in exchange and interest rates in the global market. as the custodian of the country’s foreign exchange reserves. First. is vested with the responsibility of managing their investment. Second. 52 .
the Reserve Bank focuses on: a) Maintaining market’s confidence in monetary and exchange rate policies. in consultation with the Government. Investment of Reserves:. b) Enhancing the Reserve Bank’s intervention capacity to stabilise foreign exchange markets. Special Drawing Rights (SDRs) and gold. Deployment of Reserves The foreign exchange reserves include foreign currency assets (FCA). thus reducing the costs at which foreign exchange resources are available to market participants. SDRs are held by the Government of India.Within this framework. The Reserve Bank has framed policy guidelines stipulating stringent eligibility criteria for issuers. The Reserve Bank. e) Adding to the comfort of market participants by demonstrating the backing of domestic currency by external assets. c) Limiting external vulnerability by maintaining foreign currency liquidity to absorb shocks during times of crisis. continuously reviews the reserves management strategies. counterparties. return optimisation has become an embedded strategy within this framework. including national disasters or emergencies. d) Providing confidence to the markets that external obligations can always be met. and investments to be made with them to enhance the safety and liquidity of reserves. the Reserve Bank pays close attention to currency 53 Box 8 . In deploying reserves. The foreign currency assets are managed following the principles of portfolio management.
Foreign Exchange Reserves Management: The RBI’s Approach The Reserve Bank’s approach to foreign exchange reserves management has also undergone a change. The counterparties with whom deals are conducted are also subject to a rigorous selection process. S. ensure a reasonable level of confidence in the international community about India’s capacity to honour its obligations. and counter speculative tendencies in the market. Tarapore. Until the balance of payments crisis of 1991. The committee in addition to trade-based indicators also suggested money-based and debt-based indicators. the total return (both interest and capital gains) is taken into consideration.S. The committee stressed the need to maintain sufficient reserves to meet all external payment obligations. the objective of smoothening out the volatility in the exchange rates assumed importance. All foreign currency assets are invested in assets of top quality and a good proportion is convertible into cash at short notice. In 1997. composition. Tarapore. Similar views have been held by the Committee on Fuller Capital Account Convertibility (Chairman: Shri S. One crucial area in the process of investment of the foreign currency assets in the overseas markets relates to the risks involved in the process. the size of risk-adjusted capital flows and national security requirements. In assessing the returns from deployment. 54 . Box 9 The traditional approach of assessing reserve adequacy in terms of import cover has been widened to include a number of parameters about the size. The objective is to ensure that the quantum of reserves is in line with the growth potential of the economy. The overall approach to the management of foreign exchange reserves also reflects the changing composition of Balance of Payments (BoP) and liquidity risks associated with different types of flows. the Reserve Bank follows the accepted portfolio management principles for risk management. and risk profiles of various types of capital flows.composition. Rangarajan (1993). July 2006). C. India’s approach to foreign exchange reserves was essentially aimed at maintaining an appropriate import cover. After the introduction of system of market-determined exchange rates in 1993. interest rate risk and liquidity needs. While there is no set formula to meet all situations. suggested alternative measures for adequacy of reserves. The Reserve Bank also looks at the types of external shocks to which the economy is potentially vulnerable. The approach underwent a paradigm shift following the recommendations of the High Level Committee on Balance of Payments chaired by Dr. the Report of the Committee on Capital Account Convertibility under the chairmanship of Shri S.
Like other markets. The statutory power for exchange control was provided by the Foreign Exchange Regulation Act (FERA) of 1947. 1999. which was subsequently replaced by a more comprehensive Foreign Exchange Regulation Act. and the Reserve Bank has been modulating its approach towards its function of supervising the market. 1973. the foreign exchange market has also evolved over time. foreign exchange in India was treated as a controlled commodity because of its limited availability. export and import of currency notes and bullion. Evolution For a long time. transfer of securities between 55 .9 Foreign Exchange Management The Reserve Bank oversees the foreign exchange market in India. to control and regulate dealings in foreign exchange payments outside India. Exchange control was introduced in India under the Defence of India Rules on September 3. and in certain cases the Central Government. This Act empowered the Reserve Bank. 1939 on a temporary basis. It supervises and regulates it through the provisions of the Foreign Exchange Management Act. The early stages of foreign exchange management in the country focused on control of foreign exchange by regulating the demand due to limited supply.
the Foreign Exchange Management Act (FEMA) was enacted in 1999 to replace FERA with effect from June 1. Extensive relaxations in the rules governing foreign exchange were initiated. growth in foreign trade. quantitative restrictions and other regulatory and discretionary controls.residents and non-residents. Keeping in view the changed environment. such as. current account convertibility. rationalisation of tariffs. and acquisition of immovable property in and outside India. prompted by the liberalisation measures introduced since 1991 and the Act was amended as a new Foreign Exchange Regulation (Amendment) Act 1993. negotiating foreign collaboration. the Reserve Bank has permitted residents to hold foreign currency up to a maximum of USD 2.000 or its equivalent. among other transactions. undertaking technical study tours. the Reserve Bank in due course also amended (since January 31. the Reserve Bank has undertaken substantial elimination of licensing. Liberalised Approach The Reserve Bank issues licences to banks and other institutions to act as Authorised Dealers in the foreign exchange market. Residents can now also open foreign currency accounts in India and credit specified foreign exchange receipts into it. Apart from easing restrictions on foreign exchange transactions in terms of processes and procedure. such as. Emphasising the shift in focus. 2000. resulted in a changed environment. and also for medical treatment. 56 . 2004) the name of its department dealing with the foreign exchange transactions to Foreign Exchange Department from Exchange Control Department. setting up joint ventures abroad. Significant developments in the external sector. attending international conferences. In keeping with the move towards liberalisation. the Reserve Bank has also provided the exchange facility for liberalised travel abroad for purposes. substantial increase in foreign exchange reserves. Moreover. acquisition of foreign securities. increased access to external commercial borrowings by Indian corporates and participation of foreign institutional investors in Indian stock market. FEMA aimed at consolidating and amending the laws relating to foreign exchange with the objective of facilitating external trade and payments and for promoting the orderly development and maintenance of foreign exchange markets in India. pursuing higher studies and training. liberalisation of Indian investments abroad. conducting business.. Foreign institutional investors are allowed to invest in all equity securities traded in the primary and secondary markets. The Reserve Bank has permitted foreign investment in almost all sectors. corporate debt instruments and mutual funds. up to 400 per cent of its net-worth. The Government allows Indian companies to issue Global Depository Receipts (GDRs) and American Depository Receipts (ADRs) to foreign investors The GDRs/ADRs issued by Indian companies to non-residents have free convertibility outside India. Foreign companies are permitted to set up 100 per cent subsidiaries in India. and securitised instruments. 57 . Indian Investment Abroad Any Indian entity can make investment in an overseas joint venture or in a wholly-owned subsidiary. with a few exceptions. buyers’ credit. no prior approval from the Government or the Reserve Bank is required for non-residents investing in India. suppliers’ credit. the Reserve Bank has liberalised the provisions relating to such investments. Foreign Currency Convertible Bonds (FCCBs) and Foreign Currency Exchangeable Bonds (FCEBs) are also governed by the ECB guidelines. The NRIs have the flexibility of investing under the options of repatriation and non-repatriation. Following the reforms path. Foreign institutional investors have also been permitted to invest in Government of India treasury bills and dated securities. External Commercial Borrowings Indian companies are allowed to raise external commercial borrowings including commercial-bank loans.Foreign Investment Foreign investment comes into India in various forms. In many sectors.
Such issuances are subject to approval of the sectoral regulators. authorities in India have allowed eligible companies resident outside India to issue Indian Depository Receipts (IDRs) through a domestic depository. Exchange Rate Policy The foreign exchange market in India comprises Authorised Persons (banks. which was in line with the Bretton Woods system prevalent then. As the product is exchange traded. After the breakdown of Bretton Woods System in the early seventies. the conduct of currency futures trading facility is being regulated jointly by the Reserve Bank and the Securities and Exchange Board of India. money changers and other entities) in foreign exchange business. With the decline in the share 58 . Currency Futures In a recent development. the Reserve Bank has permitted resident individuals to freely remit abroad up to USD 200. The period after independence was marked by a fixed exchange rate regime. India’s exchange rate policy has evolved in tandem with the domestic as well as international developments. most of the countries moved towards a system of flexible/managed exchange rates. The customer segment is dominated by major public sector entities and Government of India (for civil debt service and defence ) on the one hand and large private sector corporates on the other. The Indian Rupee was pegged to the Pound Sterling on account of historic links with Britain. Such trading facilities are currently being offered by the National Stock Exchange. Indian Depository Receipts (IDRs) Under another reform measure. the Bombay Stock Exchange and the MCX-Stock Exchange. Foreign Institutional Investors (FIIs) have emerged as an important constituent in the equity market and thus contribute significantly to the foreign exchange market activity. foreign exchange brokers who act as intermediaries and customers – individuals as well as corporates – who need foreign exchange for their transactions. The Indian foreign exchange market primarily comprises two segments – the spot market and the derivatives market. As in other emerging market economies.Liberalised Remittance Scheme As a step towards further simplification and liberalisation of the foreign exchange facilities available to the residents. regulators have permitted exchange-traded currency futures in India. the spot market is the dominant segment of the Indian foreign exchange market.000 per financial year for any permissible purposes.
the Indian Rupee was de-linked from the Pound Sterling in September 1975. forward rate agreements and currency futures. The Reserve Bank’s exchange rate policy focuses on ensuring orderly conditions in the foreign exchange market. When necessary. The market operations are undertaken either directly or through public sector banks. A significant two-step downward adjustment in the exchange rate of the Rupee was made in 1991. In March 1992. cross-currency options.. A unified single market-determined exchange rate system based on the demand for and supply of foreign exchange replaced the LERMS effective March 1. 59 . the Reserve Bank has facilitated increased availability of derivative instruments in the foreign exchange market. For the purpose. interest rate swaps and currency swaps.of Britain in India’s trade. foreign currency-Rupee options. it closely monitors the developments in the financial markets at home and abroad. the Rupee’s external value was allowed to be determined by market forces in a phased manner following the balance of payment difficulties in the nineties. In addition to the traditional instruments like forward and swap contracts. It has allowed trading in Rupee-foreign currency swaps. 1993. increased diversification of India’s international transactions together with the weaknesses of pegging to a single currency. it intervenes in the market by buying or selling foreign currencies. Liberalised Exchange Rate Management System (LERMS) involving the dual exchange rate was instituted.
CCIL acts as central counter party to all Government securities trade facilitating smooth 60 .10 Market Operations The Reserve Bank oprationalises its monetary policy through its operations in government securities . The netted funds settlement is carried out through members’ Current Account maintained at the Reserve Bank and through Designated Settlement Bank for those members who do not maintain current account with the Reserve Bank. foreign exchange and money markets. The Bank carries out such operations in the secondary market on the electronic Negotiated Dealing System – Order Matching (NDS-OM) platform by placing bids and/or taking the offers for securities. The entire settlement is under Delivery versus Payment mode. The securities settlement is done in SGL/ CSGL Accounts of members maintained at the central bank. Monetary Operations Open Market Operations Open Market Operations in the form of outright purchase/sale of Government securities are an important tool of the Reserve Bank’s monetary management. All the secondary market transactions in Government Securities are settled through Clearing Corporation of India Limited (CCIL).
The LAF auctions are also conducted electronically with the market participants. to be fixed through mutual consultations. interest costs are borne by the Government. Liquidity Adjustment Facility Auctions The liquidity management operations are aimed at modulating liquidity conditions such that the overnight rates in the money market remains within the informal corridor set by the repo and reverse repo rates for the liquidity adjustment facility (LAF) operations. The issuances under MSS are matched by an equivalent cash balance held by the Government in a separate identifiable cash account maintained and operated by the Reserve Bank. By design. Domestic Foreign Exchange Market Operations Operations in the domestic foreign exchange markets are conducted within the Reserve Bank’s framework of exchange rate management policy. The dated securities / treasury bills are the same as those issued for normal market borrowings for avoiding segmentation of the market. The exchange rate management policy in recent years has been guided by the broad principles of careful monitoring and management of exchange rates 61 . such as. while in a reverse repo transaction it absorbs liquidity from the system with the Reserve Bank providing securities to the counter parties. Market Stabilisation Scheme The Market Stabilisation Scheme (MSS) was introduced in April 2004 under which Government of India dated securities / treasury bills could be issued to absorb surplus structural / durable liquidity created by the Reserve Bank’s foreign exchange operations. banks and Primary Dealers. the MSS has the flexibility of not only absorbing liquidity but also of injecting liquidity. The LAF auctions are conducted either only once or two times in a day with the operations effectively modulating overnight liquidity conditions in the market. the Reserve Bank infuses liquidity into the system by taking securities as collateral. These securities are also traded in the secondary market. While these issuances do not provide budgetary support to the Government. for MSS operations along with a threshold which would trigger a review of the ceiling. thus reducing gridlocks and mitigating cascading impact that default by one member could have on the system.settlement and also guaranteeing settlement. The MoU between the Reserve Bank and the Government of India envisaged an annual ceiling. MSS operations are a sterilisation tool used for offsetting the liquidity impact created by intervention in the foreign exchange markets. In a repo transaction. if required. through unwinding as well as buy-back of securities issued under the MSS.
certificate of deposit. The Reserve Bank also collates. the exchange rate management policy is guided by the need to reduce excess volatility. It also allows underlying demand and supply conditions to determine the exchange rate movements over a period in an orderly way. repo market. commercial paper and Collateralised Borrowing and Lending Obligations (CBLO). help maintain adequate level of reserves and develop an orderly foreign exchange market.with flexibility. prevent the emergence of destabilising speculative activities. computes and disseminates RBI Reference rate on daily basis. The call / notice / term money market operations are transacted / reported on the Negotiated Dealing System – Call (NDS Call) platform. Money Market The Reserve Bank also carries out regulation and development of money market instruments such as call / notice / term money market. without a fixed target or a pre-announced target or a band coupled with the ability to intervene if and when necessary. Subject to this predominant objective. 62 .
Development.11 Payment and Settlement Systems The regulation and supervision of payment systems is being increasingly recognised as a core responsibility of central banks. people’s preference for paper-based instruments and rapid changes in technology are among factors that make this task a formidable one. The Reserve Bank. 63 . has been initiating reforms in the payment and settlement systems to ensure efficient and faster flow of funds among various constituents of the financial sector. Consolidation and Integration The Reserve Bank has adopted a three-pronged strategy of consolidation. The increasing monetisation in the economy. development and integration to establish a modern and robust payment and settlement system which is also efficient and secure. the country’s large geographic expanse. Safe and efficient functioning of these systems is an important pre-requisite for the proper functioning of the financial system and the efficient transmission of monetary policy. as the regulator of financial systems.
Payment and Settlement System: Evolution and Initiatives Computerisation of clearing operations was the first major step towards modernisation of the payments system. To facilitate faster clearing of large-value cheques (of value of rupees one lakh and above). For settlement of trade in foreign exchange. The Reserve Bank introduced mechanised clearing in the four metro cities of Mumbai. the Reserve Bank has advised the clearing houses to gradually discontinue its use. mechanised cheque processing. and interconnection of the clearing houses. apart from providing accuracy in the final settlement. Mechanisation of the clearing operations was another milestone with the introduction of Magnetic Ink Character Recognition (MICR)-based chequeprocessing technology using High Speed Reader Sorter systems driven by mainframe computers. The NDS facilitates the dealing process and provides for electronic reporting of trades. Government securities and other debt instrument. However. such as. To facilitate settlement of Government securities transactions. on-line information dissemination and settlement in a centralised system. with the development of other electronic modes of transfer and to encourage customers to move from paper-based modes to electronic products. covering select branches of banks for same day settlement. This uses a series of electronic payment instructions for transfer of funds instead Box 10 64 . The Reserve Bank has introduced Electronic Clearing Service (ECS). The Reserve Bank has also taken steps towards integrating the payment system with the settelement systems for government securities and foreign exchange. This system eliminates the physical movement of cheques and provides a more secure and efficient method for clearing cheques. The Reserve Bank has also introduced a ‘Cheque Truncation System’ (CTS) in the National Capital Territory of New Delhi. it has set up the Clearing Corporation of India Limited (CCIL). New Delhi. its aim being to reduce the time taken in clearing. This plays the role of a central counter party to transactions and guarantees settlement of trade. a screen-based trading platform. thus managing the counter party risk. image-based cheque processing systems. balancing and settlement. the Reserve Bank introduced ‘High-Value’ Clearing (HVC). The reach is also facilitated by the use of latest technology. it created the Negotiated Dealing System. Kolkata and Chennai during 1986.The consolidation revolves around expanding the reach of the existing products by introducing clearing process in new locations.
The National Electronic Clearing Service (NECS). telephone companies. The system has a pan-India characteristic leveraging on Core Banking Solutions (CBS) of member banks. primary dealers and clearing entities. facilitating all CBS bank branches to participate in the system. The guidelines focus on systems for security and inter-bank transfer arrangements through authorised systems. NPCI is expected to bring greater efficiency in retail payment by way of uniformity and standardisation as also expansion of reach and innovative payment products to augment customer convenience. forex settlement and money market settlements are processed through the RTGS system. financial institutions. 65 . facilitates credits to bank accounts of multiple customers against a single debit of remitter’s account. such as. irrespective of their location. Participants in this system include banks.. The ‘ECS–Credit’ enables companies to pay interest or dividend to a large number of beneficiaries by direct credit of the amount to their bank accounts. Pre-paid payment instruments facilitate purchase of goods and services against the value stored on these instruments. of paper instruments. All systemically important payments including securities settlement. payment of insurance premia and loan installments. As at the end of September 2009 as many as 114 banks with 30. The Real Time Gross Settlement system settles all inter-bank payments and customer transactions above rupees one lakh. The Reserve Bank encouraged the setting up of the National Payments Corporation of India (NPCI) to act as an umbrella organisation for operating the various retail payment systems in India. NECS (Debit) when launched would facilitate multiple debits to destination account holders against a single credit to the sponsor bank.780 branches were participating in NECS. The Reserve Bank has introduced an Electronic Funds Transfer scheme to enable an account holder of a bank to electronically transfer funds to another account holder with any other participating bank. The Reserve Bank has also issued guidelines for the use of mobile phones as a medium for providing banking services. electricity. To encourage the use of this safe payment mechanism. Only banks which are licensed and supervised in India and have a physical presence in India are permitted to offer mobile banking services in the country. directly by debit to the customer’s account with a bank. ‘ECS-Debit’ facilitates payment of charges to utility services. the Reserve Bank has issued guidelines that lay down the basic eligibility criteria and the conditions for operating such payment systems in the country.
In 2005. only payment systems authorised by the Reserve Bank can be operated in the country. 2007 provides for regulation and supervision of payment systems in India and designates the Reserve Bank as the authority for the purpose. As per the Act. it created a Board for Regulation and Supervision of Payment and Settlement Systems (BPSS) as a Committee of the Central Board. Institutional Framework The Reserve Bank has put in place an institutional framework and structure for oversight of the payment systems. 66 . The Act also provides for the settlement effected under the rules and procedures of the system provider to be treated as final and irrevocable. A new department called the Department of Payment and Settlement Systems (DPSS) was constituted to assist the BPSS in performing its functions.Legal Framework The Payment and Settlement Systems Act.
through the thrust on financial inclusion.12 Developmental Role The Reserve Bank is one of the few central banks that has taken an active and direct role in supporting developmental activities in their country. Towards this goal. Rural Credit Given the predominantly agrarian character of the Indian economy. as well as extension of banking service to all. the Reserve Bank has taken various initiatives. and expanding access to affordable financial services. creating institutions to build financial infrastructure. The Reserve Bank today also plays an active role in encouraging efficient customer service throughout the banking industry. its developmental role has extended to institution building for facilitating the availability of diversified financial services within the country. The Reserve Bank’s developmental role includes ensuring credit to productive sectors of the economy. Over the years. which has evolved over many years. the Reserve Bank’s role has been to ensure timely and adequate credit to the 67 .
The scheme was gradually extended to all commercial banks by 1992. such as. initially with public sector banks. agriculture and small enterprises. In order to provide access to credit to the neglected sectors. microcredit.agricultural sector at affordable cost. education and housing. it may tender expert guidance and assistance to the National Bank (NABARD) and conduct special studies in such areas as it may consider necessary to do so for promoting integrated rural development. The guidelines on lending to priority sector were revised with effect from April 30. The scope and extent of priority sectors have undergone several changes since the formalisation of description of the priority sectors in 1972. Priority Sector Lending The focus on priority sectors can be traced to the Reserve Bank’s credit policy for the year 1967-68. and to the sectors which are employment-intensive. bulk of bank advances directed to large and medium-scale industries and established business houses. The broad categories of advances under priority sector now include agriculture. 2007. and institution of a scheme of ‘social control’ over commercial banks in 1967 by the Government of India to remove certain deficiencies observed in the functioning of the banking system. Section 54 of the RBI Act. such as. 1934 states that the Bank may maintain expert staff to study various aspects of rural credit and development and in particular. The guiding principle of the revised guidelines on lending to priority sector has been to ensure adequate flow of bank credit to those sectors of the society/ economy that impact large segments of the population and weaker sections. 68 . a target based priority sector lending was introduced from the year 1974. micro and small enterprises sector.
whichever is higher. will not be reckoned for computing performance under 18 per cent target. Advances to small enterprises sector will be reckoned in computing performance under the overall priority sector target of 40 per cent of ANBC or credit equivalent amount of Off-Balance Sheet Exposure. (ii) 20 per cent of total advances to small enterprises sector should go to micro (manufacturing) enterprises with investment in plant and machinery above Rs 5 lakh and up to Rs. At least two third of DRI advances should be granted through rural and semi-urban branches. No target. (Thus. No target 69 . whichever is higher Same as for domestic banks Micro enterprises within small enterprises sector Export credit 12 per cent of ANBC or credit equivalent amount of Off-Balance Sheet Exposure. whichever is higher. indirect lending in excess of 4. Export credit is not a part of priority sector for domestic commercial banks. whichever is higher.Targets for Lending to the Priority Sector Domestic Commercial Banks Total priority sector advances 40 per cent of Adjusted Net Bank Credit (ANBC) [Net Bank Credit plus investments made by banks in nonSLR bonds held in held to maturity (HTM) category] or credit equivalent amount of Off-Balance Sheet Exposure. whichever is higher. 18 per cent of ANBC or credit equivalent amount of OffBalance Sheet Exposure. 25 lakh. It should be ensured that not less than 40 per cent of the total advances granted under DRI scheme goes to scheduled caste / scheduled tribes. and micro (service) enterprises with investment in equipment above Rs. Total agricultural advances Small enterprise advances 10 per cent of ANBC or credit equivalent amount of Off-Balance Sheet Exposure. whichever is higher. However. whichever is higher. 2 lakh and up to Rs. 2 lakh. 10 lakh.5 per cent of ANBC or credit equivalent amount of Off-Balance Sheet Exposure. 1 per cent of total advances outstanding as at the end of the previous year. whichever is higher. (i) 40 per cent of total advances to small enterprises sector should go to micro (manufacturing) enterprises having investment in plant and machinery up to Rs 5 lakh and micro (service) enterprises having investment in equipment up to Rs. Foreign Banks 32 per cent of ANBC or credit equivalent amount of Off-Balance Sheet Exposure. whichever is higher No target Advances to weaker sections Differential rate of interest scheme 10 per cent of ANBC or credit equivalent amount of OffBalance Sheet Exposure. all agricultural advances under the categories ‘direct’ and ‘indirect’ will be reckoned in computing performance under the overall priority sector target of 40 per cent of ANBC or credit equivalent amount of OffBalance Sheet Exposure. Of this. 60 per cent of small enterprises advances should go to the micro enterprises).
market yards. having shortfall in lending to priority sector and/or agricultural lending and/or weaker section lending targets.). As a measure of disincentive for non-achievement of agricultural lending target. while the State Governments are required to pay interest at Bank Rate plus 0. the rates of interest on deposits vary between Bank Rate and Bank Rate minus 3 percentage points depending on the individual bank’s shortfall in lending to agriculture target of 18 per cent. The scheme has been extended to Private Sector banks as well from the year 2005-06.The domestic scheduled commercial banks. Special Agricultural Credit Plan With a view to augmenting the flow of credit to agriculture. the RIDF has been extended on a year-to-year basis to presently RIDF XV through announcements in the Union Budgets. Accordingly. The Reserve Bank has assigned a Lead District Manager for each district who acts as a catalytic force for promoting financial inclusion and smooth working between government and banks. Since then.5 percentage points. are required to deposit in Rural Infrastructure Development Fund (RIDF) established with NABARD or other Funds set up with other financial institutions. Lead Bank Scheme The Reserve Bank introduced the Lead Bank Scheme in 1969. rural roads and bridges. the rate of interest on RIDF deposits has been linked to the banks’ performance in lending to agriculture. assessing deposit potential and credit gaps and evolving a coordinated approach for credit deployment in each district. soil conservation. banks are required to fix self-set targets showing an increase of about 30 per cent over previous year’s disbursements on yearly basis (April – March). The interest rates charged from State Governments and payable to banks under the Rural Infrastructure Development Fund (RIDF) have been brought down over the years in accordance with the reduction of market interest rates. The public sector banks have been formulating SACP since 1994. etc. both in the public and private sector. 70 . in concert with other banks and other agencies. Special Agricultural Credit Plan (SACP) was instituted and has been in operation for quite some time now. watershed management and other forms of rural infrastructure (such as. Under the SACP. effective RIDF-VII. Here designated banks were made key instruments for local development and were entrusted with the responsibility of identifying growth centres. RIDF was established with NABARD in April 1995 to assist State Governments / State-owned corporations in quick completion of projects relating to irrigation.
Micro. allied activities and also non-farm short term credit needs (consumption needs). The relief measures include. Seasonal sub-limits may be fixed at the discretion of the banks.25 lakh. Limits may be fixed taking into account the entire production credit needs along with ancillary activities relating to crop production. relaxed security and margin norms. On revision of the KCC Scheme by NABARD in 2004. margin and rate of interest are as per RBI guidelines issued from time to time. banks have also been advised to lend collateral free loans up to Rs. 71 . rescheduling / conversion of short-term loans into term loans. cropping pattern and scales of finance. Natural Calamities – Relief Measures In order to provide relief to bank borrowers in times of natural calamities. The Act sought to modify the definition of micro. small and medium enterprises engaged in manufacturing or production and providing or rendering of services. Small and Medium Enterprises Development With the enactment of the Micro. Under the scheme. fresh loans. Security. non-compounding of interest in respect of loans converted / rescheduled. Further. Limits are valid for three years subject to annual review. the limits are fixed on the basis of operational land holding.5 lakh to the MSE borrowers.Kisan Credit Cards The Kisan Credit Card (KCC) Scheme was introduced in the year 1998-99 to enable the farmers to purchase agricultural inputs and draw cash for their production needs. the services sector has also been included in the definition of micro. Some of the major measures by RBI/ GOI to improve the credit flow to the MSE sector are as under: Collateral Free Loans: Reserve Bank has issued instructions/ guidelines advising banks to sanction collateral free loans up to Rs. and moratorium of at least one year. Small and Medium Enterprises Development (MSMED) Act. 2006. based on good track record and financial position of the units. the scheme now covers term credit as well as working capital for agriculture and allied activities and a reasonable component for consumption needs. treatment of converted/rescheduled agriculture loans as ‘current dues’. small and medium enterprises. among other things. apart from extending the scope to medium enterprises. the Reserve Bank has issued standing guidelines to banks.
Formulation of “Banking Code for MSE Customers”: The Banking Codes and Standards Board of India (BCSBI) has formulated a voluntary Code of Bank’s Commitment to Micro and Small Enterprises and has set minimum standards of banking practices for banks to follow when they are dealing with MSEs. Specialised MSE Branch in every District: Public sector banks were advised in August 2005 to operationalise at least one specialised MSE branch in every district and centre having a cluster of MSE enterprises. 72 . The Scheme envisages that the lender availing guarantee facility would give composite credit so that the borrowers obtain both term loan and working capital facilities from a single agency. 1 crore under the scheme. Working Group on Rehabilitation/Nursing of Potentially Viable Sick SME Units: Detailed guidelines have been issued to banks advising them to evolve Board approved policies for the MSE sector relating to: (i) Loan policy governing extension of credit facilities. At the end of March 2009. (ii) Restructuring / Rehabilitation policy for revival of potentially viable sick units / enterprises. (iii) Non-discretionary one time settlement scheme for recovery of non-performing loans. Credit Guarantee Scheme for Small Industries by SIDBI: The main objective of the Credit Guarantee Scheme (CGS) for MSEs is to make available bank credit to first generation entrepreneurs for setting up their MSE units without the hassles of collateral/third party guarantee. 869 specialised MSE bank branches were operationalised by banks. The Trust at present is providing guarantee to collateral free loans up to Rs.
It took the lead role in setting up the Export Import Bank of India (EXIM Bank) in January 1982. In recent years. The institutions set up included: 1982: Export-Import Bank of India Export Credit Recognising the important role of exports in maintaining the viability of external sector and in generating employment. A major task undertaken by the Reserve Bank was to put in place the necessary institutional mechanism to complement the planning efforts.Institutions to Meet Needs of the Evolving Economy When India embarked upon the era of planned development. the Reserve Bank played a proactive role in setting up a number of specialised financial institutions at the national and regional level to widen the facilities for term finance to industry and for institutionalisation of savings – a novel departure for a central bank. This was crucial especially in the context of an underdeveloped and evolving financial system. interest rates on export credit have been rationalised 73 Box 11 . In the absence of a well-developed capital market. with the liberalisation of real and financial sectors of the economy. the primary need was to facilitate adequate flow of credit to the industrial and other sectors according to the Plan priorities. the Reserve Bank had sought to ensure adequate availability of concessional bank credit to exporters.
The Reserve Bank. especially the underprivileged sections of society. promoting financial inclusion and supporting the development plans of the State Governments. funds transfer and payment facilities and revised human resources incentives in the region. Himachal Pradesh and Jharkhand between July 2006 and October 2007 with a view to improving the outreach of banks and their services. Lakshadweep. it was observed that banking industry has shown tremendous growth in volume and range of services provided while making significant improvements in financial viability. profitability and competitiveness. currency management. would bear the one time capital cost and recurring costs for a limited period of five years. the Reserve Bank of India established a Committee on Financial Sector Plan (CFSP) for North Eastern Region in January 2006. into the fold of basic banking services to the desired extent. among other things. Financial Inclusion Post liberalisation and deregulation of the financial sector within the country. However. Uttaranchal. suggestions for expanding the banking outreach. as its contribution. which are not found to be commercially viable by banks. To improve banking penetration in the North-East. The reports examined the adequacy of banking services. In order to provide adequate credit to exporters on a priority basis. The report includes.within the overall monetary and credit policy framework. made constructive suggestions towards enhancing the outreach of banks and promoting financial inclusion as well as revitalising RRBs and UCBs in the respective regions. banks had not been reaching and bringing vast segments of the population. The Report addressed important issues pertaining to financial inclusion. providing hassle-free credit. simplification of system and procedures for opening bank accounts. Chhattisgarh. improving CD ratio. The Reserve Bank has also formulated a scheme for setting-up banking facilities (currency chests. extension of foreign exchange and Government business facilities) at centres in the North-Eastern region. Box 12 74 . This prompted the need for the RBI to develop a specific focus towards Financial Inclusion for inclusive growth. the Reserve Bank has also prescribed a minimum proportion of banks’ adjusted net bank credit to be lent to exporters by foreign banks. The State Governments would make available necessary premises and other infrastructural support. Improving Banking Services in Comparatively Backward States The Reserve Bank established Working Groups in Bihar. land collateral substitutes.
which looked at various key indicators. Under the BO scheme. In order to strengthen the institutional mechanism for dispute resolution. financial inclusion. The scheme covers grievances of the customers against commercial banks. the BO and the attached staff are drawn from the serving employees of the Reserve Bank. currency management. The Reserve Bank’s initiatives in the field of customer service include the setting up of a Customer Redressal Cell. branch expansion. such as. The implementation of the report’s recommendations is monitored through an Action Point Matrix and quarterly progress reports. creation of a Customer Service Department and the setting up of the Banking Codes and Standards Board of India (BCSBI).The new scheme is fully funded by the RBI and covers grievances related to credit cards and activities of the selling agents of banks also. The BO is a quasi-judicial authority for resolving disputes between a bank and its customers. an autonomous body for promoting adherence to self-imposed codes by banks. urban cooperative banks and regional rural banks. Customer Service The Reserve Bank’s approach to customer service focuses on protection of customers’ rights. forex facilities. At present. the RBI introduced a revised BO scheme. both the complainant and the bank. funds transfer and payment. and strengthening the grievance redressal mechanism in banks and also in the Reserve Bank. enhancing the quality of customer service. there are 15 Banking Ombudsman offices in the country. if unsatisfied with the decision of the BO.A special taskforce was established for Sikkim. the Reserve Bank in 1995 introduced the Banking Ombudsman (BO) scheme. can appeal against the decisions of the BO to the appellate authority within the Reserve Bank. insurance and capital. etc. Under the revised scheme. business correspondent / facilitator model. In 2006. 75 .
The Reserve Bank has made focused efforts to provide quality data to the public at large. The Reserve Bank also disseminates data and information regularly in the form of several publications and through its website. Like other major central banks. the Reserve Bank has also developed its own research capabilities in the field of economics. The primary data compiled by the Reserve Bank becomes an important source of information for further research by the outside world.13 Policy Research and Data Dissemination The Reserve Bank has over time established a sound and rich tradition of policy-oriented research and an effective mechanism for disseminating data and information. which has emanated from its internal economic research and 76 . finance and statistics. which have critical implications for the Indian economy. Internal Research The research undertaken at the Reserve Bank revolves around issues and problems arising in the current environment at national and international levels. which contribute to a better understanding of the functioning of the economy and the ongoing changes in the policy transmission mechanism.
and speeches and interviews given by the top management which articulate the Reserve Bank’s assessment of the economy and its policies. such as. Under the aegis of the Development Research Group in the Department of Economic Analysis and Policy. quarterly and annual publications. It endeavours to provide credible statistics and information to users across the spectrum of market participants. Besides. the media. The DRG studies are the outcome of collaborative efforts between experts from outside the Reserve Bank and the pool of research talent within. it also publishes reports of various committees appointed to look into specific subjects. India is among the first few signatories of the Special Data Dissemination Standards (SDDS) as defined by the International Monetary Fund for the purpose of releasing data and the Reserve Bank contributes to SDDS in a significant manner. businesses. professionals and the academics. Besides these and the regular periodical publications. It also has the facility for simple and advanced queries. there are periodical statements on monetary policy.robust statistical system. Users now have access to a much larger database on the Indian economy through the Reserve Bank’s website. press releases. The annual Report on Currency and Finance has now been made into a theme-based publication. monthly. established and strengthened over the years. It has become a valuable reference point for research and policy formulation. the Reserve Bank encourages and promotes policy-oriented research backed by strong analytical and empirical basis on subjects of current interest. and discussion papers prepared by its internal experts. This is done through various tools. 77 . This site has a user-friendly interface and enables easy retrieval of data through pre-formatted reports. providing in-depth information and analysis on a topical subject. The Reserve Bank has also set up an enterprise-wide data warehouse through which data is made available in downloadable and reusable formats. official press releases. The Reserve Bank is under legal obligation under The RBI Act to publish two reports every year: the Annual Report and the Report on Trend and Progress of Banking in India. Data and Research Dissemination The Reserve Bank releases several periodical publications that contain a comprehensive account of its operations as well as information of the trends and developments pertaining to various areas of the Indian economy. website. and weekly.
its coverage has improved significantly.The Handbook of Statistics on the Indian Economy constitutes a major initiative at improving data dissemination by providing statistical information on a wide range of economic indicators. 78 . The Reserve Bank’s two research departments – Department of Economic Analysis and Policy and Department of Statistics and Information Management – provide analytical research on various aspects of the Indian economy. The Handbook was first published in 1996 and over the years.
14 How Departments Work Bank and 79 .
Risk Management: The emphasis is on managing and controlling exposure to financial and operational risks.Market Department of External Investments and Operations The objectives of the Department of External Investments and Operations are reserves and exchange rate management. foreign exchange market operations and deployment of foreign currency assets and gold. investments in sovereign and sovereign-guaranteed paper with a residual maturity not exceeding 10 years. It publishes data on foreign exchange reserves. instruments. etc. (iv) Market Research The Department monitors and analyses key developments in global financial markets as information inputs for management on a daily basis. any other instruments and institutions as approved by the Central Board of the Reserve Bank and dealing in certain types of derivatives. (ii) Government Business The Department manages foreign exchange transactions on behalf of the Government of India that include grants-in-aid and/or loans from various international institutions. and considerable attention to strengthening operational risk control arrangements. It also undertakes certain foreign exchange transactions on behalf of the Government and plays a role in international co-operation arrangements involving foreign exchange reserves. (iii) International Financial Co-operation The Department plays an important role in international monetary and financial co-operation initiatives. deposits with foreign commercial banks. (i) Management of Reserves Deployment of Asssets: The RBI Act. While safety and liquidity constitute the twin objectives. Special studies and reports are also prepared expeditiously on emerging international financial issues. It permits deposits with central banks and the Bank for International Settlements. 1934 provides the overarching legal framework for deployment of the foreign currency assets and gold and defines the broad parameters for currencies. issuers and counterparties. return optimisation has become an embedded strategy. bilateral arrangements and membership of the Asian Clearing Union. Decision-making relies on regular reviews of investment strategy. including the IMF. 80 .
Switzerland. While presently that involves basic single factor sensitivity analysis. identifying them and the associated data requirements is an ongoing task. economics and financial markets departments—conducts macro-prudential surveillance of the financial system. statistics. develops a database by collecting key data on variables that impact financial stability. This involves identifying key risks and possible inter-connectedness for systemically important institutions. coordinating with the FSB Secretariat at the BIS in Basel. As key risk indicators could change with the changing economic scenario. The Department — which draws upon the expertise from supervisory. markets and countries. more advanced methods of stress testing are gradually being attempted using scenario building for multifactor stress testing by developing econometric models. and develops models for assessing financial stability. 81 Market . regulatory.Financial Stability Unit The Reserve Bank established the Financial Stability Unit in July 2009 against the backdrop of international initiatives for resolving the global financial crisis and strengthening the international financial architecture. and especially of those institutions and markets it regulates. conducts systemic stress tests. institutions and infrastructure. Macro Stress Testing The Department conducts system-level stress tests based on plausible scenarios to assess the resilience of the financial system. Preparation of Periodic Financial Stability Reports Periodic financial stability reports focus on early stage identification and assessment of the magnitude and implications of potential risks and vulnerabilities that could magnify into a crisis for the financial system. The Department’s work includes the following: Macro Prudential Surveillance Macro prudential surveillance of the financial system is the core function. The reports look at the strength and resilience of three major segments— markets. Secretariat to the Financial Stability Board The FSU is the Secretariat to the Reserve Bank’s representative on the FSB. prepares periodic financial stability reports.
and conduct of MSS operations for sterilisation of Rupee liquidity of enduring nature created out of forex market intervention operations in response to large capital inflows. government securities and forex markets.charge and comprising heads of relevant departments (DEIO. compiling data on CDs and CPs and monitoring FII investment in government and corporate bonds. Given this mandate. domestic and foreign. government securities. Government Securities: Sell/purchase of Government Securities in the secondary market for effective liquidity management. commodity and derivatives markets. assessing banking system liquidity. including liquidity adjustment facility (LAF) and operations under market stabilisation scheme (MSS). Money: Conduct of daily LAF auctions for banks and primary dealers. (iv) Policy and Co-ordination: In policy matters. multiple and longer-term LAF operations under special circumstances. the Department undertakes the following functions: (i) Monitoring: Conducts detailed analysis of various financial market segments: forex. 82 . money. The FMC meets every morning to assess and evaluate developments in various market segments. (iii) Surveillance: Scrutiny and analysis of transactions in government securities and money markets. Conducting operations in the domestic foreign exchange market. augmenting the Reserve Bank’s rupee securities stocks. and provides analytical inputs to senior management for decision-making and policy formulation. smoothening volatility in the secondary market. the Financial Markets Committee (FMC) – chaired by the Deputy Governor. equity. corporate debt.Market Financial Markets Department Financial Markets Department was set up in 2005 to give the Reserve Bank an integrated interface with various financial markets for conduct of its monetary operations. Monetary operations such as open market operations (OMO).in. (ii) Market Operations: Undertakes operations in various segments of domestic market that include: Forex: Intervention operations to curb excessive volatility and to ensure orderly conditions in the domestic forex market. IDMD and FMD) – guides the Department’s initiatives. The mandated functions of the Department are: Monitoring of money. MPD.
(iii) Primary Dealers Regulation Division: Regulates and supervises Primary Dealers. runs the technology platform for Government securities auctions. all State Governments and the Union Territory of Puducherry. such as. reviews their performance and authorises new entrants. Providing innovative and practical solutions for broader government financial issues. as well as undertakes analysis on long term patterns of Government borrowing. analyses market developments and practices. choice of instruments and tenor.Internal Debt Management Department The main activities of the Internal Debt Management Department include: Managing the Government’s debt in a risk efficient and cost effective manner. The Department operates through the following Divisions: (i) Government Borrowing Division: Manages the market borrowing programmes of the Government of India (including preparing an issuance calendar in consultation with the Government of India). Building a robust institutional framework of primary dealers. World Bank and G20 publications. (v) Management Information Systems Division: Maintains database pertaining to market infrastructure. monitors their bidding commitments in primary auctions. 83 Market . Regulation and development of financial markets in keeping with the best international standards and practices. (iv) Research Division: The nodal division for various committees. (ii) Dealing Operations Division: Interfaces with the Government securities market for purchasing securities from the secondary market for investment purposes by State Governments under schemes like Consolidated Sinking Fund (CSF) and Guarantee Redemption Fund (GRF) and monitors movement of yields of Government securities. (vi) Policy Coordination Division: Regulation and development of financial market products (excluding Forex regulation). manages the auction process and monitors State and Central cash balances. acts as the focal point for research contributions to IMF. among other things. LAF and OMO activities. provides data for various statutory and internal publications. the High Level Coordination Committee on Financial Markets and the State Finance Secretaries Conference.
Monitoring domestic macroeconomic developments. Monitoring. pre-policy consultation meetings with bankers. Managing the policy formulation and communication. Monitoring maintenance of CRR and SLR. meetings of the Technical Advisory Committee on Monetary Policy. journalists and media. and maintaining financial stability. 84 . SLR. from time to time. export credit refinance. These include policies on CRR. economists. Co-ordinating with operational departments and other institutions on specific policy issues.Market Monetary Policy Department The Monetary Policy Department formulates and implements the Reserve Bank’s monetary policy. Formulating monetary policy measures. industry. analysing and dissemination of data on interest rates in the banking sector. The objectives of monetary policy in India have evolved to include maintaining price stability. Monitoring and analysing data on sectoral credit deployment and advances against select sensitive commodities. key financial market indicators and global developments including. market stabilisation scheme (MSS) and open market operations (OMOs). Core Activities The core activities of the Department include: Preparing the Governor’s monetary policy statements and its quarterly reviews. financial markets. in the policy statements of the Reserve Bank. NBFCs. Authorising food credit limits. The relative emphasis placed on a particular objective at a particular point in time is modulated according to the prevailing macroeconomic conditions and outlook and is spelt out. Making projections on growth. The Department is an inter-disciplinary unit of the Reserve Bank with professional staff drawn from both operational and research Departments. monetary policy stance in select economies. Projecting market borrowing programme of the government consistent with monetary projections. ensuring adequate flow of credit to productive sectors of the economy to support economic growth. microfinance institutions. Formulating policy on interest rates of the banking sector. RRBs. repo and reverse repo rates under the LAF. inflation and monetary aggregates. organising Governor’s quarterly meetings with bankers.
Department of Banking Operations and Development The Department of Banking Operations and Development is responsible for regulation of commercial banks. and issuing necessary instructions. and continuously upgrading ‘Know Your Customer’ guidelines. Regulation of Private Sector Banks: Setting up of operations and winding up of domestic private sector commercial banks. Regulation of Foreign Banks and Overseas Offices of Indian Banks: Governing foreign banks’ entry and expansion. Overseeing the amalgamation. Strengthening the banking system by studying International Best Practices and Codes on Anti-Money Laundering (AML) and Combating Financing of Terrorism (CFT). depending on the circumstances. orderly development and conduct of banking operations. and fostering the overall health of the banking system. Regulation of Banks The Department is the focal point for providing the framework for regulation of domestic commercial banks. and risk management systems. reconstruction and liquidation of banking companies. which is aimed at protecting depositors’ interests. This includes: Formulation of Banking Policies: Prescribing prudential regulations on capital adequacy. Other functions of the Department include: Approving appointment of chief executive officers (private sector banks and foreign banks) and their compensation packages. and monitoring sources and deployment. Collecting. investment valuation. Advising the government on amendments to various banking statutes. accounting and disclosure standards. disseminating and sharing information from banks and notified All-India Financial Institutions on defaulters. approval of Indian banks to operate overseas. asset classification. Regulation of Select All India Financial Institutions: Regulatory oversight of the National Housing Bank. and SIDBI. income recognition. Bank / Branch Licensing The Department issues ‘licenses’ for opening banks and ‘authorisations’ for opening branches in the country. 85 Regulation and Supervision . The policies for ‘licences’ and ‘authorisations’ are adapted. Monitoring CRR and SLR maintenance. provisioning for loan and other losses.
connected lending. The Department also monitors financial conglomerates (FCs). including through off-site surveillance. on the basis of capital adequacy. control. On-site inspection is the main instrument of the Reserve Bank’s supervision. such as. and a system of prompt corrective action. The Department formulates and implements supervisory policies and strategy to ensure development of a safe. The Department supplements annual financial inspection with off-site surveillance and monitoring. Secretarial services to the Board for Financial Supervision (BFS). Regulating the audit function. Banks have to submit periodic Consolidated Prudential Reports (CPRs). The Department also periodically conducts reviews of macro and micro prudential indicators. asset quality. The broad functions of the Department are: On-site annual financial inspections and off-site monitoring and surveillance. operational results. A banking group also has to prepare Consolidated Financial Statements (CFS). reviews FC monitoring activities by the Standing Technical Committee and has discussions with the major entities in the FC. are also used for effective supervision. Certain other tools. management. which examines the financial condition of the banks in between on-site inspections to take appropriate supervisory action in time. reports of the Reserve Bank’s nominee directors on the boards of State owned banks and additional directors in private banks. 86 . including foreign banks in India. loan concentration. The Department formulates policy on bank audits and the appointment of statutory auditors. sound and efficient banking system. The Reserve Bank also carries out periodic surveys to ensure that banks fulfill license conditions. The Department serves as the nodal department for monitoring large value frauds in banks. conducts interest rate sensitivity analysis and other relevant studies. liquidity and interest rate risks. Formulating supervisory policy.Regulation and Supervision Department of Banking Supervision The Department of Supervision monitors operations of scheduled commercial banks. profile of ownership. all India financial institutions and local area banks. quarterly discussions with the CEO and senior management. Monitoring high-value fraud in financial institutions and NBFCs.
87 Regulation and Supervision . Attending to complaints relating to NBFCs and supplying data to various departments of the Reserve Bank and other organisations. workshops / seminars of trade and industry organisations. Loan Companies. Broadly. Study of operations and inspection of SCs / RCs. scrutiny and follow up. 2002. Attending to various operational issues raised by SCs / RCs. Publicity campaign for depositors’ education and awareness. Initiating deterrent action against errant companies. depositors’ associations. the functions of the Department are: (i) Regulatory Activities Formulating regulatory framework and issuing directions to NBFCs. Asset Finance Companies. (ii) Non-Deposit accepting NBFCs and (iii) Securitisation Companies (SCs) / Reconstruction Companies (RCs). The Department has 16 regional offices across the country. Off-site surveillance and scrutiny of various returns. Market intelligence gathering. Collection of returns and preparing reviews on SCs’ / RCs’ functioning. Monitoring of receipt of auditors’ exception reports/annual certificates (ii) Activities with regard to Securitisation and Reconstruction Companies Issuing certificate of registration for SC / RC under SARFAESI Act. (iii) Developmental Activities Co-ordination with State Governments and other regulators for enacting state legislations to curb unauthorised and fraudulent activities in the NBFC sector. Issuing / cancellation of certificates of registration for NBFCs. The major financial intermediaries regulated by the Department are (i) Deposit accepting NBFCs. Investment Companies and Infrastructure Finance Companies. Ensuring proper classification for NBFCs by classifying them into four categories namely.Department of Non-Banking Supervision The Department of Non-Banking Supervision regulates and supervises Non-Banking Financial Companies (NBFCs). Conducting on-site inspection.
collects data on portfolio investments through authorised dealer banks and approves the opening of liaison and branch offices in India by foreign companies. securitised instruments availed from non-resident lenders by Indian companies with minimum average maturity of three years. suppliers’ credit. and administering rules governing personal remittances and money transfers. except the contraventions under section 3 (a). External Commercial Borrowing: External commercial borrowing (ECB) refers to commercial loans in the form of bank loans. buyers’ credit. (iv) Development Activity Formulating risk management policies for foreign exchange exposures including derivative contracts. immigration charges. The Department monitors post-issue reporting and transfer of shares between residents and nonresidents. medical treatment. The Department grants the required approval for investments beyond this limit. This includes remittances for travel. gifts. on an application made by the contravener. Foreign Currency Accounts: The Department’s approval is required in cases where general permission is not available. (ii) Capital Account Transactions Foreign Direct Investment: Foreign investments in India should be in tune with the Foreign Direct Investment (FDI) policy. donations. The Department grants approval where powers have not been delegated.Regulation and Supervision Foreign Exchange Department The Foreign Exchange Department covers the following areas: (i) Current Account Transactions Trade: Monitoring export and import transactions delegated to authorised dealers. Collecting and compiling data on foreign exchange transactions on fortnightly basis for quick estimates of the Balance of Payments. consultancy services. etc. 88 . education. Remittances: Granting approvals in case of other non-trade current account remittances beyond the delegated powers of authorised dealers. Overseas Direct Investment: Indian companies and Registered Partnership firms are allowed to invest up to 400 per cent of their net worth under the automatic route in joint venture/wholly owned subsidiary abroad. ECBs can be availed of through automatic and approval routes. such as deposit accounts by Non-Resident Indians and Persons of Indian Origin and foreign currency accounts. (iii) Compounding The Reserve Bank is empowered to compound any contravention of the FEMA.
Regulates Regional Rural Banks and State/ District Central cooperative banks as provided under various Acts. Undertakes special studies relating to various aspects of rural credit. Formulates policy with regard to the development of micro-finance sector in the country. based on various statutory provisions. micro and small enterprises sector. it may. Deals with the National Bank for Agriculture and Rural Development (NABARD). including. and of various Government sponsored poverty alleviation programmes. (a) tender expert guidance and assistance to the National Bank (NABARD) (b) conduct special studies in such areas as it may consider necessary to do so for promoting integrated rural development”. Formulates policy with regard to Lead Bank Scheme and monitors the implementation thereof. particularly in the under-banked and un-banked regions/ pockets of the country and monitors the performance of banks in this area. including agriculture.Rural Planning and Credit Department The Rural Planning and Credit Department studies and coordinates issues related to rural credit and development. 1934 says: “The Bank may maintain expert staff to study various aspects of rural credit and development and in particular. Assesses quantitative and qualitative performance of commercial banks in priority sector lending. presently undertakes the following functions through its Central Office and 22 Regional Offices: Formulates policy on rural credit and priority sector lending. Formulates policy for enhancing financial inclusion. both on account of the historical compulsions of the Indian economy and the special responsibility cast on it in terms of the statute. agriculture and micro and small enterprises. The RBI Act. 89 Regulation and Supervision . The Rural Planning and Credit Department.
skill and expertise. the supervisory and follow-up actions are shared with the Central Office. reports and publications. The BMDs are responsible for overall monitoring of the functioning of UCBs. Bank Supervision: The Department has two Bank Monitoring Divisions (BMD). the Division also disburses claims to UCBs under various financial assistance schemes of the Central or State Government. The merger cell within the Department oversees the sanction and process of amalgamation of UCBs as a non-disruptive exit route for weak UCBs. and its functions can be divided into four parts: (i) licensing. (ii) banking policies. attends to compliance work relating to the directions of various authorities. The Department carries out its functions through its Regional Offices. (iii) supervision. It also grants approvals for expanding areas of operation for UCBs. one for scheduled and the other for non-scheduled UCBs for on-site inspection. replies to the Parliament questions. Banking Policies: The Banking Policy Division formulates policies for regulation and supervision of UCBs under the guidance of the Board for Financial Supervision (BFS) and the Standing Advisory Committee (SAC) for Urban Cooperative Banks. and coordinates with other bodies. It also provides data and support services for preparation of policies. While the Regional Offices carry out on-site inspections of UCBs. 90 . under the chairmanship of the Deputy Governor-inCharge. Licensing: The licensing division formulates eligibility criteria for the issue of banking licenses and authorising branch expansions for already licensed banks. Developmental Functions: The Department also undertakes training to the officials of UCBs to upgrade their knowledge. and (iv) development. The Off Site Surveillance segment of the Bank Supervision Division monitors the functioning of UCBs continuously through a set of periodical returns. under the guidance of an expert committee.Regulation and Supervision Urban Banks Department The Urban Banks Department regulates and supervises the banking activities of Primary (Urban) Cooperative Banks (UCBs). Besides the formulation of banking policies.
Administering Research Chairs and Fellowships set up by the Reserve Bank in 17 Universities and research institutions. such as. banking and financial policies. Promoting research and exchange of views with outside experts on topical issues through seminars. Providing policy support to the Government and background material for the Economic Survey. collaborative studies and endowment schemes. flow-of-funds. 91 Research . Report on Currency and Finance.R. banking and finance. They are delivered by distinguished personalities in the areas of macroeconomics. State Finances: A Study of Budgets of State Governments. Brahmananda. periodic BIS meetings and SAARC Finance. the IMF for the Article IV country consultations and supports work relating to G-20. Deshmukh. Handbook of Statistics on Indian Economy. Finance Minister’s Budget Speech and Parliament questions. RBI Bulletin and Statistical Supplement. such as. Undertaking estimation and forecasting of monetary and macroeconomic aggregates required for decision-making. shaping of monetary. balance of payments and external debt statistics. L. Providing advice and views on economic policy formulation.Department of Economic Analysis and Policy The Department of Economic Analysis and Policy undertakes policy supportive research on macroeconomic issues of national and international importance. financial saving and state finances. The Department is entrusted with multiple functions. special financial grants for supporting specific research projects and publications.D. Generating primary data on monetary and credit aggregates. Organising three annual lectures in the memory of C. prominent among which are the following: Studying and analysing domestic and international issues affecting the Indian economy.K. Other Functions The Department also undertakes the following functions: Coordinating with international institutions. Preparing other publications. Identifying and collecting data of historical value for writing the history of the Reserve Bank. Preparing statutory publications—the Annual Report and the Report on Trend and Progress of Banking in India. Jha and P. Macroeconomic and Monetary Developments.
rbi. Providing primary inputs for compiling balance of payment (BoP). Providing data on India’s private corporate business sector. This includes: Compiling banking statistics relating to cash reserve ratio. investments. corporate and external sector.in). conduct structured surveys and carry out specialised statistical analysis and forecasting. (ii) Designing and implementing regular sample surveys: (a) to generate forward looking indicators for monetary policy (e. and ad hoc surveys on financial inclusion. analysing corporate finances that form the basis for assessing linkages between corporate performance and monetary policy.. processing.org.rbi. order books.g. information technology.org. 92 .in) and Database on Indian Economy (. (iii) Developing methodologies for measurement. and improving the statistical system in various sectors of the economy.Research Department of Statistics and Information Management The Department’s mandate is to manage comprehensive statistical systems relating to monetary. corporate and the external sector. credit conditions. through the Bank’s Data Warehouse (. customer services. inflation expectations of households. The Department undertakes the following core activities: (i) Collecting. deposits. inventory and capacity utilisation. (iv) Preparing estimates of saving and capital formation for private corporate business sector in India for National Accounts Statistics (NAS). international banking. external debt and international investment position (IIP) under the IMF’s Special Data Dissemination Standard. banking. annual accounts and other banking indicators of commercial banks. estimation and forecast of important macro-economic indicators. credit. assessing the investment climate. (b) to fill in data gaps in compilation of BoP and IIP and conducting surveys. (vi) Coordinating statistical activities with national and international organisations. money supply. industrial outlook. and related systems developments. including the provision of electronic data dissemination platforms. large-scale data management. etc. professional forecasters projections on major economic indicators). storing and disseminating data on banking. (v) Providing technical support to other departments for statistical analysis. analysing.
The CRC also monitors release of half-yearly advertisements by ROs on the first Sunday of January and July every year. in consultation with BCSBI and IBA. The section also handles appeals received against the decision of the BO. disposal procedures. fairness and reasonableness in bank services and their charges. 93 Services . such as. For this purpose. Providing feedback and suggestions towards framing appropriate and timely guidelines for banks to improve the level of customer service and to strengthen their internal grievance redressal systems. mode of complaint receipt. Banking Ombudsman Section monitors complaint redressal through the IT enabled Complaint Tracking System. Policy and Research Section evolves policies. It prepares guidance manuals for updating knowledge and for ensuring consistency across BO offices. Right to Information Section processes all references received under the Right to Information Act and sends replies to the applicants. Public Grievance Redressal Section handles complaints against banks as swiftly as possible from the public as well as from Members of Parliament.Customer Service Department In July 2006. the Section collects monitoring returns like Citizens Charter. Broadly.Quarterly Returns. It also prepares the Annual Report of the Banking Ombudsman Scheme to enhance awareness about it. the Customer Service Department was created to consolidate customer service activities undertaken by various departments of the Reserve Bank. for ensuring transparency. disposed and pending. the activities of the Department are: Ensuring redressal of consumer grievances in banking services in an expeditious. fair and reasonable manner that will provide impetus to improved customer services in the banking sector on a continuous basis. It strives to make the Banking Ombudsman Scheme 2006 more customer friendly in areas. reports on unofficial visits to banks conducted by ROs and monthly status of complaints received. Enhancing the awareness of the Banking Ombudsman Scheme (BO). appeal provision and ownership. Complaint Redressal Section (CRC) monitors the work of Complaint Redressal Cells in the Regional Offices.
assessing currency needs. Under this mandate the Department undertakes the following functions: Planning.Services Department of Currency Management The Department of Currency Management provides focused attention on the management of currency notes and coins. Security Related Operations: Making policy with regard to security arrangements at issue offices and currency chests. 94 . (notes and coins) and ensuring adequate and timely supplies of notes and coins. The mandated functions of the Department include those related to: Management of currency notes. Forged Notes Vigilance Operations: Formulating policy on dealing with forged notes. and monitors customer service to the public in this regard. Currency Chest Operations: Formulating policy on the establishment of currency chests. Resource and Remittance Operations: Monitoring allotment of notes and coins among issue offices and logistics for their supply and overall resource operations. design. and organising public awareness on the features of genuine currency notes. Keeping circulation of counterfeit banknotes in check. and monitoring their operations. treasure in transit as well as periodical reviews of security arrangements. Note Processing Operations: Monitoring soiled notes accumulated at currency chests and their withdrawal and disposal through a mechanised and eco-friendly manner. such as. compiling data and sharing information on cases of forged notes with central and state Government. Monitoring currency chests and availability of customer service to the public by facilitating exchange of notes and coins. Research and Development: Evaluating the need for the introduction of new design banknotes and the security features that need to be incorporated in banknotes. printing and timely supply of currency notes and withdrawal of currency notes and distribution of coins. Note Exchange Operations: Attending to the policy regarding the exchange of soiled and mutilated notes and administration of the Reserve Bank of India (Note Refund) Rules through Reserve Bank of India Issue Offices and banks.
It is also overseeing implementation of the Core Banking Solution in the Bank. the CAS provides temporary liquidity in the form of Ways and Means Advances (WMA). a Central Accounts Section (CAS) at Nagpur maintains the principal government account. and maintains the internal accounts of the Reserve Bank. The banker to banks function and maintaining the internal accounts of the Reserve Bank is delivered through the Deposit Accounts Department (DAD) at the Regional Offices. acts as banker to banks. 95 Services . compiling weekly statements. and recovery of floatation and management charges from the government. management of floatation and redemption of debt. A RBI Remittance Facility Scheme provides a mechanism of funds transfer to banks and government departments. This includes. Government Debt Administration: The administration of public debt involves the accounting of government loans (market loans. Maintenance of Internal Accounts: The Department consolidates and maintains the internal accounts of the Reserve Bank. consolidates and maintains the final accounts of the government. financial institutions and international bodies the facility of non-interest bearing accounts they can use for inter-bank settlement. The Department of Government and Bank Accounts formulates policy and issues operational instructions to the above departments: Banker to Government: The Central Accounts Section at Nagpur maintains interest free accounts. Banker to Banks: The Reserve Bank provides banks. When there is a shortfall in cash balances. and the Public Debt Offices (PDO) at the Regional Offices provide depository services for government securities. etc). as well as matters relating to statutory auditors.Department of Government and Bank Accounts The Department of Government and Bank Accounts oversees the functions of the Reserve Bank as a Banker to government. preparing annual profit and loss statement and balance sheet of the Reserve Bank. At the operational level the various functions are as follows: The Public Accounts Departments (PAD) receives money and makes payments at various Regional Offices on behalf of the government. including administering the public debt of the government. maintenance of statutory reserves and managing their funds position. small saving schemes.
Retail payment systems include. The Reserve Bank is also a member of the SAARC Payments Council (SPC). The Reserve Bank has played an active developmental role both in setting up of new payment systems and in improving the safety and efficiency of existing ones (see Box 10). prepaid cards. 2007. both general and specific. The process is clearly laid down and the concerned regulatory departments are consulted when considering applications for authorisation. The Department also issues directives. 96 . India is a member of the Committee on Payment and Settlement Systems (CPSS) of the Bank for International Settlements. both for large value payment systems and retail payment systems for banking as well as non-banking entities.Services Department of Payment and Settlement Systems The Payment and Settlement Systems Act. 2007 empowers the Reserve Bank to regulate and supervise the payment and settlement systems in the country. The Real Time Gross Settlement (RTGS) System is an example of large value payment system. The functions of the Department include: Policy Formulation: Framing policies and prescribing standards governing the operations. ATM networks. Authorisation: Issuing the required authorisation to all persons/entities who wish to set up and operate large value and retail payment systems. credit/debit cards. cheque based system. supervision and oversight of payment and settlement systems in the country. to regulated entities and is empowered to lay down technical and operational standards for various payment systems and initiate penal action against entities violating the provisions of the Payment and Settlement Systems Act. The Department is actively associated with the working groups constituted by the CPSS for laying down standards with respect to various components of the payment and settlement systems. electronic funds transfer National Electronic Fund Transfer (NEFT) / Electronic Clearing Service (ECS). etc. Monitoring and Supervision: Monitoring and supervising entities authorised to operate payment systems through periodical reporting and on-site inspections.
The Department provides the secretariat to the Central Complaints Committee. The Department is the nodal point for all other Central Office Departments with regard to implementation of the provisions of the Right to Information Act. Framing policy and monitoring security arrangements in the Reserve Bank and providing necessary manpower for this purpose. Ensuring implementation of Central Vigilance Commission’s instructions and guidelines and to maintain vigilance administration in the Reserve Bank. monitoring and disseminating information in accordance with the provisions of the Right to Information Act. Coordinating.Department of Administration and Personnel Management The core functions of the Department of Administration and Personnel Management include: Implementing the Reserve Bank’s policies about recruitment. 2005 as applicable to the Reserve Bank. transfer and allotment of flats. Overseeing the conduct of employees and administering disciplinary actions as well as attending to cases involving misconduct of senior officers. Implementing guidelines regarding prevention and redressal of sexual harassment of women at workplaces. promotion. 97 Support . 2005. placement.
regulated entities. analysts. with information in English and Hindi and 11 regional languages. which is one of the main sources of information about the Reserve Bank for the public. RBI Website: The Department manages the RBI’s external website. organising conferences with senior editors. circulars. printing and publishing brochures and pamphlets. Publications: The Department helps disseminate the Reserve Bank’s main publications and staff studies through various channels. other central banks. market participants. The Reserve Bank’s communication strategy has evolved over tlme and focuses on the following key elements: Transparency for strengthening accountability and credibility. statistics and research. defence personnel. These include researchers. A separate website for financial education has been created as part of the RBI’s web portal. rating agencies. The website hosts all press releases. Clarity on the Reserve Bank’s role and responsibilities with regard to its multiple objectives. The balance and mix of communication products is tailored to the target audiences. and school children. academics. coordinating press conferences and interviews with RBI officials. It also includes the common person women. Managing expectations and promoting a two-way flow of information. Disseminating information. including through assisting in developing educational material. statistics. multilateral institutions.Support Department of Communication Communication is central to the functioning of central banks. senior citizens. issuing press releases. It also assists operational departments in editing. 98 . Financial Literacy The Department plays a crucial role in the Reserve Bank’s efforts towards financial literacy. speeches by senior management as well as publications. teleconferences. and Government agencies. and townhall meetings. Outreach to a Broader Group of Stakeholders: The Department assists and advises management in reaching out to other constituencies through briefings/presentations. media. Communication Tools Engagement with the Media: This includes building relationships with print and broadcast media. arranging training courses on central banking for the media.
Processing and disbursements of salary and other establishment related payments. which is a package for effecting establishment-related payments to all the staff members. 99 Support . such as. It also manages the Integrated Establishment System. as well as maintenance of various Funds Accounts. pension payments and funds-related payments. the Provident Fund. and Management of various Funds. Gratuity and Superannuation Fund.Department of Expenditure and Budgetary Control The task of the Department of Expenditure and Budgetary Control is to provide efficient and prompt services to present and past employees of the Reserve Bank in establishment-related payments. Ensuring adherence to budget discipline through quarterly and monthly reviews. The main functions of the Department include: Preparing the Reserve Bank’s budget. Administration of Expenditure Rules and Bank’s Housing Loan Rules. Acting as Central Office for establishment related matters in RBI.
Implementation of major IT projects and their management. Centralised Public Accounts Department System (CPADS). Support services for IT systems for smooth operations of the application systems through Data Centres and management of Local Area Networks (LAN) etc. information security. 100 . Monitoring progress of computerisation in banks.Support Department of Information Technology The Department of Information Technology is responsible for IT related services to the various functions of the Reserve Bank and the banking sector. such as. the Department attends to: Activities related to broad policy formulation for IT Architecture in the Bank. The Department discharges these roles through its various divisions. Information Technology Support Division. Broadly. such as. Structured Financial Messaging System (SFMS). All banking and non-banking applications are run from these data centres in a very secure and efficient way. Networking Division and System Development and Support Division. The three state-of-the-art Data Centres have been operationalised and managed by the Department. It also gives broad policy guidelines in critical areas. Policy and Operations Division. namely. Information Security and the implementation of these policies. the RTGS. the Public Debt Office – Negotiated Dealing System/Securities Settlement System (PDO-NDS/SSS).
the government and other central banks on HRD issues. to empower the staff so as to draw out the latent potential. performance and appraisal system. such as. internal communication. promotion and career progression. placement. deputation / secondment. Interface with other institutions. 101 Support . compensation policy. both) and medical facilities. Publication of House Journal. Annual Young Scholar Awards Scheme. organisational development. Formulate and administer the Staff Suggestion Scheme. The Department also sees to staff welfare. Review the appraisal system on an ongoing basis in order to make it an effective tool for HRD policy management. industrial relations. Functions of HRDD Evolve HR policies relating to recruitment. and to create conditions for a more wholesome quality of life on the work as well as personal front. mobility (transfer / rotation). training establishments. remuneration and reward mechanism. Design career and succession plans. Install and implement an effective counseling system. The mission of the Department is to create a facilitating environment to enhance the efficiency of the Bank.Human Resources Development Department The vision of the Human Resources Development Department is essentially to help the Bank carry out its central banking activities. Review and revitalise training functions. retirement and voluntary vacation. training and skills upgradation (policy and implementation. ‘Without Reserve’. Summer Placement.
The compliance position of major findings of MASI Reports is monitored by the Executive Directors’ Committee (EDC) and Inspection and Audit SubCommittee (IASC) of the Central Board. internal policies. The e-compliance monitoring and follow-up are done through an online Compliance Monitoring and Reporting System (COMORS).Support Inspection Department Inspection Department examines and evaluates the adequacy and reliability of existing systems and ensures that the work is carried out as per laws. procedures and Central Office instructions. periodically reviewed through an off-site Audit Monitoring Arrangement and on-site snap audits of offices (ROs / CODs / TEs). such as. decision making process. The efficacy of the whole system is also ensured through Concurrent Audit and Control Self Assessment Audit systems. The Department also provides support to other departments and coordinates with others for conducting technology audits and ISO / ISMS certification. communication process and other relevant aspects. Major Functions The Department prepares a Management Audit Report on the health of the auditee office highlighting areas. regulations. management effectiveness. 102 .
1999. rules. Government Securities Act. 1934. These references involve interpretation of the Constitution of India. Publishing an in-house Legal Journal (Quarterly) — ‘Legal News and Views’ dealing with developments in banking and other related laws. provisions of the Reserve Bank of India Act. 1949. regulations and statutory notifications related to banking and finance. Foreign Exchange Management Act. Other functions include: Drafting legislation. Banking Regulation Act. Attending to investigation of title of land for acquisition of premises for the Reserve Bank and handling the documentation relating to construction of buildings. The Department is also required to interpret the rules and regulations governing the Reserve Bank’s staff and to deal with legal issues relating to industrial relations. Payment and Settlement Systems Act. 2007 and various other statutes.Legal Department The main function of the Legal Department is to tender legal advice on matters referred to it by the various departments and offices of the Reserve Bank. Briefing the counsel appearing in courts on behalf of the Reserve Bank and drafts pleading. 103 Support . 2006.
value works/projects of Estate Departments across the country. keeping in mind ecological and environmental concerns. conserving resources like energy and water and auditing the use of these resources. consolidation and disposal of office and residential space. acquisition. Dead Stock management through integrated Estate Management Software system across offices. The Department frames policies and guidelines on physical infrastructure. maintenance. The current thrust-areas of the Department are as follows: Promoting greater environmental consciousness.Support Premises Department The Premises Department’s responsibility is to create and maintain premisesrelated infrastructure. 104 . Rationalisation of Bank’s properties. It allocates capital budgets to Regional Offices and monitors high.
Conducting training programmes and workshops for staff to enhance the use of Hindi in the internal working of the Reserve Bank. the Annual Report and Report on Trend and Progress of Banking in India. collecting data. Celebrating Hindi Samaroh is also an important activity of the Department. conducting developmental activities and translation. such as. The department also publishes books in Hindi on banking subjects. Ensuring uniformity in translation through preparation of ‘Banking Shabdavali’ and ‘Banking Paribhasha Kosh’. including that of statutory publications. Ensuring day to day translation of press releases and various documents. Organising the Rajbhasha Shield competition for public sector banks and financial institutes as well as for the Reserve Bank’s own offices and departments. such as. holding quarterly meetings of the official language Implementation Committee. submitting different reports to Government and Committee of Parliament and issuing instructions and guidelines for smooth implementation of the official language. The Department’s activities are the following: Making policy for progressive use of Hindi as per Government guidelines and monitoring the progress through various means. 105 Support .Rajbhasha Department The functions of the Rajbhasha Department include implementation of the official language policy of the Government of India. preparing reviews. The evaluation work on behalf of the Ministry of Home Affairs for the Indira Gandhi Shield for Rajbhasha for banks is also done by the Rajbhasha Department. and brings out the only Hindi magazine on banking — ’Banking Chintan Anuchintan’. The Department also conducts all India Hindi essay writing and House Journal competition for banks.
(iv) Administrative and Staff Services The Department is the administrative hub for five central office departments — IDMD. set up in the Department. in consultation with the Central Board. Some of the major functions of the Department are discussed below: (i) Central Bank Governance The Department assists Senior Management in the decision making process by providing secretarial and logistics support.Support Secretary’s Department The Department primarily deals with the governance issues of the Reserve Bank involving the constitution and functioning of the Central Board. This includes secretarial work connected with the seven meetings of the Central Board each year in the four metros and three other state capitals. It also provides requisite protocol support to the visitors. 106 . its Committee and the Government of India. The Department also facilitates review and obtains the requisite approvals for the revision of the pay and allowances and facilities extended to the Governor and Deputy Governors from time to time. DoC and FSU and supports the maintenance of staff records. (v) Local Board Cell A Local Board Cell (LBC). weekly meetings of the Top Management Group (TMG) and the weekly Deputy Governors’ Committee meetings. annual meeting of the Administrators of the Reserve Bank of India Employees’ Provident Fund. MPD. allows for two-way communication between the various Central Office Departments and the Local Boards. governments and international agencies. by rotation. and constitution of the Central and Local Boards. (iii) International Relations and Protocol Services The Department facilitates the visits and meetings of representatives of other central banks. retirement and relinquishing of charge of the Governor and Deputy Governors. FMD. its Committees and the Top Management. 46 weekly Committee meetings. (ii) Top Management Services – Coordination with Government The Department attends to the work relating to the joining. terms and conditions of their service.
Indian Bank Act to bring banks within the ambit of the Reserve Bank. Reserve Bank of India Bill received the assent of the Governor-General. Sir C. strongly recommending the establishment of the Reserve Bank. The Bill was referred to a Joint Committee to resolve some of the controversial clauses.June. to be named as Reserve Bank of India. introduced in the Legislative Assembly. Report of the India Office Committee released. Sir Osborne Smith was appointed the first Governor of the Reserve Bank of India. Government of India published the “New Gold Standard and Reserve Bank Bill”. The Reserve Bank issued its own bank notes.15 Year 1913 1926 Chronology of Important Events in the History of the Reserve Bank Events The Royal Commission on Indian Finance and Currency (Chamberlain Commission) underlined the need for a central bank for India. The government introduced “The Gold Standard and Reserve Bank of India” in the legislature. which was set up after the India Office Committee. This note had the status of a rupee coin and represented the introduction of official fiat money in India. Government clarified that it did not intend to bring the Reserve Bank Bill before the legislature in the near future. Report of the Indian Central Banking Enquiry Committee released. Reserve Bank of India Bill passed by the Assembly. Sir James Braid Taylor assumed office of the Governor. The Reserve Bank’s accounting year changed from January -December to July. Hilton Young Commission recommended the establishment of a central bank in India. Deshmukh took over as Governor. adopted the 1928 Reserve Bank Bill as the basis and proposed certain amendments to the Bill. The silver rupee replaced by the quaternary alloy rupee. One Rupee note reintroduced. Reserve Bank of India Bill was passed by the Council of States. Reserve Bank of India Bill. D. recommending establishment of Reserve Bank of India as a private shareholders’ bank. as amended by the Joint Committee. January 1927 March 1927 January 1928 February 1929 1931 March 1933 July 1933 September 1933 December 1933 February 1934 March 1934 April 1935 July 1937 March 1937 January 1938 September 1939 1939 March 1940 1940 August 1943 1944 107 . drafted on the basis of London Committee recommendations. London Committee. The Reserve Bank acted as banker to the Government of Burma and was also responsible for note issue in Burma as per the Burma Monetary Arrangements Order. Introduction of Exchange Controls in India under Defence of India Rules. The Public Debt Act passed by the Government enabled the consolidation of laws relating to Government securities and management of public debt by the Reserve Bank. The Reserve Bank of India was created as a private share holders’ bank.
The Reserve Bank was nationalised. Establishment of Department of Banking Operations and Development and Research and Statistics Department in the Reserve Bank. Agricultural Refinance Corporation was set up as a subsidiary of the Reserve Bank. Palai Central Bank Ltd (Kerala) and Lakshmi Bank (Maharashtra). Industrial Development Bank of India came into existence with the Reserve Bank wholly contributing the capital of Rs. Indian rupee was devalued by 36. Foreign Exchange Regulation Act. 1949 came into force. Banking Companies Act. Unit Trust of India came into existence with 50 per cent share holding by the Reserve Bank. Sir Benegal Rama Rau assumed office as Governor. System of note issue was changed from proportional reserve system to minimum reserve system. Devaluation of the Rupee by 30. This formed the statutory basis of bank regulation and supervision in India. 10 crore. Bhattacharya appointed as Governor. The Reserve Bank ceased to function as Central Bank of Burma. Shri P.5 per cent. Foreign Exchange Regulation Act was passed. The Reserve Bank ceased to function as Central Bank of Pakistan. Deposit Insurance Corporation came into existence. The Reserve Bank launched a pioneering project of All India Rural Credit Survey. Shri HVR Iyengar appointed as Governor. The Imperial Bank was nationalised and renamed as State Bank of India with the Reserve Bank taking a 60 per cent stake in it.000 and Rs 10.000 were demonetised to curb unaccounted money. Cooperative banks brought under the ambit of regulation of the Reserve Bank. Failure of two commercial banks. This led to deliberations on the need for deposit insurance in India. Interim arrangements for bank supervision were put in place by an ordinance. Ambegoankar was appointed as Governor. Introduction of decimal coinage. Industrial Finance Corporation of India was established on the recommendation of the Central Board of the Reserve Bank.5 per cent consequent on the identical devaluation of Pound Sterling.February 1945 1945 January 1946 1946 March 1947 1947 1948 June 1948 January 1949 March 1949 July 1949 September 1949 April 1950 1952 September 1954 May 1955 1956 October 1956 1956 January 1957 March 1957 1961 1962 March 1962 July 1963 1963 February 1964 June 1964 1966 June 1966 Non-scheduled banks were allowed to open accounts with the Reserve Bank. Shri K. 108 . 1949 came into force. The Reserve Bank set up Bankers’ Training College at Mumbai (earlier Bombay).C.G. namely. Rs 1. Reserve Bank Staff Training College (RBSC) was established. Introduction of selective credit controls. replacing the earlier interim arrangements. High Denomination Bank Notes of Rs 500.
Foreign Exchange Regulation Act. Demonetisation of high denomination notes (Rs 1. The Foreign Exchange Regulation Act. This led to nationalisation of 14 commercial banks. Rangarajan (Deputy Governor) Committee Report on computerisation in banking system.K. Regional Rural Banks Act. 1947 was amended. state and urban cooperative banks with paid-up capital of Rs 1 lakh or more were covered under the scheme. The Bill for setting up of the Agricultural Credit Corporation passed in Parliament. Agricultural Refinance Corporation (ARC) was renamed as Agricultural Refinance and Development Corporation (ARDC). Adarkar appointed as Governor. Industrial Development Bank of India delinked from the Reserve Bank. Deposit Insurance Corporation and Credit Guarantee Corporation of India Ltd.000. Cooperative Bankers Training College was established at Pune. Shri B. The government propounded the tenet of “Social Banking”. Exchange rate of Rupee was linked to the basket of currencies of major trading partners. 1969 July 1969 September 1969 September 1969 May 1970 June 1970 January 1971 December 1972 September 1973 January 1974 1975 May 1975 August 1975 November 1975 February 1976 February 1976 May 1977 December 1977 January 1978 July 1978 April 1979 July 1982 September 1982 1984 109 . 1973 came into force.G. Puri was appointed as Governor. Basic Statistical Returns (BSR) Scheme introduced to collect banking statistics.N. Sengupta was appointed as Governor. Demonetisation of quaternary coins. Jagannathan appointed as Governor. National Institute of Bank Management (NIBM) established at Mumbai which was subsequently shifted to Pune. The Deposit Insurance Corporation (Amendment) Bill. Shri L. Jha appointed as Governor. The size of the bank notes was reduced. Credit Guarantee Corporation of India was established. 1968 came into force. Dr. MICR Clearing was introduced. Release of Sukhomoy Chakravarty Report on monetary measurement. R. Dr. Dr. Shri S. C. Manmohan Singh was appointed as Governor. 1976 received assent of the President. C. Shri N. Narasimham was appointed as Governor. Patel was appointed as Governor. were merged and renamed as Deposit Insurance and Credit Guarantee Corporation (DICGC). Shri K.March 1966 April 1967 July 1967 April 1968 May 1968 December 1968 Department of Financial Companies was established. Shri M. Six more Indian scheduled commercial banks were nationalised.000) effected. National Bank for Agriculture and Rural Development (NABARD) was set up. The Banking Companies (Acquisition and Transfer of Undertakings) Ordinance 1969 promulgated. All central.000 and Rs 10. Rs 5. I. The Cooperative Bankers’ Training College was renamed as College of Agricultural Banking.
marking the beginning of RBI’s role in financial markets. development financial institutions (DFIs) and the capital market in the years to come. The Reserve Bank becomes a member of the Bank for International Settlements. worked out to 17. July 1991 August 1991 November 1991 March 1992 December 1992 1993 August 1994 September 1994 November 1994 February 1995 June 1995 1996 July 1996 110 . Paradigm shift in economic management and the Reserve Bank steps in as the facilitator. pound sterling. Two-step downward adjustment of the rupee in terms of the intervention currency. privatisation. Rupee made convertible on the Current Account. Shri A. Board for Financial Supervision constituted as a Committee of the Central Board of Directors. functions and procedures of the financial system (Chairman: Shri M. and globalisation and contributory presence in world bodies. Rangarajan was appointed as Governor. The Honourable Prime Minister Rajiv Gandhi graced the inaugural function. which formed the basis of financial sector reforms relating to banks. Bharatiya Reserve Bank Note Mudran Limited established as a fully owned subsidiary of the Reserve Bank. Hyderabad was established by the Reserve Bank as an autonomous entity. Narasimham). Institute for Development and Research in Banking Technology. Dr.38 per cent. 26 a dollar. The value of the rupee was adjusted downwards in two stages. A dual exchange rate system called Liberalised Exchange Rate Management System (LERMS) introduced. Unified Exchange Rate was introduced. Malhotra was appointed as Governor. made wide-ranging recommendations. C. 1991. Indira Gandhi Institute of Development and Research was set up. Venkitaramanan was appointed as Governor. organisation. Committee on the Financial System submitted its report in November 1991. the rupee exchange rate was anchored on a rupee-US dollar rate close to Rs. The Reserve Bank and the Government of India signed an agreement as per which automatic monetisation of the budget deficit through the issue of ad-hoc treasury bills would phase out over a period of three years. was set up. Support to economic reforms.1985 January 1985 February 1985 December 1987 April 1988 July1988 1990 December 1990 1991 The Reserve Bank celebrates its Golden Jubilee Year. A high-powered Committee on the Financial System (CFS) was constituted by the Government of India in August 1991 to examine all aspects relating to the structure. liberalisation. Ghosh was appointed as Governor. National Housing Bank was set up under the National Housing Bank Act. 1987. at Mysore and Salboni. respectively. Shri R. Forex management under deregulated regime led to a series of measures culminating in FEMA 1999. India attained the status of Article VIII of the Articles of Agreement of the IMF. Discount and Finance House of India Ltd. Small Industries Development Bank of India was set up. It commenced printing of notes on June 1 and December 11. Banking Ombudsman scheme for redressal of customer grievance against the banking sector introduced. Shri S. Thereafter. on July 1 and 3.N.
1999 replaced FERA. Cheque truncation was introduced in Delhi region as a pilot project. Foreign Exchange Management Act. FEMA became operational. From October 2009. Bharatiya Reserve Bank Note Mudran became private limited company. The framework for further strengthening the banking sector was provided by the Committee on Banking Sector Reforms (Chairman: Shri M. D. Subbarao was appointed as Governor. 111 . 2007 came into force with effect from August 12. the RBI began the process of exit from the expansionary monetary policy. 2008. Market Stabilisation Scheme was launched. The Reserve Bank purchased 200 mts of gold under IMF’s limited gold sales programme. Payment and Settlements System Act. Dr. The Reserve Bank enters its Platinum Jubilee year. Dr. Narasimham) The Monetary Museum Web Site launched. ending automatic monetisation of fiscal deficits. Customer Service Department was set up at the Reserve Bank. Revamped Banking Ombudsman Scheme came into effect. RBI pursued an accommodative monetary policy beginning mid-September 2008 to mitigate the adverse impact of the global financial crisis on the economy. “Clean Note Policy” introduced for better currency management. Clearing Corporation of India was established. Bimal Jalan was appointed as Governor.September 1996 April 1997 November 1997 April 1998 December 1998 1999 December 1999 June 2000 April 2001 March 2002 September 2003 February 2004 November 2004 January 2006 March 2006 July 2006 2008 September 2008 December 2008 2008/9 April 2009 July 2009 November 2009 2009/10 The Reserve Bank’s Web site became operational The Reserve Bank and the Government of India agreed to replace the system of ad-hoc Treasury Bills by Ways and Means Advances. The Reserve Bank Monetary Museum was set up in Mumbai.V. Y. Dr. Banking Codes and Standards Board of India constituted. Incorporation of National Payment Corporation of India. The Reserve Bank establishes a new department — Financial Stability Unit. 1973. Reddy was appointed as Governor.
Arbitrage and Costs Monthly i) Monetary and Credit Information Review ii) RBI Bulletin Weekly i) Weekly Statistical Supplement 112 . 2007-08 iii) Basic Statistical Returns of Scheduled Commercial Banks in India iv) Branch Banking Statistics v) Directory of Commercial Bank Offices in India vi) Handbook of Monetary Statistics of India vii) Handbook of Statistics on Indian Economy viii) Manual on Financial and Banking Statistics ix) Report on Currency and Finance x) State Finances : A Study of Budgets xi) Statistical Tables Relating to Banks in India Half-Yearly i) Report on Foreign Exchange Reserves Quarterly i) Macroeconomic and Monetary Developments ii) Occasional Papers iii) Quarterly Statistics on Deposits and Credit of Scheduled Commercial Banks iv) Survey of Professional Forecasters v) Variation to Foreign Exchange Reserves in India: Sources.1 RBI Publications Annual a) Statutory i) Annual Report ii) Trend and Progress of Banking in India b) Others i) A Profile of Banks ii) Annual Report on Banking Ombudsman Scheme.Annex .
RBI at 75 Payment Systems in India Perspectives on Central Banking — Governors Speak ( 1935 to 2010 ) RBI .Governors Speak 113 . Lessons and Preventive Measures’ DRG Studies Handbook of Instructions-Basic Statistical Returns 1 and 2 Handbook of Statistics on State Government Finances India’s Financial Sector an Assessment Vol.1981 ( 3 Volumes ) 50 Years of Central Banking . 2002 The Banking Ombudsman Scheme.Staff Studies Reports on Currency and Finance . 2006 The Reserve Bank of India History 1935 .Special Edition Reserve Bank of India: Functions and Working The Banking Ombudsman Scheme. I to VI 2009 Mint Road Milestones .Note Refund Rules RBI .Other Important Publications Book on ‘External Debt Management: Issues.
Annex - 2
List of Abbreviations
American Depository Receipts Available for Sale Adjusted Net Bank Credit Agricultural Refinance Corporation Agricultural Refinance and Development Corporation Automated Teller Machine Business Correspondent Banking Codes and Standards Board of India Business Facilitator Board for Financial Supervision Bank for International Settlements Banking Ombudsman Balance of Payments Board for Regulation and Supervision of Payment and Settlement Systems Bharatiya Reserve Bank Note Mudran Private Limited Basic Statistical Returns Current Account Convertibility
Capital Adequacy, Asset Quality, Management, Earnings, Liquidity, Systems and Control
A
ADRs AFS ANBC ARC ARDC ATM
B
BC BCSBI BF BFS BIS BO BoP BPSS BRBNMPL BSR
C
CAC CAMELS CAS CBS CCIL CCP CDSL CE of OBE CFMS CFSP CMB CPPAPS CRAR CRR CSD CSF CTS
Central Accounts Section Core Banking Solution Clearing Corporation of India Limited Central Counter Party Central Depository Services Ltd Credit Equivalent of Off-Balance Sheet Exposures Centralised Funds Management System Committee on Financial Sector Plan Cash Management Bill Committee on Procedures and Performance Audit on Public Services Capital to Risk-Weighted Assets Ratio Cash Reserve Ratio Customer Service Department Consolidated Sinking Fund Cheque Truncation System
114
D
DAD DBOD DBS DCC DCCB DEAP DICGC DNBS DPSS DSIM
Deposit Accounts Department Department of Banking Operations and Development Department of Banking Supervision District Consultative Committee District Central Cooperative Bank Department of Economic Analysis and Policy Deposit Insurance and Credit Guarantee Corporation Department of Non-Banking Supervision Department of Payment and Settlement Systems Department of Statistics and Information Management Electronic Benefit Transfer External Commercial Borrowings Electronic Clearing Service Exchange Earners’ Foreign Currency Electronic Funds Transfer Export Import Bank of India Fuller Capital Account Convertibility Foreign Currency Assets Foreign Currency Convertible Bond Foreign Currency Exchangeable Bond Foreign Currency Non-Resident (Banks) Foreign Direct Investment Foreign Exchange Management Act Foreign Exchange Regulation Act Foreign Institutional Investors Fixed Income Money Market and Derivatives Association of India Financial Literacy and Credit Counseling Centres Financial Markets Committee Forward Rate Agreements Fiscal Responsibility and Budget Management Global Depository Receipts Government of India Guarantee Redemption Fund Government Securities Held for Trading High Power Committee on Urban Cooperative Banks 115
E F
EBT ECBs ECS EEFC EFT Exim Bank FCAC FCAs FCCB FCEB FCNR(B) FDI FEMA FERA FIIs FIMMDA FLCCs FMC FRAs FRBM
G H
GDRs GoI GRF G-Sec HFT HPC on UCBs
HSRS HTM HVC IBA
High Speed Reader Sorter Held-to-Maturity High Value Clearing Indian Banks’ Association Industrial Credit and Investment Corporation of India Information and Communication Technology Industrial Development Bank of India Internal Debt Management Department Indian Depository Receipt Institute for Development and Research in Banking Technology Indira Gandhi Institute of Development Research International Monetary Fund Innovative Perpetual Debt Instruments Interest Rate Swap Joint Venture Kisan Credit Card Know Your Customer Liquidity Adjustment Facility Liberalised Exchange Rate Management System Long Term Rural Cooperative Credit Institution MCX Stock Exchange Magnetic Ink Character Recognition Monetary Policy Department Micro and Small Enterprise Micro, Small and Medium Enterprises Development Market Stabilisation Scheme National Bank for Agriculture and Rural Development Non-Banking Financial Companies Deposit taking NBFC Non-deposit taking NBFC Negotiated Dealing System Negotiated Dealing System – Order Matching Net Demand and Time Liability National Electronic Clearing System National Electronic Funds Transfer North Eastern Region
I
ICICI ICT IDBI IDMD IDR IDRBT IGIDR IMF IPDIs IRS JV KCC KYC LAF LERMS LTCCI MCX-SX MICR MPD MSE MSMED MSS
J K L M
N
NABARD NBFCs NBFC-D NBFC-ND NDS NDS - OM NDTL NECS NEFT NER
116
NGO NI Act NIBM NoF NPAs NPCI NR(E)RA NREGS NRI NRO NSDL Non-Government Organisation Negotiable Instruments Act National Institute of Bank Management Net owned Funds Non-Performing Assets National Payments Corporation of India Non-Resident (External) Rupee Account National Rural Employment Guarantee Scheme Non-Resident Indian Non.Resident Ordinary Account National Securities Depository Limited Open Market Operation Off-Site Monitoring and Surveillance Off-Site Surveillance Over-the-Counter Primary Agricultural Credit Society Public Accounts Department Permanent Account Number Primary Cooperative Agriculture and Rural Development Banks Primary Dealers Association of India Public Debt Office Public Debt Office .Negotiated Dealing System Primary Dealers Person of Indian Origin Payment and Settlement Systems Act Quarterly Discussion Risk Based Supervision Reserve Bank Staff College Resident Foreign Currency Account Resident Foreign Currency (Domestic) Account Rural Infrastructure Development Fund Regional Rural Banks Real Time Gross Settlement Special Agricultural Credit Plans State Bank of India State Cooperative Agriculture and Rural Development Banks 117 O P OMO OSMOS OSS OTC PACS PAD PAN PCARDBs PDAI PDO PDO-NDS PDs PIO PSS Act QD RBS RBSC RFC RFC(D) RIDF RRBs RTGS Q R S SACPs SBI SCARDBs .
SDDS SDR SEBI SGL SHGs SIPS SLBC SLR SMEs SPMCIL SSI StCB Special Data Dissemination Standards Special Drawing Rights Securities and Exchange Board of India Subsidiary General Ledger Self-Help Groups Systemically Important Payment System State Level Bankers’ Committee Statutory Liquidity Ratio Small and Medium Enterprises Security Printing and Minting Corporation of India Ltd. Small Scale Industries State Co-operative Bank Technical Advisory Committee Task Force for Urban Co-operative Banks Treasury Bills Urban Cooperative Banks United States Dollar Unit Trust of India When Issued Ways and Means Advances Wholly Owned Subsidiary Zonal Training Centre T U W Z TAC TAFCUBs TBs UCBs USD UTI WI WMA WOS ZTC 118 .
119 .
120 . | https://www.scribd.com/doc/61939408/Funtions-of-Rbi-WWE080910 | CC-MAIN-2017-34 | en | refinedweb |
import "golang.org/x/exp/io/spi"
Package spi allows users to read from and write to an SPI device.
Example illustrates a program that drives an APA-102 LED strip.
Code:
dev, err := spi.Open(&spi.Devfs{ Dev: "/dev/spidev0.1", Mode: spi.Mode3, MaxSpeed: 500000, }) if err != nil { panic(err) } defer dev.Close() if err := dev.Tx([]byte{ 0, 0, 0, 0, 0xff, 200, 0, 200, 0xff, 200, 0, 200, 0xe0, 200, 0, 200, 0xff, 200, 0, 200, 0xff, 8, 50, 0, 0xff, 200, 0, 0, 0xff, 0, 0, 0, 0xff, 200, 0, 200, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }, nil); err != nil { panic(err) }
type Devfs struct { // Dev is the device to be opened. // Device name is usually in the /dev/spidev<bus>.<chip> format. // Required. Dev string // Mode is the SPI mode. SPI mode is a combination of polarity and phases. // CPOL is the high order bit, CPHA is the low order. Pre-computed mode // values are Mode0, Mode1, Mode2 and Mode3. The value of the mode argument // can be overriden by the device's driver. // Required. Mode Mode // MaxSpeed is the max clock speed (Hz) and can be overriden by the device's driver. // Required. MaxSpeed int64 }
Devfs is an SPI driver that works against the devfs. You need to have loaded the "spidev" Linux module to use this driver.
Open opens the provided device with the specified options and returns a connection.
Close closes the SPI device and releases the related resources.
SetBitOrder sets the bit justification used to transfer SPI words. Valid values are MSBFirst and LSBFirst.
SetBitsPerWord sets how many bits it takes to represent a word, e.g. 8 represents 8-bit words. The default is 8 bits per word.
SetCSChange sets whether to leave the chipselect enabled after a Tx.
SetDelay sets the amount of pause will be added after each frame write.
SetMaxSpeed sets the maximum clock speed in Hz. The value can be overriden by SPI device's driver.
SetMode sets the SPI mode. SPI mode is a combination of polarity and phases. CPOL is the high order bit, CPHA is the low order. Pre-computed mode values are Mode0, Mode1, Mode2 and Mode3. The value can be changed by SPI device's driver.
Tx performs a duplex transmission to write w to the SPI device and read len(r) bytes to r. User should not mutate the w and r until this call returns.
Mode represents the SPI mode number where clock parity (CPOL) is the high order and clock edge (CPHA) is the low order bit.
Order is the bit justification to be used while transfering words to the SPI device. MSB-first encoding is more popular than LSB-first.
Package spi imports 6 packages (graph) and is imported by 7 packages. Updated 2017-06-04. Refresh now. Tools for package owners. | http://godoc.org/golang.org/x/exp/io/spi | CC-MAIN-2017-34 | en | refinedweb |
Number of downloads: 448Hi,
I will be using the basic example from the tutorial here
The code is reproduced here:
Note: There is no change in web.xml
public class CheckServlet extends HttpServlet { static int count=0; public void init(ServletConfig config) throws ServletException { super.init(config); } public void service (HttpServletRequest request,HttpServletResponse response) throws IOException { PrintWriter writer = response.getWriter(); writer.println(++count); writer.println("The name as specified in web.xml :" + getServletName() ); } }
The count in above code is static and hence every user sees incremented value when he hits the servlte. But now we want that the requests coming from a particular browser be incremented from 0 onwards. Any request coming from some other browser will get an initial value of count as 0.
The code for that is:
import javax.servlet.*; import javax.servlet.http.*; import java.io.PrintWriter; import java.io.IOException; public class CheckServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void service (HttpServletRequest request,HttpServletResponse response) throws IOException { response.setContentType("text/html"); HttpSession session = request.getSession(true); Integer iCount = (Integer)session.getAttribute("count"); if(iCount == null) { iCount = new Integer(0); session.setAttribute("count",iCount ); } else { iCount = new Integer(iCount.intValue() + 1); session.setAttribute("count",iCount ); } PrintWriter writer = response.getWriter(); writer.println("<html>"); writer.println("<title>Welcome</title>"); writer.println("<body>"); writer.println("The name as specified in web.xml :" + getServletName()); writer.println("count is :" + iCount); writer.println("</body>"); writer.println("</html>"); } }
The most important line in this program is :
HttpSession session = request.getSession(true);
The above line gets a session object from request sent by the browser. The very first request doesn't has any but then the server will insert one in its first response to browser because of the parameter "true" bein sent to getSession method.
The session object can store attributes with some associated values with it. First time as the session is not present the vakue of the attribute will be null as it won't be present. In that case, we insert a count (initialized to 0) in the session object and in every subsequent object we keep on incrementing the count (that shows something is preserved by the browser and server).
Now if the servlet is hit some other browser, the initial count will always be 0 for the first request.
The session object is identified by the server by the session id. In fact, when a session is associated to first response, a parameter named as jSessionID is also appended to the URL and the browser sends the same session id back to server on each subsequent request which helps the server to recognize its clients.
This approach is known as URL rewriting because of the session id being appended to the URL.
The whole web application has been attached as zip file alongwith. You can extract its contents into your webapps directory and try this example. | http://www.dreamincode.net/forums/topic/45511-servets-maintaining-sessions-using-url-rewriting/ | CC-MAIN-2017-34 | en | refinedweb |
Well, you have gone through a lot of theory to get you started with your first program.
So let’s get your hands dirty.
Go to the command prompt if you are on linux and type : python. You will now be prompted into a shell where you can enter python commands.
Open PyCharm editor to get you started with your first python program. Click on File -> New Project and give the name of the project.
Right click on the project and click New->Python File and give it a name.
TRY IT OUT:
# Create a variable var and assign it a value 7
var = 7
print var
# Change the value of var to 3
var =3
# Here’s some code that will print var to the console:
print var
Here # is used to add comments while you are coding. Comments is a good way to recognize what you are going and it is always a good practice to write your code with comments.
Reserved Words
The following list shows the Python keywords. These are reserved words and they cannot be used as constants or variables.
Whitespace
In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it.
TRY IT OUT:
def cricket():
players = 12
return players
print cricket()
def is used to create cricket() which can be called to return players but when you run this function you will get an error saying ‘IndentationError: expected an indented block’.
So you need to indent cricket function to get to know when function started and when it ended.
def cricket():
players = 12
return players
print cricket()
This now will print 12 in the console as you have indented the body of the function.
Things you learned:
Yes We will allow, you can provide us valuable piece of Content, we will publish after approval. | http://knowledgetpoint.com/python/writing-your-first-python-program/ | CC-MAIN-2017-34 | en | refinedweb |
Announcements
TunahMembers
Content count45
Joined
Last visited
Community Reputation126 Neutral
About Tunah
- RankMember
[.net] resolved problem, can be closed
Tunah replied to Elovoid's topic in General and Gameplay Programming[quote name='Elovoid' timestamp='1308224117' post='4824036'] Edit: Problem solved, based on misunderstanding stuff and shouldn't be read by others to keep them from making the same mistakes [/quote] Unless of course others find your post because they're misunderstanding like you were but then they read the follow up posts and figure it out!
Please advice : Unable to record sound with this VB recording program
Tunah replied to KF's topic in General and Gameplay ProgrammingIf you look at the inputs that are available alongside the microphone, you may find an input named "What U Hear" (pardon the retarded spelling, but that's what they call it.) If that inputs is available, you can record everything that's currently playing. I don't know how to capture the final mixed audio without one of those, unfortunately. I haven't used the MCI API so I can't help you with figuring it out, sorry. Edit: I googled for "what u hear" and found this. The input can be called "Stereo Mix" on some cards. Have a look at this. [Edited by - Tunah on April 15, 2010 3:18:42 AM]
Please advice : Unable to record sound with this VB recording program
Tunah replied to KF's topic in General and Gameplay ProgrammingIf you load the file in Windows Media player, do you get any sound then? Is the file of some length and not just 0? You should also check the return value from mciSendString, which would be 0 if no errors occur. Another thing you should verify is if you actually have a microphone selected in the control panel for the sound card. Either bring it up by double clicking the speaker icon next to the clock or just click Start -> Run and then "sndvol32". Then select Properties under the Options menu. Select "Recording" under the "Adjust volume for" group box. Click Ok. Make sure that the proper input is selected by clicking the checkbox underneath it.
[.net] Most efficient way of doing a IntPtr to IntrPtr copy ?
Tunah replied to Niksan2's topic in General and Gameplay ProgrammingSince this thread was bumped and I didn't see it mentioned, I use this: [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] static extern void CopyMemory(IntPtr Destination, IntPtr Source, uint Length); I compared it to the one mtopley posted and got same throughput.
- The log line you pointed to is only 60 bytes. Unfortunately, I can't help you since there has to be more data somewhere we aren't seeing. Where does the log file come from? Is your code the server in this case?
- I found the FFD8 marker in this line, for example: 06/11/2009 12:18:30 172.30.252.35 2020 <APP N=79841 V=4621be95a56d75b2321f918a4c68ad33553f23553f235547235550207f23ffd8fffe A=13290e0 T=1e543 X=-74.069656 Y=4.698975 AC=241 GV=1 RS=1> But the next log entry is 6 seconds later. Does the above line show everything you received? I think you need to give us some more data to work with. 06/11/2009 12:18:36 172.30.252.35 2020 <APP N=79841 V=38c526c231b0e39951a3eb542df47f3a3abb1bf78413d306b98bcd2f518af8dba86901e4300718a13264bb0ffec09921691a41bf1f756b A=13290e0 T=1e543 X=-74.069656 Y=4.698975 AC=245 GV=1 RS=1>
C++ Memory debugging help needed
Tunah replied to johnnyk's topic in General and Gameplay ProgrammingQuote:Original post by johnnyk Thanks! I think my problem might not be a leak, but actually overwriting memory, going beyond array bounds or something like that.. I think there was an app called Bounds Checker that helped with that, but it doesnt look like it's been updated in years? I've used Memory Validator in the past to track down hard to find memory leaks. You can evaluate it, and a single user license is very cheap for what you get in my opinion. (I realize it sounds like I actually sell these myself)
Collision detection question
Tunah replied to tiranitzar's topic in Math and PhysicsQuote:Original post by tiranitzar thanks for help morons... You should put this in your signature for future reference.
File Read/Write Hooks [C++]
Tunah replied to brwarner's topic in General and Gameplay ProgrammingHave a look at Detours. Also this post.
[solved] Parallax mapping getting slow
Tunah replied to Ekast's topic in Graphics and GPU ProgrammingHow large is that texture? It looks quite high-res. You should try to generate mipmaps for it to gain performance.
[MSVC++2008] "Release" configuration result in loss of funcionality
Tunah replied to transistor09's topic in General and Gameplay ProgrammingQuote:The application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem Have a look at any new entries in your event log: click It will probably tell you which DLL it can't load.
manifest/side-by-side .exe error HELP!
Tunah replied to brasslips2's topic in General and Gameplay ProgrammingMSVCP90D.dll - Error opening file. the system cannot find the file specified(2) MSVCR90D.dll - Error opening file. the system cannot find the file specified(2) Bolded parts indicate that you've built a debug version. Those libraries aren't redistributable, so try building your executable in release mode and it should start working. Edit: GPSVC.dll seems to be Vista specific. Apart from the fact that you have built a debug version of your project, you will probably have to #DEFINE something in order to build towards an older version of Windows (ie. XP). Have a look at this Last edit, I promise: I misread your post. I thought you couldn't get it to run on your XP machine at school. [Edited by - Tunah on April 2, 2009 1:24:48 AM]
- Quote:Original post by leelouch Quote:Original post by Tunah. This is just an example ! Let's say that xml is a global variable and I do not want to destroy it and reload it again on each time I need an attribute or something else. The while statement here is only to simulate several access to the xml document ! Access to xml database must not reallocate a new element on each time you access to it. it must have like a cache on element already allocated and return cached pointer. the while loop must not create an infinite allocation behavior. memory allocation size must remains constant during the loop where here is not the case ! Fair enough, I guess. But you posted example code and valgrind output after it, so it's only logical to assume that you ran it like that.
- Quote:Original post by leelouch #include <ticpp.h> #include <ostream> using namespace std; int main() { ticpp::Document xml; string topName; ticpp::Node * _top; xml.LoadFile("test.xml"); _top = xml.FirstChild(false); // throwIfNoChildren=false topName = ((ticpp::Element*)_top)->GetAttribute("atom"); cout << topName << endl; while (1) { ticpp::Element * pElem = _top->FirstChildElement(); cout << pElem << endl; }; }.
Question about Regular Expressions (might be Perl-specific)
Tunah replied to CDProp's topic in General and Gameplay ProgrammingThat's a quantifier that: Quote: Repeats the previous item zero or more times. Lazy, so the engine first attempts to skip the previous item, before trying permutations with ever increasing matches of the preceding item. Taken from this page, have a look. Edit: Barius, part of what you posted made my post get mixed with yours until you changed it. That was pretty strange. | https://www.gamedev.net/profile/2415-tunah/ | CC-MAIN-2017-34 | en | refinedweb |
If you use the AWS Elastic Load Balancer (ELB) you’ll need to decide what to use as an endpoint on your application server for the health checker. This is how the ELB will determine if an instance is healthy, or not.
If you use the default “/” path, this may mean that a session in your application is kicked off every time the health checker connects, which could translate to unnecessary added load on your server (though perhaps it may be negligible).
Furthermore, if you create a static .html file and map it, and point the health checker to that, it could turn out that though your application server is hung, the simple static .html is still getting served. This would not make for an accurate health check, and happened to me in my experience.
The best way to ensure that your application server is online and not hung, without adding extra load to your server, will be to create a simple program that runs on the application server. In the case of a Java application server, you can create a simple servlet, as follows:
package com.whatever.aws.elb;; @SuppressWarnings("serial") public class Ping extends HttpServlet { private String message; public void init() throws ServletException { message = "Pong"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" < h1 > " + message + " < /h1> "); } }
And map the servlet to a path in web.xml:
<servlet> <servlet-name>Ping</servlet-name> <servlet-class>com.perthera.elb.Ping</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Ping</servlet-name> <url-pattern>/Ping</url-pattern> <url-pattern>/ping</url-pattern> </servlet-mapping>
Now, you can configure the ELB health checker to connect to the “/ping” path on your instance. If it times out, or returns an error, that means the application server is not healthy. If it returns a normal HTTP code, then all is good. | http://blog.adeel.io/tag/health-check/ | CC-MAIN-2018-30 | en | refinedweb |
1 /*--2 3 $Id: XSLTransform.java,v 1.8 2004/09/07 06:29:07 import org.jdom.*;58 import org.jdom.input.*;59 import org.jdom.output.*;60 import org.jdom.transform.*;61 import javax.xml.transform.*;62 import javax.xml.transform.stream.*;63 64 public class XSLTransform {65 66 public static void main(String [] args) throws Exception {67 if (args.length != 2) {68 System.err.println("Usage: java XSLTransformer [some.xml] [some.xsl]");69 return;70 }71 72 String docname = args[0];73 String sheetname = args[1];74 SAXBuilder builder = new SAXBuilder();75 Document doc = builder.build(docname);76 77 XSLTransformer transformer = new XSLTransformer(sheetname);78 Document doc2 = transformer.transform(doc);79 80 XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());81 outp.output(doc2, System.out);82 }83 }84
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/XSLTransform.java.htm | CC-MAIN-2018-30 | en | refinedweb |
I wrote this post on this blog. I thought that We didn't have the Azure SDK for Log Analytics. However, I was wrong.
They have. It is great one.
Only problem is the documentation and sample code is not shown until now. So I wrote a sample code for it. Also the code becomes very simple than used to. I realize they use brand new API for the Log Analytics code. Let's enjoy it.
Simpler Azure Management API "Fluent"
The new API's namespace is "Fluent". It seems preview.
We are announcing the first developer preview release of the new, simplified Azure management libraries for .NET. Our goal is to improve the developer experience by providing a higher-level, object-oriented API, optimized for readability and writability.
Using the new API, we can easily write the code to operate Azure. Especially, Token management.
All you need is just three lines. This is the example of the Service Principle constructor.
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud); var client = new OperationalInsightsManagementClient(credentials); client.SubscriptionId = subscriptionId;
Now you can get a client. Then operate it.
var parameters = new SearchParameters(); parameters.Query = "*"; parameters.Top = top; var searchResult = await client.Workspaces.GetSearchResultsAsync(resourceGroup, workspeceName, parameters);
Then you can get the result. You can Unmarshal it if you like.
foreach (var result in searchResult.Value) { Console.WriteLine(result.ToString()); }
Compared with the old one, you will find it is very simple.
Resource
You can find whole source code on my GitHub.
List of the OMS resource
Old Post for Log Analytics (Let's compare with new one)
Announcement of the New API fluent.
OMS Azure SDK for .NET. I recommend to read Test code for understanding the behavior
Azure SDK for .NET Fluent branch. You can see the document and sample code in it. (Unfortunately, we can't find LogAnaytics sample and Service Principle sample)
Enjoy | https://blogs.technet.microsoft.com/livedevopsinjapan/2017/08/30/searching-log-analytics-using-azure-sdk-with-new-simpler-library-fluent/ | CC-MAIN-2018-30 | en | refinedweb |
dev_New()
Create a new device.
#include "device.h" LResult dev_New ( LDeviceName deviceName, LDevice * deviceOut );
dev_New() retrieves the device definition from the device database and allocates memory for the device data structure and initializes it with the device definition. It does not try to open the device. Devices created with dev_New() should be disposed of by calling dev_Dispose().
If successful, dev_New() returns a non-negative value. Otherwise, it returns a negative value indicating the reason it failed. Possible unsuccessful return values are:
if ((result = dev_New(deviceName, &device)) < 0) { LOG("New failure", dev_ErrorMessage(result)); } else { assert(device != NULL); } | http://www.advancedrelay.com/laygodoc/laygodev/new.htm | CC-MAIN-2018-30 | en | refinedweb |
Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or any other identifier.
Here's a list of all keywords in Python Programming.
If we give the function an odd number,
None is returned implicitly.
>>> True and False False >>> True or False True >>> not False True:
>>>.
Learn more about Python break and continue statement.:
class ExampleClass: def function1(parameters): … def function2(parameters): …
Learn more about Python Objects and Class.
def is used to define a user-defined function.
Function is a block of related statements, which together does some specific task. It helps us organize code into manageable chunks and also to do some repetitive task.
The usage of
def is shown below:
def function_name(parameters): …
Learn more about Python functions..
Learn more about Python if and if...else Statement.:
def reciprocal(num): try: r = 1/num except: print('Exception caught') return return r print(reciprocal(10)) print(reciprocal(0))
Output
0.1 Exception caught None:
if num == 0: raise ZeroDivisionError('cannot divide').
Learn more about exception handling in Python programming.:
names = ['John','Monica','Steven','Robin'] for i in names: print('Hello '+i)
Output
Hello John Hello Monica Hello Steven Hello Robin
Learn more about Python for loop.().
Learn more on Python modules and import statement.
global is used to declare that a variable inside the function is global (outside the function).
If we need to read the value of a global variable, it is not necessary to define it as
global. This is understood. is created which is not visible outside this function. Although we modify this local variable to 15, the global variable remains unchanged. This is clearly visible in our output..
Learn more about Python lamda function..
def outer_function(): a = 5 def inner_function(): nonlocal a a = 10 print("Inner function: ",a) inner_function() print("Outer function: ",a) outer_function()
Output
Inner function: 10 Outer function: 10 keyword is as follows:
def outer_function(): a = 5 def inner_function(): a = 10 print("Inner function: ",a) inner_function() print("Outer function: ",a) outer_function()
Output
Inner function: 10 Outer function: 5
Here, we do not declare that the variable a inside the nested function is
nonlocal. Hence, a new local variable with the same name is created, but the non-local a is not modified as seen in our output..
Learn more about Python while loop..
with open('example.txt', 'w') as my_file: my_file.write('Hello world!'),
>>>. | https://www.programiz.com/python-programming/keyword-list | CC-MAIN-2018-30 | en | refinedweb |
Technical Information
- Miranda Francis
- 1 years ago
- Views:
Transcription
1 Technical Information TI 50A01A10-01EN FAST/TOOLS System Hardening Windows XP SP3/ Windows 2003 SP1 TI 50A01A10-01EN Copyright May (YK) 1st Edition May (YK)
2 Blank Page
3 i Introduction About This Document This manual describes System Hardening Windows XP SP3/ Windows 2003 SP1. All Rights Reserved. Copyright 2009, Yokogawa Electric Corporation
4 Blank Page
5 iii FAST/TOOLS System Hardening Windows XP SP3/ Windows 2003 SP1 CONTENTS TI 50A01A10-01EN Introduction...i CONTENTS...iii 1. Introduction Purpose Validity Definitions, Abbreviations and Acronyms References General Windows Firewall Service packs and security updates User account considerations Antivirus Installed services...13 Revision Information...i
6 Blank Page
7 <1. Introduction> 1 1. Introduction 1.1 Purpose 1.2 Validity In order to protect systems from network related security vulnerabilities, it is important to harden the operating system on which the application is running. This document describes the hardening procedure to be followed for FAST/TOOLS systems running Microsoft operating systems. This document is primarily intended for internal Yokogawa use when engineering projects that use FAST/TOOLS on Microsoft operating systems. 1.3 Definitions, Abbreviations and Acronyms YEF-SCE : Yokogawa System Center Europe B.V. AV : Antivirus software. 1.4 References 1. McAfee VirusScan Enterprise version 8.7i, YHQ recommended antivirus software. 2. OPC Configuration White Paper, YEF-SCE procedure for setting up OPC communications on Windows 2003 and Windows XP machines.
8 Blank Page
9 <2. General> 3 2. General This document describes the steps that should be taken for hardening the Windows systems used in your project. The hardening process consists of the following steps: 1. Windows Firewall 2. applications 3. Service packs 4. Account considerations 5. Antivirus 6. Remote network access 7. Installed services TIP This document is specifically related to operating system and network configuration for a Windows machine. However it may be useful to read the Security White Paper first to get a broader idea of the security aspects associated with SCADA systems in general.
10 Blank Page
11 <3. Windows Firewall> 5 3. Windows Firewall The Microsoft firewall must be activated on each system. All ports and application exceptions must be blocked expect for those described in this section or any specifically required by project applications. Exceptions are required when using: OPC ODBC A redundant server configuration and the high-availability (HAC) software Remote desktop services TCP/IP based equipment managers The table below describes which ports should be configured as exceptions where necessary. Table Set-TABLE-TITLE Port number Protocol Description When and where used 3389 TCP Remote desktop connection Only if VNC is required for this machine UDP FAST/TOOLS DURM connection On each machine with a DURM connection. Make exceptions for the port number used for each DURM line. For example if you are using a dual redundant network connection, you must do this twice, once for each line TCP FAST/TOOLS DURR line 101 Only on the server machines of a redundant TCP FAST/TOOLS DURR line 102 server configuration, in case HAC is used. Only make exceptions for the number of lines you are TCP FAST/TOOLS DURR line 103 using. For example a dual network connection TCP FAST/TOOLS DURR line 104 will only require lines 101 and UDP HAC GUI commands On the servers and all HMI machines, only when using a redundant server configuration and the HAC software UDP HAC logger On the servers and all HMI machines, only when using a redundant server configuration and the HAC software UDP HAC watchdog On the servers machines, only when using a redundant server configuration and the HAC software. 135 TCP DCOM Only when the machine is used as OPC server or client TCP SimbaServer Only on the server machine and only when using the ODBC interface of ACCESS/FAST Allow incoming echo request is enabled. This allows network pings which are useful for troubleshooting network configurations. When using TCP/IP based equipment managers, then eqp should be configured as an application exception in the firewall. When using OPC connections the following applications should be defined as application exceptions in the firewall. These settings are not required if you are using the OPC DCOM tunneler because the tunneler uses the DURM connection for this purpose. - OPC server (OPC server machine only) - OPC client (OPC client machine only) - Microsoft Management Console (located in C:\Windows\Systems32\mmc.exe) (both client and
12 <3. Windows Firewall> 6 - server machines) - OPCEnum (OPC server machine only) - Print and file sharing (tick box) If using OPC or File and Printer Sharing is enabled, the scope of the following ports 139 & 145 TCP and 137 & 138 UDP should be changed to Any. TIP - When using OPC, please refer to the OPC Configuration White Paper (ref[2]). - If you are using a virus scanner then you may want to open the port for automatic updates. It is advisable to use a managed machine with an internet connection to download new pattern files and deploy them on the machines rather than having a direct connection to the internet. applications The following applications should be disabled or uninstalled on all the systems: - Netmeeting (uninstalled) - Windows Messenger (uninstalled) - Windows Movie Maker (disabled) - Windows Update (disabled) - Windows Media Player (uninstalled) - All games (uninstalled) - Outlook express (uninstalled) - MSN Explorer (uninstalled)
13 <4. Service packs and security updates> 7 4. Service packs and security updates Microsoft regularly releases operating system updates and security patches. As a result, it is not practical to include a list of all updates that need to be installed on the project machine. The practice for installing Windows updates is as follows: - Connect the machine to the internet - Visit using Internet Explorer - Download the Windows Genuine Advantage program if requested to confirm the authenticity of your Windows installation - Install all latest fixes via the online update wizard In addition to the latest operating system updates, Yokogawa maintains a list of security updates that have been tested and evaluated (e.g. for Centum). After updating your system through Windows updates, obtain this list from YHQ or your nearest Yokogawa center of excellence. - Open Add/Remove programs from the Control Panel - Check the option Show updates - The updates are shown in numerical order. Scroll down the list in the Add/Remove programs dialog and find the last Windows update that is also included in the Yokogawa list. - If there are more updates in the Yokogawa list that come after this one then install only the latest updates that come afterwards. Do not install older updates that come before since these changes may have been overruled by Windows hot fixes. TIP FAST/TOOLS should be installed and tested on a define patch level for the project. If for example the customer feels the need for additional updates at a later date or critical fixes are released, then Yokogawa must first determine the relevance of such a fix and test FAST/TOOLS on the patched system to check that functionality is not adversely affected.
14 Blank Page
15 <5. User account considerations> 9 5. User account considerations The following table shows the recommended user definitions. Table Set-TABLE-TITLE Name Password Description Administrator Xxx System Administrator password. This user has no limitations for system administration. This user is defined for the system custodian. FT Xxx The FT user has administrator rights and is only used to startup the FAST/TOOLS service. FTUSER Xxx The FTUSER has normal USER privileges. The FAST/TOOLS configuration tools and operator mimics run under this account. TIP - If the HMI station is configured to automatically logon with the FTUSER account, then the USER/FAST software must be started as the OS Shell. This will automatically disable the Windows Explorer functions like the task bar, desktop and the Windows function keys. Other functions like, Lock computer, System Shutdown, Change password and Task manager are also disabled for the FTUSER account. - If you use remote access software such as VNC then make sure that access can only be acquired via the Administrator user account and that it is used for maintenance purposes only.
16 Blank Page
17 <6. Antivirus> Antivirus Antivirus software should be installed on all systems. The recommended antivirus software used by YHQ is described in ref[1], though the customer may have standardized on other software. The antivirus should be configured so that realtime scanning is enabled. If the virus scanner permits exceptions, then the following FAST/TOOLS directories should be configured as exceptions to the anti virus software: C:\Program Files\Yokogawa\FAST TOOLS\TLS\DAT C:\Program Files\Yokogawa\FAST TOOLS\TLS\SAV C:\Program Files\Yokogawa\FAST TOOLS\TLS\HIS TIP Virus pattern updates should be downloaded via a separate machine. They should be applied either manually or through automatic updates from a controlled system, preferably from within a demilitarized zone in the network (DMZ), in order to prevent direct internet access.
18 Blank Page
19 <7. Installed services> Installed services The following table lists the services that should be activated on disabled for both services and HMI stations. NB: If you wish to configure DCOM for OPC, then you must set the Distributed Transaction Coordinator service as. Otherwise it is not possible to run the DCOM configuration tool. Table Set-TABLE-TITLE Service Description Windows XP Windows 2003.NET Runtime Microsoft.NET Framework NGEN N/A Optimization Service v _x86 Alerter Notifies selected users and computers of administrative alerts. APC PBE Agent APC PowerChute Business Edition Agent Only installed on a machine if directly connected to a ups with an USB cable Log On: administrator APC PBE Server APC PowerChute Business Edition Server Only installed on a machine if directly connected to a ups with an USB cable Log On: administrator Application Experience Lookup Service Processes application compatibility lookup requests for applications as they are launched. N/A Application Layer Gateway service Application Management ASP.NET State Service Provides support for 3rd party protocol plug-ins for Internet Connection Sharing and the Windows Firewall. Provides software installation services such as Assign, Publish, and Remove. Provides support for out-of-process session states for ASP.NET. ATI Hotkey Poller N/A Updates Enables the download and installation of critical Windows updates. Background Transfers data between clients and servers in the intelligent transfer service background. ClipBook Enables ClipBook Viewer to store information and share it with remote computers. COM+ Event System COM+ system application Computer Browser Cryptographic Services DCOM Server process launcher Supports System Event Notification service (SENS), which provides automatic distribution of events to subscribing Component Object Model (COM) components. Manages the configuration and tracking of Component Object Model (COM)+-based components. Maintains an updated list of computers on the network and supplies this list to computers designated as browsers. Provides three management services: Catalogue Database Service, which confirms the signatures of Windows files; Protected Root Service, which adds and removes Trusted Root Certification Authority certificates from this computer; and Key Service, which helps enroll this computer for certificates. Provides launch functionality for DCOM services. N/A
20 <7. Installed services> 14 Table Set-TABLE-TITLE DHCP Client Service Description Windows XP Windows 2003 Distributed File System Distributed Link Tracking Server Distributed Link Tracking Client Distributed Transaction Coordinator DNS Client DVWebViews Service Error Reporting Service Event Log Fast User Switching Compatibility File Replication Help and Support HTTP SSL Human Interface Device Access IMAPI CD-Burning COM Service Indexing Service Manages network configuration by registering and updating IP addresses and DNS names. Integrates disparate file shares into a single, logical N/A namespace and manages these logical volumes distributed across a local or wide area network Enables client programs to track linked files that are N/A moved within an NTFS volume, to another NTFS volume on the same computer, or to an NTFS volume on another computer. Maintains links between NTFS files within a computer or across computers in a network domain. Coordinates transactions that span multiple resource managers, such as databases, message queues, and file systems. Resolves and caches Domain Name System (DNS) names for this computer. If this service is stopped, this computer will not be able to resolve DNS names and locate Active Directory domain controllers. Allows error reporting for services and applications running in non-standard environments. Enables event log messages issued by Windowsbased programs and components to be viewed in Event Viewer. Provides management for applications that require assistance in a multiple user environment. Allows files to be automatically copied and maintained simultaneously on multiple servers. Enables Help and Support Center to run on this computer. This service implements the secure hypertext transfer protocol (HTTPS) for the HTTP service, using the Secure Socket Layer (SSL). Enables generic input access to Human Interface Devices (HID), which activates and maintains the use of predefined hot buttons on keyboards, remote controls, and other multimedia devices. Manages CD recording using Image Mastering Applications Programming Interface (IMAPI). Indexes contents and properties of files on local and remote computers; provides rapid access to files through flexible querying language. N/A N/A Intel NCS Netservice Supports Intel(R) PROSet for Wired Connections. N/A Intersite messaging Enables messages to be exchanged between N/A computers running Windows Server sites. IPSEC Services Manages IP security policy and starts the ISAKMP/Oakley (IKE) and the IP security driver. Kerberos Key On domain controllers this service enables users to N/A Distribution Center log on to the network using the Kerberos authentication protocol License Logging Monitors and records client access licensing for portions of the operating system (such as IIS, Terminal Server and File/Print) as well as products that aren't a part of the OS, like SQL and Exchange Server. N/A
21 <7. Installed services> 15 Table Set-TABLE-TITLE Service Description Windows XP Windows 2003 Logical Disk Manager Detects and monitors new hard disk drives and sends disk volume information to Logical Disk Manager Administrative Service for configuration. Logical Disk Manager Configures hard disk drives and volumes. The service Administrative only runs for configuration processes and then stops. Service Messenger Transmits net send and Alerter service messages between clients and servers. This service is not related to Windows Messenger. MS Software Shadow Copy Provider Net Logon NetMeeting Remote Desktop Sharing Manages software-based volume shadow copies taken by the Volume Shadow Copy service. Supports pass-through authentication of account logon events for computers in a domain. Enables an authorized user to access this computer remotely by using NetMeeting over a corporate intranet. Network Connections Manages objects in the Network and Dial-Up Connections folder, in which you can view both local area network and remote connections. Network DDE Provides network transport and security for Dynamic Data Exchange (DDE) for programs running on the same computer or on different computers. Network DDE DSDM Manages Dynamic Data Exchange (DDE) network shares. Network Location Awareness (NLA) Network Provisioning Service NT LM Security Support Provider Collects and stores network configuration and location information, and notifies applications when this information changes. Manages XML configuration files on a domain basis for automatic network provisioning. Provides security to remote procedure call (RPC) programs that use transports other than named pipes. OpcEnum Performance Logs Collects performance data from local or remote and Alerts computers based on preconfigured schedule parameters, then writes the data to a log or triggers an alert. Plug and Play Enables a computer to recognize and adapt to hardware changes with little or no user input. Portable Media Serial Number Retrieves the serial number of any portable music player connected to your computer. Print Spooler Loads files to memory for later printing. Protected Storage Provides protected storage for sensitive data, such as private keys, to prevent access by unauthorized services, processes, or users. QoS RSVP Provides network signaling and local traffic control N/A setup functionality for QoS-aware programs and control applets. Remote Access Auto Creates a connection to a remote network whenever Connection Manager a program references a remote DNS or NetBIOS name or address. Remote Access Connection Manager Creates a network connection.
22 <7. Installed services> 16 Table Set-TABLE-TITLE Service Description Windows XP Windows 2003 Remote Desktop Help Session Manager Manages and controls Remote Assistance. If this service is stopped, Remote Assistance will be unavailable. Before stopping this service, see the Dependencies tab of the Properties dialog box. Remote Procedure Call (RPC) Remote Procedure Call (RPC) Locator Remote Registry Provides the endpoint mapper and other miscellaneous RPC services. Manages the RPC name service database. Enables remote users to modify registry settings on this computer. If this service is stopped, the registry can be modified only by users on this computer. Removable Storage Used for managing removable media. Resultant Setup Policy Provider Routing and Remote Access Secondary Logon Security Accounts Manager Enables a user to connect to a remote computer, access the Windows Management Instrumentation database for that computer, and either verify the current Group Policy settings made for the computer or check settings before they are applied. N/A Offers routing services to businesses in local area and wide area network environments. Enables starting processes under alternate credentials. Stores security information for local user accounts. Security Center Monitors system security settings and configurations. N/A Server Supports file, print, and named-pipe sharing over the network for this computer. Shell Hardware Provides notifications for AutoPlay hardware events. Detection Smart Card Manages access to smart cards read by this computer. Special Administrator Allows administrators to remotely access a command N/A Console Helper prompt using Emergency Management Services. SSDP Discovery Service Enables discovery of UPnP devices on your home network. Start Fasttools LOG On: FT System Event Notification Tracks system events such as Windows logon, network, and power events. Notifies COM+ Event System subscribers of these events. System Restore Service Task Scheduler TCP/IP NetBIOS Helper Telephony Telnet Performs system restore functions. To stop service, turn off System Restore from the System Restore tab in My Computer, Properties, System Restore tab. Enables a user to configure and schedule automated tasks on this computer. Enables support for NetBIOS over TCP/IP (NetBT) service and NetBIOS name resolution. Provides Telephony API (TAPI) support for programs that control telephony devices and IP based voice connections on the local computer and, through the LAN, on servers that are also running the service. Enables a remote user to log on to this computer and run programs, and supports various TCP/IP Telnet clients, including UNIX-based and Windows-based computers. N/A N/A N/A
23 <7. Installed services> 17 Table Set-TABLE-TITLE Service Description Windows XP Windows 2003 Terminal Services Allows multiple users to be connected interactively to a machine as well as the display of desktops and applications to remote computers. The underpinning of Remote Desktop (including RD for Administrators), Fast User Switching, Remote Assistance, and Terminal Server. Terminal Services Enables a user connection request to be routed to the N/A Session Directory appropriate terminal server in a cluster. Themes Provides user experience theme management. Uninterruptible Power Supply Universal Plug and Play Device Host Upload Manager Manages an uninterruptible power supply (UPS) connected to the computer. Provides support to host Universal Plug and Play devices. Manages synchronous and asynchronous file transfers between clients and servers on the network. Virtual Disk Services Provides software volume and hardware volume management service. Volume Shadow Copy WebClient WinHTTP Web Proxy Auto-Discovery Service Windows Audio Windows Firewall/internet connection sharing(ics) Windows Image Acquisition (WIA) Windows Installer Windows Management Instrumentation Windows Management Instrumentation Driver Extensions Windows Time Windows User mode driver framework Wireless Zero Configuration Wireless Configuration WMI Performance Adapter Workstation Manages and implements Volume Shadow Copies used for backup and other purposes. Enables Windows-based programs to create, access, and modify Internet-based files. Implements the Web Proxy Auto-Discovery (WPAD) protocol for Windows HTTP Services (WinHTTP). WPAD is a protocol to enable an HTTP client to automatically discover a proxy configuration. Manages audio devices for Windows-based programs. Provides network address translation, addressing, name resolution and/or intrusion prevention services for a home or small office network. Provides image acquisition services for scanners and cameras. Installs repairs and removes software according to instructions contained in.msi files. Provides a common interface and object model to access management information about operating system, devices, applications and services. Provides systems management information to and from drivers. N/A N/A N/A N/A Maintains date and time synchronization on all clients and servers in the network. If this service is stopped, date and time synchronization will be unavailable. Enables Windows user mode drivers. Provides automatic configuration for the adapters. Enables automatic configuration for IEEE adapters. Provides performance library information from WMI HiPerf providers. Creates and maintains client network connections to remote servers. If this service is stopped, these connections will be unavailable. If this service is disabled, any services that explicitly depend on it will fail to start. Very important service. N/A N/A
24 Blank Page
25 i Revision Information Title No. : FAST/TOOLS System Hardening Windows XP SP3/Windows 2003 SP1 : TI 50A01A10-01EN May. 2009/1st Edition Newly published Written by Open System Department Industrial Automation Systems Business Center Yokogawa Electric Corporation Published by Yokogawa Electric Corporation Nakacho, Musashino-shi, Tokyo , Japan Subject to change without notice.
Windows Server 2003 default services
Windows Server 2003 default services To view a description for a particular service, hover the mouse pointer over the service in the Name column. The descriptions included here are based on Microsoft documentation.
CHARON-VAX application note
CHARON-VAX application note AN-33 Required Windows Standard Services Author: Software Resources International Date: 16-Jan-2006 Software Resources International (SRI) recommends the use of the host operating
Services Summary... 1
Services Report By Service Name Period: Last 20 week(s) Generated: For: Internal Auditor InternalAuditor@ecora.com By: Ecora Auditor Professional 4.5 - Windows Module 4.5.8063.19200 Using: FFR Definition
SECURITY BEST PRACTICES FOR CISCO PERSONAL ASSISTANT (1.4X)
WHITE PAPER SECURITY BEST PRACTICES FOR CISCO PERSONAL ASSISTANT (1.4X) INTRODUCTION This document covers the recommended best practices for hardening a Cisco Personal Assistant 1.4(x) server. The term
Windows 2003 Server Baseline page 1 of 5. Windows 2003 Server Baseline v1.1
Windows 2003 Server Baseline page 1 of 5 Windows 2003 Server Baseline v1.1 Before the installation, make sure you have the server disconnected from the network or behind a firewall on an IP address that
Services on Server 11/5/2015 00:00:00-12/4/2015 23:59:59
Services on Server 11/5/2015 00:00:00-12/4/2015 23:59:59 Computers: SQL2014 Computer: SQL2014 Microsoft Monitoring Agent Audit Forwarding Stopped Disabled NT AUTHORITY\NetworkService Sends events to
Windows 2000 Professional Service Configurations
Windows 2000 Professional Service Configurations Original content created January 23, 2000 Last update was Saturday, July 19, 2003 Copyright 2000-2003 by Black Viper All Rights Reserved. All trademarks
SAP Hardening and Patch Management Guide for Windows Server
SAP Hardening and Patch Management Guide for Windows Server Microsoft Corporation November 15, 2005 Summary This whitepaper introduces security measures for SAP systems running on Windows Server. Two security
WhatsUp Gold v16.3 Installation and Configuration Guide
WhatsUp Gold v16.3 Installation and Configuration Guide Contents Installing and Configuring WhatsUp Gold using WhatsUp Setup Installation Overview... 1 Overview... 1 Security considerations... 2 Standard
Course Description. Course Audience. Course Outline. Course Page - Page 1 of 12
Course Page - Page 1 of 12 Windows 7 Enterprise Desktop Support Technician M-50331 Length: 5 days Price: $2,795.00 Course Description This five-day instructor-led course provides students with the knowledge
Disable Redundant Windows XP Services which are Hogging Your RAM
X P Services Optimisation X 36/1 Disable Redundant Windows XP Services which are Hogging Your RAM With the information in this article you can: Configure your Windows XP Services for top performance Identify
MCSE 2003. Core exams (Networking) One Client OS Exam. Core Exams (6 Exams Required)
MCSE 2003 Microsoft Certified Systems Engineer (MCSE) candidates on the Microsoft Windows Server 2003 track are required to satisfy the following requirements: Core Exams (6 Exams Required) Four networking
A+ Guide to Managing and Maintaining Your PC. Installing and Using Windows XP Professional
A+ Guide to Managing and Maintaining Your PC Fifth Edition Chapter 15 Installing and Using Windows XP Professional You Will Learn About the features and architecture of Windows XP How to install Windows
Core Protection for Virtual Machines 1
Core Protection for Virtual Machines 1 Comprehensive Threat Protection for Virtual Environments. Installation Guide e Endpoint Security Trend Micro Incorporated reserves the right to make changes to this
Networking Best Practices Guide. Version 6.5
Networking Best Practices Guide Version 6.5 Summer 2010 Copyright: 2010, CCH, a Wolters Kluwer business. All rights reserved. Material in this publication may not be reproduced or transmitted in any form
Table of Contents. CHAPTER 1 About This Guide... 9. CHAPTER 2 Introduction... 11. CHAPTER 3 Database Backup and Restoration... 15
Table of Contents CHAPTER 1 About This Guide......................... 9 The Installation Guides....................................... 10 CHAPTER 2 Introduction............................ 11 Required
VERITAS Backup Exec 9.1 for Windows Servers Quick Installation Guide
VERITAS Backup Exec 9.1 for Windows Servers Quick Installation Guide N109548 Disclaimer The information contained in this publication is subject to change without notice. VERITAS Software Corporation makes
MCSE Objectives. Exam 70-236: TS:Exchange Server 2007, Configuring
MCSE Objectives Exam 70-236: TS:Exchange Server 2007, Configuring Installing and Configuring Microsoft Exchange Servers Prepare the infrastructure for Exchange installation. Prepare the servers for Exchange Operating Systems. Basic Security
Windows Operating Systems Basic Security Objectives Explain Windows Operating System (OS) common configurations Recognize OS related threats Apply major steps in securing the OS Windows Operating System
StruxureWare Power Monitoring 7.0.1
StruxureWare Power Monitoring 7.0.1 Installation Guide 7EN02-0308-01 07/2012 Contents Safety information 5 Introduction 7 Summary of topics in this guide 7 Supported operating systems and SQL Server editions
ManageEngine Desktop Central Training
ManageEngine Desktop Central Training Course Objectives Who Should Attend Course Agenda Course Objectives Desktop Central training helps you IT staff learn the features offered by Desktop Central and to
KASPERSKY LAB. Kaspersky Administration Kit version 6.0. Administrator s manual
KASPERSKY LAB Kaspersky Administration Kit version 6.0 Administrator s manual KASPERSKY ADMINISTRATION KIT VERSION 6.0 Administrator s manual Kaspersky Lab Visit our website:
Configuring an APOGEE System on an IT Infrastructure White Paper
Configuring an APOGEE System on an IT Infrastructure White Paper 149-1006 Building Technologies 149-1006, Rev. DA Copyright Notice Copyright Notice Notice Document information is subject to change without
Lesson Plans Microsoft s Managing and Maintaining a Microsoft Windows Server 2003 Environment
Lesson Plans Microsoft s Managing and Maintaining a Microsoft Windows Server 2003 Environment (Exam 70-290) Table of Contents Table of Contents... 1 Course Overview... 2 Section 0-1: Introduction... 4
Pearl Echo Installation Checklist
Pearl Echo Installation Checklist Use this checklist to enter critical installation and setup information that will be required to install Pearl Echo in your network. For detailed deployment instructions
WhatsUp Gold v16.1 Installation and Configuration Guide
WhatsUp Gold v16.1 Installation and Configuration Guide Contents Installing and Configuring Ipswitch WhatsUp Gold v16.1 using WhatsUp Setup Installing WhatsUp Gold using WhatsUp Setup... 1 Security guidelines
Installing GFI MailSecurity
Installing GFI MailSecurity Introduction This chapter explains how to install and configure GFI MailSecurity. You can install GFI MailSecurity directly on your mail server or you can choose to install
MCSA Objectives. Exam 70-236: TS:Exchange Server 2007, Configuring
MCSA Objectives Exam 70-236: TS:Exchange Server 2007, Configuring Installing and Configuring Microsoft Exchange Servers Prepare the infrastructure for Exchange installation. Prepare the servers
Topaz Installation Sheet
Topaz Installation Sheet P/N 460924001E ISS 08FEB12 Content Introduction... 3 Recommended minimum requirements... 3 Setup for Internet Explorer:... 4 Topaz installation... 10 Technical support... 14 Copyright
FREQUENTLY ASKED QUESTIONS
FREQUENTLY ASKED QUESTIONS Secure Bytes, October 2011 This document is confidential and for the use of a Secure Bytes client only. The information contained herein is the property of Secure Bytes and may
Freshservice Discovery Probe User Guide
Freshservice Discovery Probe User Guide 1. What is Freshservice Discovery Probe? 1.1 What details does Probe fetch? 1.2 How does Probe fetch the information? 2. What are the minimum system requirements
Release Notes for Websense Email Security v7.2
Release Notes for Websense Email Security v7.2 Websense Email Security version 7.2 is a feature release that includes support for Windows Server 2008 as well as support for Microsoft SQL Server 2008.
LifeSize Control Installation Guide
LifeSize Control Installation Guide April 2005 Part Number 132-00001-001, Version 1.0 Copyright Notice Copyright 2005 LifeSize Communications. All rights reserved. LifeSize Communications has made every
Step-by-Step Configuration
Step-by-Step Configuration Kerio Technologies C 2001-2003 Kerio Technologies. All Rights Reserved. Printing Date: December 17, 2003 This guide provides detailed description on configuration of the local
Agency Pre Migration Tasks
Agency Pre Migration Tasks This document is to be provided to the agency and will be reviewed during the Migration Technical Kickoff meeting between the ICS Technical Team and the agency. Network: Required
VeriCentre 3.0 Upgrade Pre-Installation and Post Installation Guidelines
VeriCentre 3.0 Upgrade Pre-Installation and Post Installation Guidelines * For actual installation steps, please refer to the VeriCentre 3.0 Installation guide that came with the VeriCentre 3.0 software. 7, Enterprise Desktop Support Technician
Course 50331D: Windows 7, Enterprise Desktop Support Technician Page 1 of 11 Windows 7, Enterprise Desktop Support Technician Course 50331D: 4 days; Instructor-Led Introduction This four-day instructor-ledcourse
Integration Guide. Microsoft Active Directory Rights Management Services (AD RMS) Microsoft Windows Server 2008
Integration Guide Microsoft Active Directory Rights Management Services (AD RMS) Microsoft Windows Server 2008 Integration Guide: Microsoft Active Directory Rights Management Services (AD RMS) Imprint
Table of Contents. FleetSoft Installation Guide
FleetSoft Installation Guide Table of Contents FleetSoft Installation Guide... 1 Minimum System Requirements... 2 Installation Notes... 3 Frequently Asked Questions... 4 Deployment Overview... 6 Automating,
Step-by-Step Guide for Creating and Testing Connection Manager Profiles in a Test Lab
Step-by-Step Guide for Creating and Testing Connection Manager Profiles in a Test Lab Microsoft Corporation Published: May, 2005 Author: Microsoft Corporation Abstract This guide describes how to create
Step-by-Step Configuration
Step-by-Step Configuration Kerio Technologies Kerio Technologies. All Rights Reserved. Printing Date: August 15, 2007 This guide provides detailed description on configuration of the local network which
SA Citrix Virtual Desktop Infrastructure (VDI) Configuration Guide
SA Citrix Virtual Desktop Infrastructure (VDI) Configuration Guide Published July 2015 This document covers steps to configure Citrix VDI on Pulse Secure s SA Series SSL VPN platforms. It also covers brief
Domain Restructuring Designing RODC
Domain Restructuring Designing RODC Introduction: This document will describe design decision to implement Read Only Domain Controller in the existing Active Directory Forest. The infrastructure is assumed
Avalanche Site Edition
Avalanche Site Edition Version 4.8 avse ug 48 20090325 Revised 03/20/2009 ii Copyright 2008 by Wavelink Corporation All rights reserved. Wavelink Corporation 6985 South Union Park Avenue, Suite 335 Midvale,
Citrix Access Gateway Plug-in for Windows User Guide
Citrix Access Gateway Plug-in for Windows User Guide Access Gateway 9.2, Enterprise Edition Copyright and Trademark Notice Use of the product documented in this guide is subject to your prior acceptance GFI MailSecurity
Installing GFI MailSecurity Introduction This chapter explains how to install and configure GFI MailSecurity. You can install GFI MailSecurity directly on your mail server or you can choose to install
ScriptBlocking Service... 27 Secondary Logon Service... 28 Security Accounts Manager Service... 28 Security Center... 29 Server Service...
The table below illustrates how I've set up the information for each service.... 3 Alerter Service... 4 Application Layer Gateway Service... 4 Application Management Service... 4 Automatic Updates Service...
70-685: Enterprise Desktop Support Technician
70-685: Enterprise Desktop Support Technician Course Introduction Course Introduction Chapter 01 - Identifying Cause and Resolving Desktop Application Issues Identifying Cause and Resolving Desktop Application
Network Configuration Settings
Network Configuration Settings Many small businesses already have an existing firewall device for their local network when they purchase Microsoft Windows Small Business Server 2003. Often, these devices
Sophos for Microsoft SharePoint startup guide
Sophos for Microsoft SharePoint startup guide Product version: 2.0 Document date: March 2011 Contents 1 About this guide...3 2 About Sophos for Microsoft SharePoint...3 3 System requirements...3 4 Planning. Symantec Client Security. About Symantec Client Security. How to get started
Getting Started Symantec Client Security About Security Security provides scalable, cross-platform firewall, intrusion prevention, and antivirus protection for workstations and antivirus protection
Enterprise Manager. Version 6.2. Installation Guide
Enterprise Manager Version 6.2 Installation Guide Enterprise Manager 6.2 Installation Guide Document Number 680-028-014 Revision Date Description A August 2012 Initial release to support version 6.2.1
PrintFleet Local Beacon
PrintFleet Local Beacon User Guide Version 2.5.15 as of March 3, 2008. 2008 PrintFleet Inc. All rights reserved. Copyright 2008 PrintFleet Inc. All rights reserved. PrintFleet Local Beacon User Guide.
MCSA Security + Certification Program
MCSA Security + Certification Program 12 credit hours 270 hours to complete certifications Tuition: $4500 Information technology positions are high-demand occupations that support virtually all industries. and Configuring WhatsUp Gold
Installing and Configuring WhatsUp Gold This guide provides information about installing and configuring WhatsUp Gold v14.2, including instructions on how to run the WhatsUp web interface through an Internet
DOCSVAULT Document Management System for everyone
Installation Guide DOCSVAULT Document Management System for everyone 9 v Desktop and Web Client v On Premises Solution v Intelligent Data Capture v Email Automation v Workflow & Record Retention Installing
FortKnox Personal Firewall
FortKnox Personal Firewall User Manual Document version 1.4 EN ( 15. 9. 2009 ) Copyright (c) 2007-2009 NETGATE Technologies s.r.o. All rights reserved. This product uses compression library zlib Copyright
Vector Asset Management User Manual
Vector Asset Management User Manual This manual describes how to set up Vector Asset Management 6.0. It describes how to use the: Vector AM Console Vector AM Client Hardware Inventory Software Inventory
FileMaker Server 15. Getting Started Guide
FileMaker Server 15 Getting Started Guide 2007 2016 FileMaker, Inc. All Rights Reserved. FileMaker, Inc. 5201 Patrick Henry Drive Santa Clara, California 95054 FileMaker and FileMaker Go are trademarks
Installing Policy Patrol on a separate machine
Policy Patrol 3.0 technical documentation July 23, 2004 Installing Policy Patrol on a separate machine If you have Microsoft Exchange Server 2000 or 2003 it is recommended to install Policy Patrol on
Click Studios. Passwordstate. Installation Instructions
Passwordstate Installation Instructions This document and the information controlled therein is the property of Click Studios. It must not be reproduced in whole/part, or otherwise disclosed, without prior
Sage Abra SQL HRMS Abra Workforce Connections. Pre-Installation Guide
Sage Abra SQL HRMS Abra Workforce Connections Pre-Installation Guide 2010 Sage Software, Inc. All rights reserved. Sage, the Sage logos, and the Sage product and service names mentioned herein are registered
Windows 7, Enterprise Desktop Support Technician
Windows 7, Enterprise Desktop Support Technician Course Number: 70-685 Certification Exam This course is preparation for the Microsoft Certified IT Professional (MCITP) Exam, Exam 70-685: Pro: Windows
SMART Vantage. Installation guide
SMART Vantage Installation guide Product registration If you register your SMART product, we ll notify you of new features and software upgrades. Register online at smarttech.com/registration. Keep the
Metalogix SharePoint Backup. Advanced Installation Guide. Publication Date: August 24, 2015
Metalogix SharePoint Backup Publication Date: August 24, 2015 All Rights Reserved. This software is protected by copyright law and international treaties. Unauthorized reproduction or distribution of | http://docplayer.net/23929742-Technical-information.html | CC-MAIN-2018-30 | en | refinedweb |
I am currently writing a programme using Biopython and part of it involves searching Pubmed using an entry specified by the user. This returns all the records that match this entry. I then want to search just these records for a specific author, again specified by the user, however I am having issues with how to do this. If anyone can help, it would be much appreciated.
Here is my code so far, it is largely taken from the Biopython cookbook documentation. For this example, I am searching for the word "brainbow" and the author "Currie" (which I believe should be there).
from Bio import Entrez, SeqIO, Medline Entrez.email = "A.N.Other@example.com" def pbmd_search(): #searches pubmed database, using Biopython documentation handle = Entrez.egquery(term="brainbow") record = Entrez.read(handle) for row in record["eGQueryResult"]: if row["DbName"]=="pubmed": print(str(row["Count"]) + " records returned") handle = Entrez.esearch(db="pubmed", term="brainbow", retmax=1000) record = Entrez.read(handle) idlist = record["IdList"] handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="text") records = Medline.parse(handle) records = list(records) records_str = [] for record in records: records_str += "Title: %s \nAuthors: %s \nSource: %s\n\n" %(record.get("TI"), ", ".join(record.get("AU")), record.get("SO")) search_author = "Currie" print(search_author) if search_author in records_str: print("yes") else: print("no")
Can you specify what the issue is? What's the reason for not searching for "brainbow AND currie"?
What I want to do is to search first for "brainbow," and then to search that list of records for "Currie", i.e. I'm only interested in records that match "brainbow" and that also have an author called "Currie". However, I want it to work so that the user doesn't have to search for both at the same time.
Ps. I'm not an expert programmer so I may be missing something obvious!
So you'd search for
brainbow AND currie[Author]? Programming looks fine, I'm a bit at loss about the logic ;)
Okay, so this is part of a GUI programme that uses GTK3. I have a window with 2 buttons and 2 entry widgets, so one button is linked to the code searching pubmed e.g. for "brainbow" and then the other button is linked to searching for an author e.g. "Currie". My idea was that users can search for records without necessarily also searching for an author.
Then you could still have the input from both entry widgets use to concatenate a search term? But okay, you seem quite convinced about your approach. Is the problem that the search_author isn't found? Or what goes wrong in your code?
Yes, so the bit that goes wrong is the
The search_author isn't found.
And have you confirmed that
records_strcontains
Currie? Because when I use your code, records_str doesn't look like something useful ;)
You probably need records_str.append() instead of += But then still your
if search_author in records_str:won't work because records_str is a list. You'll need to iterate over the list and for every element ask if search_author is in that element
Note that you can simplify a lot too, but let's first try to get it working correctly before further changing stuff.
Thanks for your help, I have now solved my problem. | https://www.biostars.org/p/225044/ | CC-MAIN-2018-30 | en | refinedweb |
Hi Everyone. Consider this part two after solving part one of my output window issie
basically 7zip i needed to output its text to a output window i had created inside my main menu where the button "backup" exists.
The window within the window code looks like this.
outputLabel = Label(root,text="7Zip Output Window") outputLabel.place(x=500,y=425) outputWindow = Text(root) outputWindow.config(relief=SUNKEN, bg='beige',width=51,height=17) outputWindow.place(x=350,y=130)
and when you click the backup button this piece of code executes
def picbackup(): source = ['-ir!"%USERPROFILE%\*.bmp"', '-ir!"%USERPROFILE%\*.tif"', ': # can a progress bar be implemented or EBC anim ????? print('Successful backup to', target) else: print('Backup FAILED')
ok ... this is great cause it works ... but i have niggly issues i would like to solve.
1. The output only appears AFTER 7zip has completed. (i would like to see it happen in real time
2. No scroll bars (i have extensive researched this and found when i try to put the working source code in .. it puts scroll bars on the ENTIRE MAIN MENE (root?) window .. NOT the small output window.
3. the output that is show is showing the TOP of the output and not the bottom .... ii do have code for this embedded in my scroll bar code BUT like above ... the scroll bars are attaching to the wrong window.
If anyone can help me .. the code i have been using to help me is here. this works great cause it has scrolls, shows the bottom of the text instantly ... i'm not sure how it works in a live continous output situation but i guess we'll see.
# searching a long text for a string and scrolling to it # use ctrl+c to copy, ctrl+x to cut selected text, # ctrl+v to paste, and ctrl+/ to select all import tkinter as tk def display(data): """creates a text display area with a vertical scrollbar""" scrollbar = tk.Scrollbar(root) text1 = tk.Text(root, yscrollcommand=scrollbar.set) text1.insert(0.0, data) scrollbar.config(command=text1.yview) scrollbar.pack(side='right', fill='y') text1.pack(side='left', expand=0, fill='both') # could bring the search string in from a listbox selectionscroll</strong> text until index line is visible # might move to the top line of text field text1.see(index) root = tk.Tk() str1 = """\ Chapter 1 . . . . . . . Chapter 2 . . . . . . . . Chapter 3 . . . . . . . . The End """ display(str1) root.mainloop()
Thankyou for your time ... and so far .. thansk to everyone as i have gained heaps using these forums to seek out answers, snippet code .. all great stuff. | https://www.daniweb.com/programming/software-development/threads/206803/output-window-not-behaving | CC-MAIN-2018-30 | en | refinedweb |
I’m trying to write a regular expression that validates a date. The regex needs to match the following
- M/D/YYYY
- MM/DD/YYYY
- Single digit months can start with a leading zero (eg: 03/12/2008)
- Single digit days can start with a leading zero (eg: 3/02/2008)
- CANNOT include February 30 or February 31 (eg: 2/31/2008)
So far I have
^(([1-9]|1[012])[-/.]([1-9]|[12][0-9]|3[01])[-/.](19|20)/d/d)|((1[012]|0[1-9])(3[01]|2/d|1/d|0[1-9])(19|20)/d/d)|((1[012]|0[1-9])[-/.](3[01]|2/d|1/d|0[1-9])[-/.](19|20)/d/d)$
This matches properly EXCEPT it still includes 2/30/2008 & 2/31/2008.
Does anyone have a better suggestion?
Edit: I found the answer on RegExLib
^((((0[13578])|([13578])|(1[02]))[//](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[//](([1-9])|([0-2][0-9])|(30)))|((2|02)[//](([1-9])|([0-2][0-9]))))[//]/d{4}$|^/d{4}$
It matches all valid months that follow the MM/DD/YYYY format.
Thanks everyone for the help.
Regular expression to match valid namespace name
I thought this question was asked before but I tried Google but didn’t find an answer. Maybe I used wrong keywords. Is it possible to use regular expression to match valid C# namespace name? Thanks Up
Regular Expression to match dates in dd/mm/yy format and check for valid values
Does anyone have a regurlar expression available which only accepts dates in the format dd/mm/yy but also has strict checking to make sure that the date is valid, including leap year support? I am cod
What regular expression will match valid international phone numbers?
I need to determine whether a phone number is valid before attempting to dial it. The phone call can go anywhere in the world. What regular expression will match valid international phone numbers?
Regular expression to match google calendar event feed dates
I have been trying to match various dates from a google calendar xml feed in JavaScript but I am failing miserably. Currently I have this regular expression: /s(.*)/s Here are some of the examples o
How do I match valid words with a ruby regular expression
Using a ruby regular expression, how do I match all words in a coma separated list, but only match if the entire word contains valid word characters (i.e.: letter number or underscore). For instance,
Regular expression to match a valid absolute Windows directory containing spaces
I would like a regular expression to match a valid absolute Windows directory path, where directory names can contain spaces. Example matches: C:/pictures/holiday (without trailing backslash) C:/pictu
Valid regular expression
In order to check to see if a string is a valid regular expression I use the following piece of code: import re try: re.compile(‘(0*|2*)’) is_valid = True print(is_valid) except re.error: is_valid = F
regular expression matching dates
Need to match date in a user submitted string it should work with these different formats jan 1 2000 january 1 2000 jan. 1 2000 1/1/2000 2000 january how would you write this regular expression?
Regular Expression for date format validation [duplicate]
This question already has an answer here: Regular Expression to match valid dates 14 answers Regex to match Date 4 answers javascript – regular expression to validate date in mm/dd/yyyy form
Regular Expression Cant Match
I have the following string: 8 0 0 . Item s Payable in Connection w ith Loan I am trying to match it using the following regular expression: ^8//s*0//s*0//. What I believe this regular expression is s
Answers
Sounds like you’re overextending regex for this purpose. What I would do is use a regex to match a few date formats and then use a separate function to validate the values of the date fields so extracted.
Regex was not meant to validate number ranges(this number must be from 1 to 5 when the number preceding it happens to be a 2 and the number preceding that happens to be below 6). Just look for the pattern of placement of numbers in regex. If you need to validate is qualities of a date, put it in a date object js/c#/vb, and interogate the numbers there.
This is not an appropriate use of regular expressions. You’d be better off using
[0-9]{2}/[0-9]{2}/[0-9]{4}
and then checking ranges in a higher-level language.
I know this does not answer your question, but why don’t you use a date handling routine to check if it’s a valid date? Even if you modify the regexp with a negative lookahead assertion like (?!31/0?2) (ie, do not match 31/2 or 31/02) you’ll still have the problem of accepting 29 02 on non leap years and about a single separator date format.
The problem is not easy if you want to really validate a date, check this forum thread.
For an example or a better way, in C#, check this link
If you are using another platform/language, let us know
If you’re going to insist on doing this with a regular expression, I’d recommend something like:
( (0?1|0?3| <...> |10|11|12) / (0?1| <...> |30|31) | 0?2 / (0?1| <...> |28|29) ) / (19|20)[0-9]{2}
This might make it possible to read and understand.
Perl expanded version
Note use of /x modifier.
/^( ( ( # 31 day months (0[13578]) | ([13578]) | (1[02]) ) [//] ( ([1-9]) | ([0-2][0-9]) | (3[01]) ) ) | ( ( # 30 day months (0[469]) | ([469]) | (11) ) [//] ( ([1-9]) | ([0-2][0-9]) | (30) ) ) | ( # 29 day month (Feb) (2|02) [//] ( ([1-9]) | ([0-2][0-9]) ) ) ) [//] # year /d{4}$ | ^/d{4}$ # year only /x
Original
^((((0[13578])|([13578])|(1[02]))[//](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[//](([1-9])|([0-2][0-9])|(30)))|((2|02)[//](([1-9])|([0-2][0-9]))))[//]/d{4}$|^/d{4}$
Maintainable Perl 5.10 version
/ (?: (?<month> (?&mon_29)) [//] (?<day>(?&day_29)) | (?<month> (?&mon_30)) [//] (?<day>(?&day_30)) | (?<month> (?&mon_31)) [//] (?<day>(?&day_31)) ) [//] (?<year> /d{4}) (?(DEFINE) (?<day_29> [0-2]?/d ) (?<day_30> [0-2]?/d | 30 ) (?<day_31> [0-2]?/d | 3[01] ) (?<mon_29> 0?2 ) (?<mon_30> 0?[469] | (11) ) (?<mon_31> 0?[13578] | 1[02] ) ) /x
You can retrieve the elements by name in this version.
say "Month=$+{month} Day=$+{day} Year=$+{year}";
Perl 6 version
rx{ ^ $month := (/d{1,2}) { $^month <= 12 or fail } <[//]> $day := (/d{1,2}) { given( +$^month ){ when any(qw'1 3 5 7 8 10 12') { $day <= 31 or fail } when any(qw'4 6 9 11') { $day <= 30 or fail } when 2{ $day <= 29 or fail } default { fail } } } <[//]> $year := (/d{4}) $ }
Note this was quickly made and probably has a few bugs.
A slightly different approach that may or may not be useful for you.
I’m in php.
The project this relates to will never have a date prior to the 1st of January 2008. So, I take the ‘date’ inputed and use strtotime(). If the answer is >= 1199167200 then I have a date that is useful to me. If something that doesn’t look like a date is entered -1 is returned. If null is entered it does return today’s date number so you do need a check for a non-null entry first.
Works for my situation, perhaps yours too?
Here is the Reg ex that matches all valid dates including leap years. Formats accepted mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy format
^(?:(?:(?})$
courtesy Asiq Ahamed
if you didn’t get those above suggestions working, I use this, as it gets any date I ran this expression through 50 links, and it got all the dates on each page.
^20/d/d-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(0[1-9]|[1-2][0-9]|3[01])$
var dtRegex = new RegExp(/[1-9/-]{4}[0-9/-]{2}[0-9/-]{2}/); if(dtRegex.test(date) == true){ var evalDate = date.split('-'); if(evalDate[0] != '0000' && evalDate[1] != '00' && evalDate[2] != '00'){ return true; } }
To control a date validity under the following format :
YYYY/MM/DD or YYYY-MM-DD
I would recommand you tu use the following regular expression :
((])))
Matches
2016-02-29 | 2012-04-30 | 2019/09/31
Non-Matches
2016-02-30 | 2012-04-31 | 2019/09/35
You can customise it if you wants to allow only ‘/’ or ‘-‘ separators. This RegEx strictly controls the validity of the date and verify 28,30 and 31 days months, even leap years with 29/02 month.
Try it, it works very well and prevent your code from lot of bugs !
FYI : I made a variant for the SQL datetime. You’ll find it there (look for my name) : Regular Expression to validate a timestamp
Feedback are welcomed 🙂
This regex validates dates between 01-01-2000 and 12-31-2099 with matching separators.
^(0[1-9]|1[012])([- /.])(0[1-9]|[12][0-9]|3[01])/2(19|20)/d/d$
I landed here because the title of this question is broad and I was looking for a regex that I could use to match on a specific date format (like the OP)..
These are :-
Delimeters
[^/w/d/r/n:]
This will match anything that is not a word character, digit character, carriage return, new line or colon. The colon has to be there to prevent matching on times that look like dates (see my test Data)
You can optimise this part of the pattern to speed up matching, but this is a good foundation that detects most valid delimiters.
Note however; It will match a string with mixed delimiters like this 2/12-73 that may not actually be a valid date.
Year Values
(/d{4}|/d{2})
This matches a group of two or 4 digits, in most cases this is acceptable, but if you’re dealing with data from the years 0-999 or beyond 9999 you need to decide how to handle that because in most cases a 1, 3 or >4 digit year is garbage.
Month Values
(0?[1-9]|1[0-2])
Matches any number between 1 and 12 with or without a leading zero – note: 0 and 00 is not matched.
Date Values
(0?[1-9]|[12]/d|30|31)
Matches any number between 1 and 31 with or without a leading zero – note: 0 and 00 is not matched.
This expression matches Date, Month, Year formatted dates
(0?[1-9]|[12]/d|30|31)[^/w/d/r/n:](0?[1-9]|1[0-2])[^/w/d/r/n:](/d{4}|/d{2})
But it will also match some of the Year, Month Date ones. It should also be bookended with the boundary operators to ensure the whole date string is selected and prevent valid sub-dates being extracted from data that is not well-formed i.e. without boundary tags 20/12/194 matches as 20/12/19 and 101/12/1974 matches as 01/12/1974
Compare the results of the next expression to the one above with the test data in the nonsense section (below)
/b(0?[1-9]|[12]/d|30|31)[^/w/d/r/n:](0?[1-9]|1[0-2])[^/w/d/r/n:](/d{4}|/d{2})/b
There’s no validation in this regex so a well-formed but invalid date such as 31/02/2001 would be matched. That is a data quality issue, and as others have said, your regex shouldn’t need to validate the data.
Because you (as a developer) can’t guarantee the quality of the source data you do need to perform and handle additional validation in your code, if you try to match and validate the data in the RegEx it gets very messy and becomes difficult to support without very concise documentation.
Garbage in, garbage out.
Having said that, if you do have mixed formats where the date values vary, and you have to extract as much as you can; You can combine a couple of expressions together like so;
This (disastrous) expression matches DMY and YMD dates
(/b(0?[1-9]|[12]/d|30|31)[^/w/d/r/n:](0?[1-9]|1[0-2])[^/w/d/r/n:](/d{4}|/d{2})/b)|(/b(0?[1-9]|1[0-2])[^/w/d/r/n:](0?[1-9]|[12]/d|30|31)[^/w/d/r/n:](/d{4}|/d{2})/b)
BUT you won’t be able to tell if dates like 6/9/1973 are the 6th of September or the 9th of June. I’m struggling to think of a scenario where that is not going to cause a problem somewhere down the line, it’s bad practice and you shouldn’t have to deal with it like that – find the data owner and hit them with the governance hammer.
Finally, if you want to match a YYYYMMDD string with no delimiters you can take some of the uncertainty out and the expression looks like this
/b(/d{4})(0[1-9]|1[0-2])(0[1-9]|[12]/d|30|31)/b
But note again, it will match on well-formed but invalid values like 20010231 (31th Feb!) 🙂
Test data
In experimenting with the solutions in this thread I ended up with a test data set that includes a variety of valid and non-valid dates and some tricky situations where you may or may not want to match i.e. Times that could match as dates and dates on multiple lines.
I hope this is useful to someone.
Valid Dates in various formats Day, month, year 2/11/73 02/11/1973 2/1/73 02/01/73 31/1/1973 02/1/1973 31.1.2011 31-1-2001 29/2/1973 29/02/1976 03/06/2010 12/6/90 month, day, year 02/24/1975 06/19/66 03.31.1991 2.29.2003 02-29-55 03-13-55 03-13-1955 12/24/1974 12/30/1974 1/31/1974 03/31/2001 01/21/2001 12/13/2001 Match both DMY and MDY 12/12/1978 6/6/78 06/6/1978 6/06/1978 using whitespace as a delimiter 13 11 2001 11 13 2001 11 13 01 13 11 01 1 1 01 1 1 2001 Year Month Day order 76/02/02 1976/02/29 1976/2/13 76/09/31 YYYYMMDD sortable format 19741213 19750101 Valid dates before Epoch 12/1/10 12/01/660 12/01/00 12/01/0000 Valid date after 2038 01/01/2039 01/01/39 Valid date beyond the year 9999 01/01/10000 Dates with leading or trailing characters 12/31/21/ 31/12/1921AD 31/12/1921.10:55 12/10/2016 8:26:00.39 wfuwdf12/11/74iuhwf fwefew13/11/1974 01/12/1974vdwdfwe 01/01/99werwer 12321301/01/99 Times that look like dates 12:13:56 13:12:01 1:12:01PM 1:12:01 AM Dates that runs across two lines 1/12/19 74 01/12/19 74/13/1946 31/12/20 08:13 Invalid, corrupted or nonsense dates 0/1/2001 1/0/2001 00/01/2100 01/0/2001 0101/2001 01/131/2001 31/31/2001 101/12/1974 56/56/56 00/00/0000 0/0/1999 12/01/0 12/10/-100 74/2/29 12/32/45 20/12/194 2/12-73 | http://w3cgeek.com/regular-expression-to-match-valid-dates.html | CC-MAIN-2018-30 | en | refinedweb |
Introduction to MobX 4 for React/Redux Developers
shawn swyx wang 🇸🇬
Mar 17
Updated on Mar 19, 2018
MobX uses the "magic" of observables to manage state and side effects. This not only has a learning curve but is a different programming paradigm altogether, and there is not a lot of up-to-date training material on how to use React with Mobx, while there is far, far more content on using React with Redux.
In this intro we will progressively build up a simple app that pings a mock API to see how MobX works with React, and then make a MobX + React Kanban board to show off the power of MobX!
How we will proceed:
- Example A. Build a basic app that lets you type an text Input that is reflected in a Display. We show the basics of establishing
observables and
observercomponents.
- Example B. We split up the Input and Display into siblings to simulate a more complex app. We also introduce async state updating by pinging a mock API. To do this we use the
mobx-react
Providerto put MobX state into React context to demonstrate easy sibling-to-sibling or sibling-to-parent communication similar to
react-redux.
- Example C: We add a secondary Display to our app. Demonstrates the usefulness of
computedvariables (a Mobx concept).
- Example D: We scale our app up to do an arbitrary number of Displays. Demonstrates using arrays and maps for our MobX state.
- Example E: Tune up and Cleanup! We add the MobX dev tools, put our whole app in
useStrictmode and explain the formal use of MobX
actions and
transactions for better app performance.
This tutorial will use the recently released MobX 4 and MobX-React 5. A lot of people associate MobX with decorators, which are only a stage 2 proposal. That (rightfully) causes hesitation for some people, but MobX 4 introduces non-decorator based syntax so we don't have that excuse anymore! However; for tutorial writers this is a problem, because you have to decide to either teach one or the other or both. To resolve this, every example here will use the non decorator syntax as the primary version, but will have a clone that uses decorators to show the equivalent implementation (e.g. Example A vs Decorators A).
Note to Reader: There is not an attempt at recommending MobX over Redux or vice versa. This is solely aimed at factually introducing core MobX concepts for people like myself who were only familiar with Redux. I will attempt to draw some conclusions but reasonable people will disagree. Additionally, Michel Weststrate has stated repeatedly that both libraries address completely different requirements and values.
EXAMPLE A1: React + MobX
Here is our very basic app using React + MobX:
import { decorate, observable } from "mobx"; import { observer } from "mobx-react"; const App = observer( class App extends React.Component { text = ""; // observable state render() { // reaction return ( <div> Display: {this.text} <br /> <input type="text" onChange={e => { this.text = e.target.value; // action }} /> </div> ); } } ); decorate(App, { text: observable });
(Example A1, Decorators A1)
You can see here that
observer connects the observable
text property of
App so that it rerenders whenever you update
text.
While this is nice, it really isn't any different from using
state and
setState. If you have React you don't need MobX just to do this.
EXAMPLE A2: So what?
Let's try separating the concerns of state and view model:
// this deals with state const appState = observable({ text: "" // observable state }); appState.onChange = function(e) { // action appState.text = e.target.value; }; // this deals with view const App = observer( class App extends React.Component { render() { // reaction const { text, onChange } = this.props.store; return ( <div> Display: {text} <br /> <input type="text" onChange={onChange} /> </div> ); } } ); // you only connect state and view later on... // ... <App store={appState} />
(Example A2, Decorators A2)
Here the
store:
- is explicitly passed in as a prop (we will use the
Providerpattern later)
- brings its own action handlers along with it (no separate reducers to import)
EXAMPLE A3: But that's not OO
Look at this part of the above code.
const appState = observable({ text: "" // observable state }); appState.onChange = function(e) { // action appState.text = e.target.value; };
Yeah, I dont like that. The method isn't encapsulated within the observable. Can we make it more object oriented?
// import { decorate } from 'mobx' class State { text = ""; // observable state onChange = e => (this.text = e.target.value); // action }; decorate(State, { text: observable }); const appState = new State()
(Example A3, Decorators A3)
ahh. much better (especially the Decorators example where you don't need to use
decorate)!
EXAMPLE B1: But I hate prop drilling!
Just like
react-redux lets you put your store in a
Provider,
mobx-react also has a
Provider that works in the same way. We will refactor our Display and our Input components into sibling apps:
import { inject, observer, Provider } from "mobx-react"; class State { text = ""; // observable state onChange = e => (this.text = e.target.value); // action } decorate(State, { text: observable }); const appState = new State(); const Display = inject(["store"])( observer(({ store }) => <div>Display: {store.text}</div>) ); const Input = inject(["store"])( observer( class Input extends React.Component { render() { // reaction return <input type="text" onChange={this.props.store.onChange} />; } } ) ); // look ma, no props const App = () => ( <React.Fragment> <Display /> <Input /> </React.Fragment> ); // connecting state with context with a Provider later on... // ... <Provider store={appState}> <App /> </Provider>
(Example B1, Decorators B1)
Note that if I were to add a -second- store, I could simply define another
observable, and pass it in to
Provider as another prop, which I can then call from any child. No more redux style
combineReducers!
Using a Provider also helps avoid creating global store instances, something that is strongly advised against in MobX React Best Practices.
MobX 4 Note: If you just try to use the old MobX
observer(['store']) shorthand, which was always synonymous with
observer +
inject(['store']), you will get a very nice deprecation warning to not do that anymore.
I found this inject/observer syntax a bit fiddly, so this is a nice little utility function you can define to type less:
const connect = str => Comp => inject([str])(observer(Comp));
Hey! that's like our good friend
connect from
react-redux! The API is a little different, but you can define whatever you want 🤷🏼♂️.
EXAMPLE B2: Ok but what about async
Well for async API fetching we have a few choices. We can go for:
mobx-thunk
mobx-observable
mobx-saga
- and about 300 other options.
They're all special snowflakes and we can't wait to see what you decide on!
pause for rage quit...
Ok if you couldnt tell, I was kidding. Using observables means you can "just" mutate the observables and your downstream states will react accordingly. You might have observed that I have been annotating the code examples above with
// reaction,
// action, and
// observable state, and they mean what they normally mean in English. We'll come back to this.
Back to code! Assume we now have an async API called
fetchAllCaps. This is a
Promise that basically capitalizes any text you pass to it, after a 1 second wait. So this simulates a basic request-response flow for any async action you want to take. Let's insert it into our example so far!
class State { text = ""; // observable state onChange = e => { // action this.text = e.target.value; fetchAllCaps(e.target.value).then(val => (this.text = val)); }; } decorate(State, { text: observable }); const appState = new State();
(Example B2, Decorators B2)
Well that was... easy?
Note that here we are using the public class fields stage 2 feature for that
onChange property, while not using decorators, which are also stage 2. I decided to do this because public class fields are so widespread in React (for example, it comes with
create-react-app) that you likely already have it set up or can figure out how to set it up in Babel if you need to).
CONCEPT BREAK! Time to recap!
We've come this far without discussing core MobX concepts, so here they are:
- Observable state
- Actions
- Derivations (Reactions and Computed values)
In our examples above we've already used observable states as well as defined actions that modify those states, and we have used
mobx-react's
@observer to help bind our React components to react to changes in state. So that's 3 out of 4. Shall we check out Computed values?
EXAMPLE C: Computed Values
Computed values are essentially reactions without side effects. Because Observables are lazy by default, MobX is able to defer calculations as needed. They simply update whenever the observable state updates. Another way of phrasing it, computed values are derived from observable state.
Let's add a computed value that just reverses whatever is in
text:
class State { text = ""; get reverseText() { return this.text .split("") .reverse() .join(""); } onChange = e => { // action this.text = e.target.value; fetchAllCaps(e.target.value).then(val => (this.text = val)); }; } decorate(State, { text: observable, reverseText: computed }); const appState = new State(); // lower down... const Display2 = inject(["store"])( observer(({ store }) => <div>Display: {store.reverseText}</div>) );
(Example C1, Decorators C1)
Cool! It "just works" (TM) !
A fair question to have when looking at this is: why bother?? I can always put synchronous business logic in my React
render function, why have computed values at the appState level at all?
That is a fair criticism in this small example, but imagine if you rely on the same computed values in multiple places in your app. You'd have to copy the same business logic all over the place, or extract it to a file and then import it everywhere. Computed values are a great way to model derivations of state by locating them nearer to the state rather than nearer to the view. It's a minor nuance but can make a difference at scale.
By the way, vue.js also has computed variables, while Angular just uses them implicitly.
EXAMPLE D1: Observable Arrays
MobX can make basically anything observable. Let me quote the docs:
- If value, all its current properties will be made observable. See Observable Object
- If value is an object with a prototype, a JavaScript primitive or function, a Boxed Observable will be returned. MobX will not make objects with a prototype automatically observable; as that is the responsibility of its constructor function. Use extendObservable in the constructor, or @observable in its class definition instead.
In the examples above we have so far been making Boxed Observables and Observable Objects, but what if we wanted to make an array of observables?
Observable Arrays are array-like objects, not actual arrays. This can bite people in the behind, particularly when passing data to other libraries. To convert to a normal JS array, call
observable.toJS() or
observable.slice().
But most of the time you can just treat Arrays as arrays. Here's a very simple Todo app using an observable array:
class State { text = ["get milk"]; // observable array onSubmit = e => this.text.push(e); // action } decorate(State, { text: observable }); const appState = new State(); const Display = inject(["store"])( observer(({ store }) => ( <ul>Todo: {store.text.map(text => <li key={text}>{text}</li>)}</ul> )) ); const Input = observer( ["store"], class Input extends React.Component { render() { // reaction return ( <form onSubmit={e => { e.preventDefault(); this.props.store.onSubmit(this.input.value); this.input.value = ""; }} > <input type="text" ref={x => (this.input = x)} /> </form> ); } } ); const App = () => ( <React.Fragment> <Display /> <Input /> </React.Fragment> );
(Example D1, Decorators D1)
note that "just
push" just works!
Example D2: Observable Maps
What's the difference between Observable Objects (what we used in Examples A, B, and C) and Observable Maps? Well, its the same difference between Plain Old Javascript Objects and ES6 Maps. I will quote the MobX doc in explaining when to use Maps over Objects:
Observable maps are very useful if you don't want to react just to the change of a specific entry, but also to the addition or removal of entries.
So if we want to have a bunch of Todo lists, where we can add new todo lists, this is the right abstraction. So if we take that App from Example D1, rename it to
TodoList and put it in
todolist.js with some other superficial tweaks, then on
index.js, we can do this:
// index.js const connect = str => Comp => inject([str])(observer(Comp)); // helper function const listOfLists = observable.map({ Todo1: new TodoListClass(), Todo2: new TodoListClass() // observable map rerenders when you add new members }); const addNewList = e => listOfLists.set(e, new TodoListClass()); const App = connect("lists")( class App extends React.Component { render() { const { lists } = this.props; return ( <div className="App"> <span /> <h1>MobX Kanban</h1> <span /> {Array.from(lists).map((k, i) => ( <div key={i}> {/*Provider within a Provider = Providerception */} <Provider todolist={k}> <TodoList /> </Provider> </div> ))} <div> <h3>Add New List</h3> <form onSubmit={e => { e.preventDefault(); addNewList(this.input.value); this.input.value = ""; }} > <input type="text" ref={x => (this.input = x)} /> </form> </div> </div> ); } } );
(Example D2, Decorators D2)
And hey presto! We have a Kanban board (an expandable list of lists)!
This was enabled by the dynamically expanding ability of that
listOfLists which is an Observable Map. To be honest, you could probably also use Arrays to achieve this but if you have a use case that is better suited for demonstrating Observable Maps, please let me know in the comments below.
Example E1: MobX Dev Tools
Redux dev tools are (rightfully) an important part of Redux's value, so let's check out MobX React dev tools!
import DevTools from 'mobx-react-devtools'; // npm install --save-dev mobx-react-devtools // somewhere within your app... <DevTools />
(Example E1, Decorators E1)
You can see the three icons pop up:
- Visualize rerenders
- Audit the dependency tree
- Log everything to console (use Browser console not Codepen console)
You can't do time travel but this is a pretty good set of tools to audit any unexpected state changes going on in your app.
Stay tuned...
There is a blocking bug with
mobx-dev-tools and
mobx 4: and I will finish this out when the bug is fixed.
However in the mean time you can check out how to explicitly define
actions so that MobX can batch your state changes into
transactions, which is a big performance saver:
Notice how we were able to do all our demos without using the
actions - MobX has a (poorly) documented strict mode (formerly
useStrict, now
configure({enforceActions: true});) - see the MobX 4 docs. But we need the dev tools to really show the benefits for our example app.
Acknowledgements
This introduction borrows a lot of code and structure from Michel Weststrate's egghead.io course, but updates the 2 year old course for the current Mobx 4 API. I would also like to thank my employer for allowing me to learn in public.
The examples here were done with the help of Javid Askerov, Nader Dabit, and Michel.
Other Tutorials and Further Reading
Other recent guides
Docs
- MobX docs - common pitfalls and best practices
- MobX changelog - be very careful on v3 vs v4 changes
- official MobX+React 10 minute guide
Older
Related libraries to explore
- MobX state tree and associated blogpost
Contribute
What other current (<1yr) resources should I include in this guide? Have I made any mistakes? Let me know below!
Choosing a Programming Language
A discussion on programming languages and the rationale for choosing them
| https://dev.to/swyx/introduction-to-mobx-4-for-reactredux-developers-3k07 | CC-MAIN-2018-30 | en | refinedweb |
I've been working on this script all weekend and am almost done with it accept for one last detail; implementing a "process another number?" prompt after a user input is processed.
The script works like this: First, the user enters a number to test (to find the two prime numbers that make up that number). Next the program finds the numbers, outputs them, then quits.
What I want to do is create a prompt after the number has been processed that asks the user if they want to try another number or quit. I tried doing this but it isnt working rite... As it is now, after the user enters yes to continue the script simply exits instead of asking the user for another number.
Here is that output:
This program finds two prime numbers that add up to any even number you enter.
Enter an even integer larger than 2: 6
========================================
Found two prime numbers that sum to 6 !
6 = 3 + 3
========================================
Would you like to try another number (yes or no)? y
>>>
Could someone please show me what i'm doing wrong and how to get it working rite?
Heres my code:
import math def is_prime(p): if p == 2: return True else: return prime_test(p) def is_even(n): return n % 2 == 0 def prime_test(p): stop = int(math.ceil(math.sqrt(p))) + 1 if p % 2 == 0: return False else: for i in range(3, stop, 2): if p % i == 0: return False return True # is a prime def validated_input(moredata): while moredata[0] == "y" or moredata[0] == "Y": input = raw_input("\nEnter an even integer larger than 2: ") try: n = int(input) except ValueError: print "*** ERROR: %s is not an integer." % input for x in range(2, int(math.ceil(math.sqrt(n))) + 2): if n % x == 0: break if x == int(math.ceil(math.sqrt(n))) + 1: print "*** ERROR: %s is already prime." % input if is_even(n): if n > 2: return n else: print "*** ERROR: %s is not larger than 2." % n else: print "*** ERROR: %s is not even." % n return None def main(): print "This program finds two prime numbers that add up to any even number you enter." moredata = "y" n = validated_input(moredata) if n: for p in xrange(2, int(math.ceil(math.sqrt(n))) + 2): if is_prime(p) and is_prime(n - p): print "="*40,"\nFound two prime numbers that sum to",n,"!" print n, '= %d + %d' % (p, n - p),"\n","="*40 moredata = raw_input("\nWould you like to try another number (yes or no)? ") if __name__ == '__main__': main() | https://www.daniweb.com/programming/software-development/threads/114252/need-some-help-implementing-a-continue-or-quit-prompt | CC-MAIN-2018-30 | en | refinedweb |
Tue Sep 4 09:40:36 PDT 2001 <blair@orcaware.com> Blair Zajac * Release version 1.05. Sun Sep 2 23:06:10 PDT 2001 <blair@orcaware.com> Blair Zajac * lib/DateTime/Precise.pm: Change the default value of $USGSMidnight from 1 to 0, which in dprintf now disables treating midnight (00:00) of one day as 24:00 from the previous day. This results in odd behavior when the date is printed using dprintf, as it will return the previous date. Fix the POD documentation for $USGSMidnight to complete the end of the sentence. * lib/DateTime/Precise.pm: Optimize dprintf to use a series of elsif's instead of a series of if's when deciding what to do with a %X string. * lib/DateTime/Precise.pm: Do not put &IsLeapYear and &DaysInMonth in @EXPORT, instead put them in @EXPORT_OK to reduce namespace pollution. * lib/DateTime/Precise.pm: Instead of doing multiple shift's in subroutines to get the subroutine's parameter, set the variables directly from @_. * lib/DateTime/Precise.pm: Change the variables $Secs_per_week, $Secs_per_day, $Secs_per_hour and $Secs_per_minute to constant subroutines to improve the performance of the module. * t/01date_time.t: Ditto. * lib/DateTime/Precise.pm: Make minor formatting changes to reflect my current coding style. Tue Aug 28 13:16:59 PDT 2001 <blair@orcaware.com> Blair Zajac * Release version 1.04. Tue Aug 28 13:14:01 PDT 2001 <blair@orcaware.com> Blair Zajac * README: Update Blair Zajac's email address to blair@orcaware.com. Remove reference to the Caltech FTP site for a secondary repository of Blair Zajac's Perl modules. * lib/DateTime/Precise.pm: Update Blair Zzajac's email address to blair@orcaware.com. Tue Aug 28 12:34:15 PDT 2001 <blair@orcaware.com> Blair Zajac * lib/DateTime/Precise.pm: The $VERSION variable was being set using $VERSION = substr q$Revision: 1.04 $, 10;' which did not properly set $VERSION to a numeric value in Perl 5.6.1 probably due to the trailing ' ' character after the number. This resulted in 'use DateTime::Precise 1.03' failing to force Perl to use version 1.03 or newer of DateTime::Precise even if 1.02 or older was installed because $VERSION was set using substr and Perl would not consider $VERSION to be set. Now use the longer but effective: $VERSION = sprintf '%d.%02d', '$Revision: 1.04 $' =~ /(\d+)\.(\d+)/; Sun Jun 10 20:10:19 PDT 2001 * Release 1.03. Sun Jun 10 18:54:44 PDT 2001 <blair@orcaware.com> (Blair Zajac) * lib/DateTime/Precise.pm: Try to import Time::HiRes::time to load a high resolution time. Fix a bug when the time was modified using seconds() and the time had previously a non-zero fractional second component. The previous fractional seconds would be included in a sum with the argument to seconds(). Now reset the fractional part of the time to 0 before using the seconds() argument. * t/01date_time.t: Reorder a test to ensure that the above bug in seconds() is checked. Thu Feb 22 20:37:22 PST 2001 <blair@orcaware.com> (Blair Zajac) * Release version 1.02. Thu Feb 22 20:27:46 PST 2001 <blair@orcaware.com> (Blair Zajac) * Fix a bug where if 0 is passed to an increment or decrement function, then it would actually increment the time by 1 unit. Check for a defined value instead of a non-0 or non-'' value. Wed Jan 31 15:24:17 PST 2001 <blair@orcaware.com> (Blair Zajac) * Release version 1.01. Wed Jan 31 15:09:10 PST 2001 <blair@orcaware.com> (Blair Zajac) * Fix a bug where a \s was not being properly added to a regular expression. This also fixes the 'Unrecognized escape \s passed through at Precise.pm line 1483' warning when using Perl 5.6.0. Thu Apr 8 10:20:30 PDT 1999 <blair@orcaware.com> (Blair Zajac) * Have ok() in t/*.t return the success or failure of the test instead of the number of tests performed. * Release version 1.00. Thu Oct 22 09:11:09 PDT 1998 <blair@orcaware.com> (Blair Zajac) * Fix a bug in new() where it wouldn't correctly set the time using the one argument form of time. This bug found by Joe Pepin <joepepin@att.com>. * Fix some spelling mistakes. * Release version 0.04. Sun Jun 28 11:56:40 PDT 1998 <blair@orcaware.com> (Blair Zajac) * Add dscanf('%u') which loads GMT time into the object. This complements dscanf('%U') which loads local time into the object. * lib/DateTime/Precise.pm: Update the POD to reflect the change in dscanf. * Change test #8 to use %u instead of %U so the test will succeed in any timezone. Release version 0.03. Fri Jun 26 16:57:37 PDT 1998 <blair@orcaware.com> (Blair Zajac) * Add a new jday() method that returns day_of_year() - 1. Fri Jun 26 15:06:52 PDT 1998 <blair@orcaware.com> (Blair Zajac) * New() didn't properly initialize the underlying representation of DateTime::Precise before it was passed off to set_time(). Add a new test to cover this case. * Update the POD a little. * Release version 0.02. Mon Jun 22 13:46:03 PDT 1998 <blair@orcaware.com> (Blair Zajac) * Add a new method copy, which creates a new copy of an existing DateTime::Precise object. Use copy to create copies of times instead of new and clone. Add tests for copy. * Add comparison test between integer and fractional times. Sun Jun 21 12:05:38 PDT 1998 <blair@orcaware.com> (Blair Zajac) * Have overloaded neg operator state the class of the offending object instead of DateTime::Precise. * Have all of the set_* methods return the newly set object if the set was successful, undef otherwise. Thu Apr 24 12:00:00 PDT 1998 <blair@orcaware.com> (Blair Zajac) * Version 0.01 First version. * Merge jpltime.pl from the JPL GPS group and DateTime.pm from Greg Fast into this package. * The changes below refer to the DateTime part of this package written by Greg Fast. Revision history for DateTime.pm Version numbers refer to RCS/CVS revision number. 1.4.1 r1.17 Thu Apr 2 1998 - damn. set_from_epoch time was broken. serves me right for not running my own 'make test'. 1.4 r1.16 Mon Mar 30 1998 - redid documentation. cleaned up, etc. nothing exciting. - ignored Changes file long enough for it to no longer be valid. 1.3.2 r1.8 Mon Sep 15 15:00:00 1997 - oops. addSec was behaving very wrong on day boundaries. 1.3.1 r1.7 Thu Sep 11 18:50:04 CDT 1997 - squashed bug in passing new a dt of form "yyyy.mm.dd" (no time) 1.3 r1.5 Thu Sep 11 10:20:04 CDT 1997 - switched internal obj storage from hash to scalar. 1.2.6 r1.3 Wed Sep 10 18:47:36 1997 - imported to CVS - added 22 deadly (heh) tests to test.pl - fixed subtle bug in overloaded <=> and cmp (in comparing objects with non-objects) 1.21 Fri Sep 05 20:45:55 1997 - suppressed some warnings 1.20 Fri Sep 05 20:12:22 1997 - added new-from-internalfmt capability. 1.19 Thu Sep 04 23:30:34 1997 - properly reset $VERSION 1.18 Thu Jul 31 20:42:19 1997 - replaced some tr///s with lc()s 1.17 Thu Jul 31 19:35:28 1997 - whee 1.16 Thu Jul 31 19:28:39 1997 - dscanf now works quietly, and doesn't die on failure. 1.15 Thu Jul 31 19:08:31 1997 - dscanf works properly 1.14 Thu Jul 31 18:48:51 1997 - functional, but vapid, dscanf inserted 1.13 Tue Jul 29 00:08:54 1997 - interim random checkin. 1.12 Thu Jun 19 16:42:50 1997 - weekday tested. bug in AUTOLOADING of dec_* fixed. 1.10 Thu Jun 19 16:25:01 1997 - typo 1.9 Thu Jun 19 16:20:41 1997 - added weekday(), dprintf("%w") 1.8 Fri Jun 06 20:28:08 1997 - doco fixes 1.4 Thu May 22 20:05:07 1997 - started doco. (copied to nwisw tree) 1.2 Fri May 09 02:23:55 1997 - fixed all references to Gtime 1.1 Tue Apr 29 22:45:51 1997 - Initial revision | https://metacpan.org/changes/distribution/DateTime-Precise | CC-MAIN-2018-30 | en | refinedweb |
Document Number: P1097R1
Date: 2018-06-22
Audience: SG16, EWG, CWG
Author: R. Martinho Fernandes
Reply-to: cpp@rmf.io
This paper proposes a new character escape sequence that enables the programmer to refer to a character by its name or alias.
Currently C++ provides four ways to specify characters in string literals:
\xescapes that corresponds to the underlying code units of the character;
\uescape that corresponds to the ISO 10646 short identifier of the character;
\Uescape that corresponds to the ISO 10646 short identifier of the character;
These last two are the best way to represent specific Unicode characters that may be hard to type, hard to read, or that cannot be represented in the source encoding. For example, if one wants a string literal with a combining acute accent, typing
"\u0301" is easier than producing a combining acute without a base character, and it is guaranteed that it won't render wonky in a text editor (e.g. the acute could be rendered on top of the opening double quotes, making it ugly, and above all, easy to miss).
However,
"\u0301" is hard to read as well: yes, it's unambiguously clear that this is the character U+0301, but in general there is no way to know what character that is without first looking it up on some table. This solves the problem of clarity that is inherent with typing the character directly, but in turn it obfuscates the actual character behind a series of meaningless numbers.
Other programming languages, in particular Python 3, Perl 5, and Perl 6, have solved this obfuscation problem by providing an alternative character escape mechanism. In these languages, one can specify a character by using its Unicode Name, as in the following Python 3 example:
>>> print('A\N{COMBINING ACUTE ACCENT}') Á
Having this ability enables one to choose between the brevity of "0301" and the clarity of "combining acute accent" as desired.
What follows is a Tony Table that demonstrates the differences between the existing mechanisms and the proposed one.
Each Unicode character has a Name property associated. They correspond to the names in the English edition of ISO/IEC 10646. These names are meant to be used as unique identifiers for each character. Once assigned they never change. Such names contain only characters from a limited set: the capital letters A-Z, the digits 0-9, spaces, and hyphens; all of them are in the C++ basic character set. Supporting these names is the bare minimum necessary for this feature.
However, for added convenience, some leeway in the matching of these names is preferable. The names use only capital letters, but it would be convenient to ignore case so that the following all result in the same string:
"\N{LATIN CAPITAL LETTER A}" // exact match "\N{Latin capital letter A}" "\N{latin capital letter a}"
Another convenient feature would be to allow hyphens and spaces to be treated the same, so as to make the following result in the same string:
"\N{ZERO WIDTH SPACE}" // exact match "\N{ZERO-WIDTH SPACE}" // common spelling, e.g. Wikipedia "\N{zero-width space}"
The Unicode Standard describes which transformations are guaranteed to still produce unique identifiers and recommends the loose matching rule UAX44-LM2: "Ignore case, whitespace, underscore ('_'), and all medial hyphens except the hyphen in U+1180 HANGUL JUNGSEONG O-E". This is the most liberal set of transformations that can be forwards-compatible. Stricter sets of transformations are also possible. Python 3 allows lowercasing the names, but no other differences; Perl 6 allows only exact matching names.
In addition to the Name property, Unicode characters can also have several values of the Name_Alias property assigned to them. The values of this property are effectively additional names for a character. Aliases can be corrections, names for characters that have no Name property, alternative names, or common abbreviations.
Assignment of these aliases follows the same rules of assignment of Names: they draw from the same character set, once assigned the values are immutable, and they share the same namespace. Thanks to this last property, it is possible to allow named character escape sequences to match via both the Name and Name_Alias property.
"\N{NO-BREAK SPACE}" // matches Name for U+00A0 "\N{KANNADA LETTER LLLA}" // matches correction alias for U+0CDE "\N{NBSP}" // matches abbreviation alias for for U+00A0 "\N{LINE FEED}" // matches control character alias for U+000A "\N{LF}" // matches abbreviation alias for U+000A
All of Python 3, Perl 5, and Perl 6 support name aliases in their named character escapes.
These aliases are defined normatively by the Unicode Standard, but not all of them are normative in ISO/IEC 10646. This means that, without a normative reference to the Unicode Standard, only names or correction aliases two can be specified to work.
In addition to names and aliases, there is a third set of identifiers that shares the same namespace and the same rules of assignment: named character sequences. These names represent sequences of Unicode characters for which there is a need for an identifier; they are used e.g. to correlate with identifiers in other standards. Again, because these share the same namespace, it is possible to add these as a third option for matching named character escape sequences without conflict.
"\N{LATIN SMALL LETTER I WITH MACRON AND GRAVE}" // matches the named sequence <U+012B, U+0300> "\N{KEYCAP DIGIT ZERO}" // matches the named sequence <U+0030, U+FE0F, U+20E3>"
Python 3 does not support named character sequences, but Perl 5 and Perl 6 do.
This paper proposes a new character escape sequence that enables the programmer to refer to a character by one of its names. Specifically, out of the possibilities delineated above, this paper proposes the following kinds of name matching:
This specific set of features was chosen by virtue of being both reasonably simple and reasonably convenient. A larger feature set could also be specified if there is strong feedback in that direction.
Note that, unlike with the
\u and
\U syntaxes, which are allowed in identifiers, the proposed
\N is only valid in character and string literals.
The syntax used in the description above uses
\N{NAME} as the escape sequence for this feature merely because of the author's familiarity with Python 3. Perl 5 uses the same syntax as Python 3 but Perl 6 uses
\c[NAME], instead. Either of these two syntaxes would generate no significant conflicts with present day C++ syntax. The only potential conflict that this could cause would be with code that has character and string literals with extraneous backslashes: presently, the string literal
"\N{NBSP}" is equivalent to
"N{NBSP}". This doesn't seem like something that occurs often and in the unlikely case that it occurs, it's easy to search for and to work around (one can simply remove the backslash).
Other alternatives are also possible, as long as we paint the shed red.
Add the following item after 2 [intro.refs], item (1.2):
(1.3) — The Unicode Consortium. The Unicode Standard.
Edit 5.13.3 [lex.ccon] as follows:
escape-sequence:
simple-escape-sequence
octal-escape-sequence
hexadecimal-escape-sequence
Add the following paragraph after 5.13.3 [lex.ccon], paragraph 9:
10
Edit 5.13.5 [lex.string], paragraph 15 as follows:
15 Escape sequences and universal-character-names in non-raw string literals have the same meaning as in character literals, except that the single quote
'is representable either by itself or by the escape sequence
\', and the double quote
"shall be preceded by a
\, and except that a universal-character-name in a
char16_tstring literal may yield a surrogate pair. In a narrow string literal, a universal-character-name may map to more than one char element due to multibyte encoding. The size of a
char32_tor wide string literal is the total number of escape sequences, universal-character-names, and other characters, plus one for the terminating
U'\0'or
L'\0'. The size of a
char16_tstring literal is the total number of escape sequences, universal-character-names, and other characters, plus one for each character requiring a surrogate pair, plus one for the terminating
u'\0'. [ Note: The size of a
char16_tstring literal is the number of code units, not the number of characters. — end note] Within
char32_tand
char16_tstring literals, any universal-character-names shall be within the range
0x0to
0x10FFFF. The size of a narrow string literal is the total number of escape sequences and other characters, plus at least one for the multibyte encoding of each universal-character-name, plus one for the terminating
'\0'.
Edit 5.2 [lex.phases], paragraph 1, step 5 as follows:
- Each source character set member in a character literal or a string literal as well as each escape sequence
anduniversal-character-name in a character literal or a non-raw string literal, is converted to the corresponding member of the execution character set ([lex.ccon], [lex.string]); if there is no corresponding member, it is converted to an implementation-defined member other than the null (wide) character. | http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1097r1.html | CC-MAIN-2020-10 | en | refinedweb |
Angular: How to support IE11
In this article I will show you the steps I took to support Internet Explorer 11 with Angular. The first half of this will quickly show the steps you need to take, and the second half will break these steps down in more detail for anyone wishing to learn more. At the end I’ll add some additional tips that may come up in a real-world application.
💪 Let’s get it done
🎯 Step 1 — Targeting ES5
IE11 only supports at best ES5. Therefore we have to update our
tsconfig.json.
Update the
target property in
compilerOptions to match the following, if not already:
"compilerOptions": {
"target": "es5"
}
🌐 Step 2 — Update
broswerlist
Open you
browserlist file and change the line
not IE 9-11 to match:
not IE 9-10
IE 11
🔧 Step 3 — Polyfills
If you or any of your dependencies use features from ES6+, you’re going to need to polyfill those. CoreJS is included with Angular install, and can be used for the majority of the polyfills you require.
Open your
polyfills.ts file and place the following at the top under
BROWSER POLYFILLS:
If you need a quick win (NOT RECOMMENDED):
import 'core-js';
Otherwise, try to discern what polyfills you need. I found that these covered my use-case:/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
import 'core-js/es6/array';
import 'core-js/es7/array'; // for .includes()
The next part we need to do is to find the following lines, near the top of
polyfills.ts:
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
As instructed run:
npm install --save classlist.js
and then uncomment the import:
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import ' classlist.js ' ; // Run `npm install --save classlist.js`.
If you use Angular Material or the
AnimationBuilder from
@angular/platform-browser/animations then find the following line:
// import 'web-animations-js';
// Run `npm install --save web-animations-js`.
Uncomment the import statement and run
npm install --save web-animations-js.
Your final
polyfills.ts file should look similar to:
✅ Completed
And that’s it! You should be good to go! 🚀🚀
You may well run into further issues. Some of these will now be discussed in the second half of this article.
🤯 But why?
Let’s go quickly go through the why’s of each step above before we go into some further tips on additional problems that may arise.
- Target ES5: Pretty straightforward, IE11 only supports ES5 or lower. Therefore, TypeScript needs to Transpile your code to ES5 compatible code.
- Browserlist: This is an interesting one. We need to say we are supporting IE 11, but if we are not supporting IE 9 or 10, it’s equally important to specifically say we aren’t supporting them, otherwise the differential loader will include a lot of guff. _(Thanks @wescopeland_ for that advice)_
- Polyfills — Some of the libraries we work with, or code we write, relies on features from versions of ECMAScript that IE11 doesn’t support, therefore we need to provide this functionality to ES5 manually using workarounds. This will allow the code using modern features to continue to work correctly. (Note: Each polyfill will increase the bundle size, so be careful when choosing which polyfills to import)
💡 Some additional tips
Ok, so the motivation to write this article came from being tasked to support IE11 in our green-field app. It was particularly painful as it was an afterthought that then highlighted compatibilities issues with supporting IE11:
Third-party dependencies need to support ES5
This became evident quickly as the errors were easily spit out into the console. But it did highlight an interesting problem.
Now if we want to include a new dependency or library in our application, we need to make sure that it builds to and supports ES5, otherwise, we have to skip it. This could potentially limit our choices going forward, which is never ideal.
IE11 doesn’t support CSS Custom Properties
This became hell quickly. IE11 doesn’t support CSS Custom Properties such as
--primary-color: blue; which meant our theming solution was potentially on the ropes.
After a lot of investigation, I found that it could be polyfilled, however, the polyfills that I found were slow, had a huge impact on the bundle size and not entirely perfect. missing features such as multiple Custom Properties in one line among other issues.
They also didn't work for our particular use-case and our theming solution which relied on runtime setting of the Custom Properties.
My solution to this came from the css-vars-ponyfill that allowed the setting of global Custom Properties at runtime. Awesome 🔥🔥
Setting the
style attribute in IE11
IE11 will only allow the setting of a DOM Element’s
style attribute with CSS Properties it supports.
For example, doing the following:
document.body.style = '--primary-color: blue; font-size: 18px';
results in the following on IE11, losing the
--primary-color: blue.
<body style="font-size: 18px"></body>
Styling issues arising from flexbox support
IE11 does support flexbox, but it’s very picky about how it does so. I noticed that if I wanted to use
flex: 1; to allow an element to fill the remaining space, on IE11 I had to set the full flex property:
flex: 1 0 auto; or something similar.
Running DevTools in IE11 conflicts with zone.js
Yep. For some reason, when you open dev tools whilst having
ng serve running on IE11 causes conflicts with
zone.js;
To fix this you need to add a global
ZONE FLAG for zone to execute slightly additional code.
You do this in
polyfills.ts. Find the
zone.js import and add the following so it looks like this:
(window as any).__Zone_enable_cross_context_check = true; import 'zone.js/dist/zone'; // Included with Angular CLI.
😭 Conclusion
I did not have fun trying to get this to work during the week. Now that I have it supported; I feel pretty accomplished 💪.
I hope this article can save someone some pain in the future!
Hopefully you have gained something from reading this article, maybe a tidbit you didn’t know before.
If you have any questions, feel free to ask below or reach out to me on Twitter: @FerryColum.
Originally published at on January 10, 2020. | https://medium.com/javascript-in-plain-english/angular-how-to-support-ie11-d3b8c3d3494e?source=---------2------------------ | CC-MAIN-2020-10 | en | refinedweb |
Keeping Javascript test naming updated after refactoring
Jan Küster
・2 min read
Some days ago I ran into a problem. I refactored (simply renamed) some Functions and faced the situation, that I also had to update all the names in my tests, too... manually!
This is because I did not assigned the Functions a proper name, when I created them as a property of something else:
export const Utils = {} Utils.isDefined = function (obj) { return typeof obj !== 'undefined' && obj !== null } // ...
In the tests I then wrote the function name by hand:
import { Utils } from '../Utils.js' describe ('Utils', function () { describe ('isDefined', function () { // ... }) })
Now later I realized, that the name
isDefined is somewhat wrong picked and I refactored it to
exists:
Utils.exists = function (obj) { return typeof obj !== 'undefined' && obj !== null }
Well, my tests were not covered by the update and still were outputting the old
isDefined:
Utils isDefined ✓ ...
I was thinking "how could I make my test automatically reflect my Function's namespaces?" and luckily (since ECMA2015) there is a nice way to always get a Function's name, using the
name property:
import { Utils } from '../Utils.js' describe ('Utils', function () { describe (Utils.exists.name, function () { // ... }) })
This will always be the Function's name, because it references to it and is thus covered by the refactoring. Keep in mind however, that in the current state of this code there will be nothing returned as name. This is because the Function simply has no name, yet. To do so we need to declare not only the property but also the Function name:
Utils.exists = function exists (obj) { return typeof obj !== 'undefined' && obj !== null }
and the tests are then automatically reflecting the naming:
Utils exists ✓ ...
Simple tweak with a great reduction in follow-up work here. For those of you, who think this would then require to double rename (property and Function name) then I encourage you to try out with your IDE: usually you should just have to refactor-rename one of them to trigger the refactoring of both.
Note, that in order to make this work with arrow functions, you need to declare them as variables:
const exists = (obj) => typeof obj !== 'undefined' && obj !== null Utils.exists = exists
The secret that the fonts industry doesn't want you to know
Finally the story of CSS's most unsung hero
| https://dev.to/jankapunkt/keeping-javascript-test-naming-updated-after-refactoring-1l6n | CC-MAIN-2020-10 | en | refinedweb |
Table of Contents
Introduction
Developing never stays in one place. New technologies are increasingly emerging to implement better software solutions. If you want to create a multi-functional, clearly-described system now, you should pay attention to APIs. Today we will take a look at the API principles, specifically for RESTful APIs. We will also consider an example of using ready APIs from the RapidAPI marketplace via C# and .NET Core.
What is a RESTful API?
Let’s explain what an API is before everything else. API stands for an application programming interface. In short, it’s a way to create a system with great usability and robustness. This system is based on requests that are dedicated to some exact endpoints. You could understand this principle like a conversation between user and program. The user asks something by a predefined standard, the program returns a feasible and informative response.
The main advantages of this approach can be formulated as follows:
- easy-to-understand – a good API has comprehensive information about every possible request, so developers won’t have too many problems with it;
- server-independence – the receiving side (i.e. server) doesn’t care about states and types of clients. APIs are good for a bigger part of the tools and applications: web/browser apps, mobile projects, desktop systems, etc.
- fast workload – requests are processed rapidly, that’s why final scripts could be very efficient;
- security – best practices of creating the API illustrate this expression. API supports various tools to make good and encrypted interaction services. Bright example: authorization, especially OAuth 2.0.
Now let’s clarify the RESTful part. There are many different concepts, you can explore this topic more here. We will describe and investigate REST API, as it is more widespread and popular right now.
REST stands for representational state transfer – a standard that ensures both feasibility (API will return correct data if the question is correct) and visibility. Data should be ready to use and well-prepared. Of course, there is some wordplay, because you can rest with a REST API – all the ‘dirty’ job is done without your participation. However, this standard has some important required features. If you want to create RESTful API, it should consist of some basic criteria:
- Client-server architecture – areas of responsibility are distributed directly. The client sends requests (questions), the server returns responses (answers). Such architecture allows making independent systems with separate sides of development.
- Statelessness – the server doesn’t need to remember any previous questions. This principle creates an opportunity to reduce data storage sizes and improve security.
- Cacheability – the client, instead of the receiving side, has some useful practices in the temporal data storing. It may be a very strong upgrade of productivity and computing for the system.
- Layered system – step-by-step separation of some different parts in the query->response chain. Each link in the chain only knows about its neighboring parts. This helps make more secure and portable systems. If some part of the interaction is broken, you don’t need to fix all parts.
- Uniform interface – as the client represents a start-point of the API, there must be an endpoint. That’s why, to prevent any misunderstanding, each possible interaction should have a direct and unique alias.
At this stage it is not necessary to take care of RESTful API creation, we will focus on the API calls. Let’s move to a practical example. It will be divided into two parts. First of all, there will be a simple guide on a basic API calling via a C# console application. Secondary, we will implement some sort of web app via ASP.NET Core.
How to call an API in C#
Prerequisites
As the tech stack, it is required to have a .NET package. We will use .NET Core, which is portable, lightweight and supportable for many different OS. On the link above, you could see and install this package. For the installation checking, you could type the next command in the terminal:
dotnet.
The output should look like this:
Usage: dotnet [options] Usage: dotnet [path-to-application] Options: -h|--help Display help. --info Display .NET Core information. --list-sdks Display the installed SDKs. --list-runtimes Display the installed runtimes. path-to-application: The path to an application .dll file to execute.
This command allows us to create different types of applications, install any possible libraries and build our projects. So any further manipulations with the code will be done via dotnet usage.
Now it’s time to do some outside API research!
And there is no better place on the internet, than RapidAPI, if you want to make some API calls. This portal supports a very big amount of different APIs: from enterprise to the custom ‘hello-world!’ interfaces. You don’t need to take care of any storing problems, any API is ready for your queries. Anytime, any day.
Find the search bar and let’s search for ‘microsoft text translation’. In the drop-down box, you can choose our subject today – translation tool from the C# creators. Let’s take a look at the basic view of the API and explain some key features.
Related: Google Translate API and Alternatives
First of all, pay attention, that this API is on the Freemium plan. It means, that you need to subscribe to this page if you want to use this API. Don’t worry, on the basic plan, it will be absolutely free. After subscribing, your screen should look something like this:
On the top, we can see a piece of brief information about the API. There are creator credentials, the popularity score, etc. Next line – 4 tabs about different edges of the project.
- Endpoints are the most interesting, so we will explore it further.
- API Details – a short description of the product from the creator.
- Discussions – some trends and issues within the RapidAPI community about the API.
- Pricing – listing of the usage cost.
Now let’s take a look at the Endpoints. Here we can see the conditional division of the screen into three parts.
- Left side – endpoints. Here is the possibility to switch between any created endpoints. Also, you could search for some of them. In this exact case, there are 6 endpoints.
- Translate – basic endpoint. Here we will point languages of translation and actual text. The response should have the translated text.
Speak – returns a wave or mp3 stream of the passed-in text being spoken in the desired language.
- Get Translate Supported Languages – obtain a list of language codes representing languages that are supported by the Translation Service.
- Get Speak Supported Languages – retrieves the languages available for speech synthesis.
- Detect Language – use the Detect method to identify the language of a selected piece of text.
- Break sentences – breaks a piece of text into sentences and returns an array containing the lengths in each sentence.
- Center – detail endpoint view. Here you can see all the required and possible parameters of the query. Take a look at the X-RapidAPI-Host and X-RapidAPI-Key. A former is a unique identifier of the API inside of the RapidAPI hub. Latter is your own unique identifier. This is it, no other registrations or tokens.
- Right side – testing part. Code snippets on any supportable programming language may help with the developing. Also, there are some hints in the installing. But the most interesting thing is testing in the browser. You could make requests right from here, with no discrete scripts.
Choose in the Code snippet part C#->Unirest. And press the button Install SDK.
Here it is, dotnet CLI component. Looks like this is what we are looking for.
Creating a project with all the required libraries
Now open a terminal and paste the next lines:
dotnet new console -o myApp cd myApp
Here we created a new console application. Open myApp folder and look at the directory structure. It should have folders bin and obj, .csproj description file and Program.cs. We will work inside of the last, but not now. Don’t forget about the requests’ library. RapidAPI recommends a very popular library, called Unirest. It has implementations for many programming languages and is also very easy to use. So let’s take a bit of advice and install it for this project.
dotnet add package Unirest-API --version 1.0.7.6
This is it! Now your .csproj file should have the next content:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.0</TargetFramework> <RootNamespace>myApp</RootNamespace> </PropertyGroup> <ItemGroup> <PackageReference Include="Unirest-API" Version="1.0.7.6" /> </ItemGroup> </Project>
So, our project is created with all the required libraries. Let’s finally make some code!
Making an API Call
Now our task is to implement Unirest and handle some response from the translation API. First of all, don’t forget to include Unirest via the next line in the using-section (top of the file). Paste next line in the Program.cs:
using unirest_net.http;
Now we can return to the site and take a look at the snippet for the C#. Paste the next lines in the main section of the file:
HttpResponse<string> response = Unirest.get("!") .header("X-RapidAPI-Host", "microsoft-azure-translation-v1.p.rapidapi.com") .header("X-RapidAPI-Key", "<YOUR_RAPID_API_KEY>") .header("Accept", "application/json") .asJson<string>(); Console.WriteLine(response.Body.ToString());
This simple code creates a variable, that handles GET request to the translate endpoint. Here we wrote, that we would like to translate “Hello world!” from the English to Spanish. Save changes and run this project via a simple dotnet run command in the terminal.
<string xmlns="">¡Hola mundo!</string>
Not so pretty, but the result is correct! Now we know how to say hello in Spanish and that we need to improve response processing.
Process the response and test the other endpoint
As you may notice, this API returns data in the XML format. It is widespread in Microsoft developing, so it’s not a big problem. All we need to do is this magic line in the using section:
using System.Xml;
There are some modules for simpler and faster XML processing. Now add these lines to the code:
XmlDocument doc = new XmlDocument(); doc.LoadXml(response.Body.ToString()); Console.WriteLine(doc.DocumentElement.FirstChild.InnerText);
Here we rewrite the response body string to the XmlDocument object, that can parse and prettify our data. As we have only one single node (with the translation result), we can just take it directly. Run and test the output:
¡Hola mundo!
So now we can make any possible API calls. Let’s test it on some other endpoint. For example, we can get all supported languages. Paste this snippet after previous in the Program.cs:
response = Unirest.get("") .header("X-RapidAPI-Host", "microsoft-azure-translation-v1.p.rapidapi.com") .header("X-RapidAPI-Key", "<YOUR_RAPID_API_KEY>") .asJson<string>(); doc.LoadXml(response.Body.ToString()); foreach(XmlNode node in doc.DocumentElement.ChildNodes){ Console.WriteLine(node.InnerText); }
Almost everything is the same, except for the XML processing. As there are many languages, we can just move step-by-step (via for each operator) on each node. Let’s take a look at the running results:
¡Hola mundo! af ar bn bs-Latn bg ca zh-CHS zh-CHT yue hr cs da nl en et fj fil fi fr de el ht he hi mww hu is id it ja sw tlh tlh-Qaak ko lv lt mg ms mt yua no otq fa pl pt ro ru sm sr-Cyrl sr-Latn sk sl es sv ty ta te th to tr uk ur vi cy
After a previously called translation (that part of code should still be in the file), we have had a pretty processed language list. You may be surprised, but we don’t need anything more to do some really interesting application.
Related: Top Translation APIs
Example: web translator
The idea of the application is as follows: we will propose to the potential user a translation form. There will be two drop-down boxes with any possible languages and special text input. Then, we will send this data to the translation endpoint and return the result. What are we waiting for?
Create a new project. It will be the ASP.NET Core application. This is a part of the .NET platform, that allows creating web applications on a C#. It is some sort of lightweight ASP.NET project, which is bigger and more advanced. As right now we need a simple and easy app, .NET Core version will be fitted perfectly.
Now create a new application via the next command line in the CLI:
dotnet new asp_rapid -o asp_rapid --no-https cd asp_rapid
The directory structure is more difficult, that in the console example. If you want some more detailed information about it, visit this page. At this point, we are interested only in 2 files: Index.cshtml and Index.cshtml.cs. Both of them are responsible for the Index view (basic view of the web app). Former is used for the visualization (view), latter – data preparing (controller). As our app is very simple and light, we don’t need models. But they may be required in more advanced projects.
Don’t forget to install Unirest:
dotnet add package Unirest-API --version 1.0.7.6
You can check the success of the installation in the .csproj file.
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> </PropertyGroup> <ItemGroup> </ItemGroup> <ItemGroup> <PackageReference Include="Unirest-API" Version="1.0.7.6" /> </ItemGroup> </Project>
Now we will modify both files. Let’s start from the Index.cshtml.cs file. Add these familiar lines to the using-section:
using System.Xml; using unirest_net.http;
So right now we can handle signals from the view and prepare data. Replace IndexModel class with the next code:
public class IndexModel : PageModel { private string host = ""; private string x_rapid_api_host = "microsoft-azure-translation-v1.p.rapidapi.com"; private string x_rapid_api_key = "<YOUR_RAPID_API_KEY>"; private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { string endpoint = "GetLanguagesForTranslate"; HttpResponse<string> response = Unirest.get(host + endpoint) .header("X-RapidAPI-Host", x_rapid_api_host) .header("X-RapidAPI-Key", x_rapid_api_key) .asJson<string>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(response.Body.ToString()); List<string> languages = new List<string>(); foreach(XmlNode node in doc.DocumentElement.ChildNodes){ languages.Add(node.InnerText); } ViewData["languages"] = languages; } public void OnPost(){ var from = Request.Form["from"]; var to = Request.Form["to"]; var text = Request.Form["text"]; Console.WriteLine("________" + from); string endpoint = "translate"; string fields = "?from=" + from + "&to=" + to + "&text=" + text; HttpResponse<string> response = Unirest.get(host + endpoint + fields) .header("X-RapidAPI-Host", x_rapid_api_host) .header("X-RapidAPI-Key", x_rapid_api_key) .header("Accept", "application/json") .asJson<string>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(response.Body.ToString()); ViewData["translation"] = doc.DocumentElement.FirstChild.InnerText; Console.WriteLine(doc.DocumentElement.FirstChild.InnerText); } }
Class PageModel is a base class for a simple view. Here we implement two basic requests via OnGet() and OnPost() respectively. Pay attention, that each handler works only in case of the correct HTTP method. If there will be a GET request (basic page opening), it should return the translation form. So we need to request all acceptable languages and save them into the ViewData dictionary – special connecting object between view and controller.
But if the request will be a POST (there are some text and languages), it should return translated text. So we need to request the translation and save it to the ViewData.
Now we need to add some handlers inside of the Index.cshtml:
@page @model IndexModel @{ ViewData["Title"] = "Home page"; } <div class="text-center"> <h1>Translator on C#</h1> <p>The time on the server is @DateTime.Now</p> @if (ViewData["translation"] != null){ <h4 style="color:red">@ViewData["translation"]</h4> <form action="/"> <input type="submit" value="Make more translations!" /> </form> } else { <form method="post"> <label>From:</label> <select id="from" name="from"> @foreach (var language in ViewData["languages"] as List<string>) { <option [email protected]> @language </option> } </select> <br> <label>To:</label> <select id="to" name="to"> @foreach (var language in ViewData["languages"] as List<string>) { <option [email protected]> @language </option> } </select> <br> <input type="text" name="text" placeholder="Input your text here" style="margin: .4rem 0" required="true"/> <br> <input type="submit" value="Translate!"> </form> } </div>
Basically, we have some conditions. If there is some value for the key Translation – it is the translation response. So we just represent it with a red color and ability to create a new conversion. But if there isn’t anything – we just show a translation form. Pay attention to the method parameter of the tag form. Here we point out that the results of the form should be sent by POST method, and (by default) in itself. Take a look at a @ operators – it’s the way to use some C# code inside of the markdown. This is how we add all language options in the drop-down box.
Now let’s test our application. Run it via console and open. | https://rapidapi.com/blog/how-to-use-an-api-with-c-sharp/ | CC-MAIN-2020-10 | en | refinedweb |
DOM.
See also the Document Object Model (DOM) Level 3 Core Specification.
Constant Summary
Field Summary
Public Constructor Summary
Inherited Method Summary
Constants
public static final short DOMSTRING_SIZE_ERR
If the specified range of text does not fit into a
DOMString.
public static final short HIERARCHY_REQUEST_ERR
If any
Node is inserted somewhere it doesn't belong.
public static final short INDEX_SIZE_ERR
If index or size is negative, or greater than the allowed value.
public static final short INUSE_ATTRIBUTE_ERR
If an attempt is made to add an attribute that is already in use elsewhere.
public static final short INVALID_ACCESS_ERR
If a parameter or an operation is not supported by the underlying object.
public static final short INVALID_CHARACTER_ERR
If an invalid or illegal character is specified, such as in an XML name.
public static final short INVALID_MODIFICATION_ERR
If an attempt is made to modify the type of the underlying object.
public static final short INVALID_STATE_ERR
If an attempt is made to use an object that is not, or is no longer, usable.
public static final short NAMESPACE_ERR
If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
public static final short NOT_FOUND_ERR
If an attempt is made to reference a
Node in a context
where it does not exist.
public static final short NOT_SUPPORTED_ERR
If the implementation does not support the requested type of object or operation.
public static final short NO_DATA_ALLOWED_ERR
If data is specified for a
Node which does not support
data.
public static final short NO_MODIFICATION_ALLOWED_ERR
If an attempt is made to modify an object where modifications are not allowed.
public static final short SYNTAX_ERR
If an invalid or illegal string is specified.
public static final short TYPE_MISMATCH_ERR
If the type of an object is incompatible with the expected type of the parameter associated to the object.
public static final short VALIDATION_ERR.
public static final short WRONG_DOCUMENT_ERR
If a
Node is used in a different document than the one
that created it (that doesn't support it). | https://developers.google.com/j2objc/javadoc/jre/reference/org/w3c/dom/DOMException?hl=es-419 | CC-MAIN-2020-10 | en | refinedweb |
Hi everyone,
I am currently working on a Python script that enables me to create multiple layouts out of bounding curves and zooms the detail to each one of them. For some reason, the script only fails for the 1st curve on the list, not zooming in correctly. If you test for 1 curve (by only puttting on curve on the selection layer) the error becomes apparent.
import rhinoscriptsyntax as rs import scriptcontext as sc import Rhino def AddLayout(): sc.doc.PageUnitSystem = Rhino.UnitSystem.Millimeters page_views = sc.doc.Views.GetPageViews() page_number = 1 if page_views: page_number = len(page_views) + 1 pageview = sc.doc.Views.AddPageView("A0_{0}".format(page_number), 34, 20) if pageview: top_left = Rhino.Geometry.Point2d(0,0) bottom_right = Rhino.Geometry.Point2d(34, 20) detail = pageview.AddDetailView("ModelView", top_left, bottom_right, Rhino.Display.DefinedViewportProjection.Top) pageview.SetPageAsActive() sc.doc.Views.ActiveView = pageview if detail: pageview.SetActiveDetail(detail.Id) detail.Viewport.ZoomBoundingBox(bounding_box) detail.DetailGeometry.SetScale(1, sc.doc.ModelUnitSystem, 1, sc.doc.PageUnitSystem) detail.DetailGeometry.IsProjectionLocked = True detail.CommitChanges() sc.doc.Views.Redraw() layer = rs.GetLayer("Select Layer", None, False) ids = rs.ObjectsByLayer(layer) for id in ids: bounding_box = rs.coerceboundingbox(rs.BoundingBox(id)) AddLayout()
This is the first layout (WRONG)
This is the second one and all that follow (RIGHT)
I leave my test file for anyone that wants to try. CatalogueExample04.3dm (163.5 KB) | https://discourse.mcneel.com/t/layout-zoomboundingbox-fails/81111 | CC-MAIN-2020-10 | en | refinedweb |
The country converter (coco) - a Python package for converting country names between different classifications schemes.
Project description
The country converter (coco) is a Python package to convert and match country names between different classifications and between different naming versions. Internally it uses regular expressions to match country names. Coco can also be used to build aggregation concordance matrices between different classification schemes.
Table of Contents
- Motivation
- Installation
- Usage
- Classification schemes
- Data sources and further reading
- Communication, issues, bugs and enhancements
- Contributing
- Related software
- Citing the country converter
- Acknowledgements
Motivation
To date, there is no single standard of how to name or specify individual countries in a (meta) data description. While some data sources follow ISO 3166, this standard defines a two and a three letter code in addition to a numerical classification. To further complicate the matter, instead of using one of the existing standards, many databases use unstandardised country names to classify countries.
The country converter (coco) automates the conversion from different standards and version of country names. Internally, coco is based on a table specifying the different ISO and UN standards per country together with the official name and a regular expression which aim to match all English versions of a specific country name. In addition, coco includes classification based on UN-, EU-, OECD-membership, UN regions specifications, continents and various MRIO databases (see Classification schemes below).
Installation
Country_converter is registered at PyPI. From the command line:
pip install country_converter --upgrade
To install from the Anaconda Cloud use:
conda install -c konstantinstadler country_converter
Alternatively, the source code is available on GitHub.
The package depends on Pandas; for testing py.test is required. For further information on running the tests see CONTRIBUTING.rst.
Usage
Basic usage
Use within Python
Convert various country names to some standard names:
import country_converter as coco some_names = ['United Rep. of Tanzania', 'DE', 'Cape Verde', '788', 'Burma', 'COG', 'Iran (Islamic Republic of)', 'Korea, Republic of', "Dem. People's Rep. of Korea"] standard_names = coco.convert(names=some_names, to='name_short') print(standard_names)
Which results in [‘Tanzania’, ‘Germany’, ‘Cabo Verde’, ‘Tunisia’, ‘Myanmar’, ‘Congo Republic’, ‘Iran’, ‘South Korea’, ‘North Korea’]. The input format is determined automatically, based on ISO two letter, ISO three letter, ISO numeric or regular expression matching. In case of any ambiguity, the source format can be specified with the parameter ‘src’.
In case of multiple conversion, better performance can be achieved by instantiating a single CountryConverter object for all conversions:
import country_converter as coco cc = coco.CountryConverter() some_names = ['United Rep. of Tanzania', 'Cape Verde', 'Burma', 'Iran (Islamic Republic of)', 'Korea, Republic of', "Dem. People's Rep. of Korea"] standard_names = cc.convert(names = some_names, to = 'name_short') UNmembership = cc.convert(names = some_names, to = 'UNmember') print(standard_names) print(UNmembership)
Convert between classification schemes:
iso3_codes = ['USA', 'VUT', 'TKL', 'AUT', 'XXX' ] iso2_codes = coco.convert(names=iso3_codes, to='ISO2') print(iso2_codes)
Which results in [‘US’, ‘VU’, ‘TK’, ‘AT’, ‘not found’]
The not found indication can be specified (e.g. not_found = ‘not there’), if None is passed for ‘not_found’, the original entry gets passed through:
iso2_codes = coco.convert(names=iso3_codes, to='ISO2', not_found=None) print(iso2_codes)
results in [‘US’, ‘VU’, ‘TK’, ‘AT’, ‘XXX’]
Internally the data is stored in a Pandas DataFrame, which can be accessed directly. For example, this can be used to filter countries for membership organisations (per year). Note: for this, an instance of CountryConverter is required.
import country_converter as coco cc = coco.CountryConverter() some_countries = ['Australia', 'Belgium', 'Brazil', 'Bulgaria', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'India', 'Indonesia', 'Ireland', 'Italy', 'Japan', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Romania', 'Russia', 'Turkey', 'United Kingdom', 'United States'] oecd_since_1995 = cc.data[(cc.data.OECD >= 1995) & cc.data.name_short.isin(some_countries)].name_short eu_until_1980 = cc.data[(cc.data.EU <= 1980) & cc.data.name_short.isin(some_countries)].name_short print(oecd_since_1995) print(eu_until_1980)
Some properties provide direct access to affiliations:
cc.EU28 cc.OECD cc.EU27as('ISO3')
and the classification schemes available:
cc.valid_class
The regular expressions can also be used to match any list of countries to any other. For example:
match_these = ['norway', 'united_states', 'china', 'taiwan'] master_list = ['USA', 'The Swedish Kingdom', 'Norway is a Kingdom too', 'Peoples Republic of China', 'Republic of China' ] matching_dict = coco.match(match_these, master_list)
See the IPython Notebook (country_converter_examples.ipynb) for more information.
Command line usage
The country converter package also provides a command line interface called coco.
Minimal example:
coco Cyprus DE Denmark Estonia 4 'United Kingdom' AUT
Converts the given names to ISO3 codes based on matching the input to ISO2, ISO3, ISOnumeric or regular expression matching. The list of names must be separated by spaces, country names consisting of multiple words must be put in quotes (‘’).
The input classification can be specified with ‘–src’ or ‘-s’ (or will be determined automatically), the target classification with ‘–to’ or ‘-t’.
The default output is a space separated list, this can be changed by passing a separator by ‘–output_sep’ or ‘-o’ (e.g -o ‘|’).
Thus, to convert from ISO3 to UN number codes and receive the output as comma separated list use:
coco AUT DEU VAT AUS -s ISO3 -t UNcode -o ', '
The command line tool also allows to specify the output for none found entries, including passing them through to the output by passing None:
coco CAN Peru US Mexico Venezuela UK Arendelle --not_found=None
and to specifiy an additional data file which will overwrite existing country matchings
coco Congo --additional_data path/to/datafile.csv
See for an example of an additional datafile.
For further information call the help by
coco -h
Use in Matlab
Newer (tested in 2016a) versions of Matlab allow to directly call Python functions and libaries. This requires a Python version >= 3.4 installed in the sytem path (e.g. through Anaconda).
To test, try this in Matlab:
py.print(py.sys.version)
If this works, you can also use coco after installing it through pip (at the windows commandline - see the installing instruction above):
pip install country_converter --upgrade
And in matlab:
coco = py.country_converter.CountryConverter() countries = {'The Swedish Kingdom', 'Norway is a Kingdom too', 'Peoples Republic of China', 'Republic of China'}; ISO2_pythontype = coco.convert(countries, pyargs('to', 'ISO2')); ISO2_cellarray = cellfun(@char,cell(ISO2_pythontype),'UniformOutput',false);
Alternativley, as a long oneliner:
short_names = cellfun(@char, cell(py.country_converter.convert({56, 276}, pyargs('src', 'UNcode', 'to', 'name_short'))), 'UniformOutput',false);
All properties of coco as explained above are also available in Matlab:
coco = py.country_converter.CountryConverter(); coco.EU27 EU27ISO3 = coco.EU27as('ISO3');
These functions return a Pandas DataFrame. The underlying values can be access with .values (e.g.
EU27ISO3.values
I leave it to professional Matlab users to figure out how to further process them.
See also IPython Notebook (country_converter_examples.ipynb) for more information - all functions available in Python (for example passing additional data files, specifying the output in case of missing data) work also in Matlab by passing arguments through the pyargs function.
Building concordances for country aggregation
Coco provides a function for building concordance vectors, matrices and dictionaries between different classifications. This can be used in python as well as in matlab. For furter information see (country_converter_aggregation_helper.ipynb)
Classification schemes
Currently the following classification schemes are available (see also Data sources below for further information):
- ISO2 (ISO 3166-1 alpha-2)
- ISO3 (ISO 3166-1 alpha-3)
- ISO - numeric (ISO 3166-1 numeric)
- UN numeric code (M.49 - follows to a large extend ISO-numeric)
- A standard or short name
- The “official” name
- Continent
- UN region
- EXIOBASE 1 classification
- EXIOBASE 2 classification
- EXIOBASE 2 classification
- WIOD classification
- Eora
- OECD membership (per year)
- UN membership (per year)
- EU membership (per year)
- Cecilia 2050 classification
Coco contains offical recognised codes as well as non-standard codes for disputed or dissolved countries. To restrict the set to only the official recognized UN members or include obsolete countries, pass
import country_converter as coco cc = coco.CountryConverter() cc_UN = coco.CountryConverter(only_UNmember=True) cc_all = coco.CountryConverter(include_obsolete=True) cc.convert(['PSE', 'XKX', 'EAZ', 'FRA'], to='name_short') cc_UN.convert(['PSE', 'XKX', 'EAZ', 'FRA'], to='name_short') cc_all.convert(['PSE', 'XKX', 'EAZ', 'FRA'], to='name_short')
cc results in [‘Palestine’, ‘Kosovo’, ‘not found’, ‘France’], whereas cc_UN converts to [‘not found’, ‘not found’, ‘not found’, ‘France’] and cc_all converts to [‘Palestine’, ‘Kosovo’, ‘Zanzibar’, ‘France’] Note that the underlying dataframe is available at the attribute .data (e.g. cc_all.data).
Data sources and further reading
Most of the underlying data can be found in Wikipedia. is a good starting point. UN regions/codes are given on the United Nation Statistical Division (unstats) webpage. For the differences between the ISO numeric and UN (M.49) codes see. EXIOBASE, WIOD and Eora classification were extracted from the respective databases. For Eora, the names are based on the ‘Country names’ csv file provided on the webpage, but updated for different names used in the Eora26 database. The membership of OECD, UN and EU can be found at the membership organisations’ webpages, informatio about obsolete country codes on the Statoids webpage.
Communication, issues, bugs and enhancements
Please use the issue tracker for documenting bugs, proposing enhancements and all other communication related to coco.
You can follow me on twitter to get the latest news about all my open-source and research projects (and occasionally some random retweets).
Contributing
Want to contribute? Great! Please check CONTRIBUTING.rst if you want to help to improve coco.
Citing the country converter
Version 0.5 of the country converter was published in the Journal of Open Source Software. To cite the country converter in publication please use:
Stadler, K. (2017). The country converter coco - a Python package for converting country names between different classification schemes. The Journal of Open Source Software. doi:
For the full bibtex key see CITATION
Acknowledgements
This package was inspired by (and the regular expression are mostly based on) the R-package countrycode by Vincent Arel-Bundock and his (defunct) port to Python (pycountrycode). Many thanks to Robert Gieseke for the review of the source code and paper for the publication in the Journal of Open Source Software.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/country-converter/0.6.6/ | CC-MAIN-2020-10 | en | refinedweb |
Automatic topsis for decision making
Project description
TOPSIS implementation
Class project for DATA ANALYSIS AND VISUALISATION 2020 - UCS633 Thapar University, Patiala Submitted by: Paras Arora 101703382 (COE 18)
Output is a dataframe with 3 columns
- Alternatives
- Score
- Rank
Installation
pip install topsis-101703382
To use via command line
topsis-101703382-cli data.csv 25,25,25,25 -+++
First argument after run.py is filename with .csv extension. The .csv file is assumed to have a structure similar to one provided in topsis-101703382/data.csv
That is, the .csv file should have a header with column names and first column should only list alternatives and not attribute values.
To use in .py script
from topsis-101703382 import topsis """ decision_matrix is 2D numpy array, weights is a 1D array and impacts is a string of the form +-+-- where + implies benefit and - implies cost """ output_dataframe = topsis(decision_matrix,weights,impacts)
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/topsis-101703382/ | CC-MAIN-2020-10 | en | refinedweb |
In this post, post, we are going to create a simple chat application using Angular 8, ASP.NET Core and SignalR
In this post, we are going to create a simple chat application using Angular 8, ASP.NET Core 2.2.0, and SignalR 1.1.0 as shown below.
We need to install all the below-mentioned prerequisites on our development machine.
Prerequisite
Open the command prompt and enter the following command to create an ASP.NET Core web project as below.
Install the following NuGet package in your project.
Call SignalR in the “Startup.ConfigureServices” method to add SignalR services.
services.AddSignalR();Create MessageHub Class
SignalR makes real-time client-to-server and server-to-client communications possible and it will call methods to connect clients from a server using SignalR Hub API. You can find more details about SignalR from here. Now, we need to perform the following steps to create the MessageHub class that is extending SignalR Hub API features.
using ChatApp.Models; using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace ChatApp.Hubs { public class MessageHub : Hub { public async Task NewMessage(Message msg) { await Clients.All.SendAsync("MessageReceived", msg); } } }
Then, add route to handle a request in Startup.ConfigureService method for MessageHub.
app.UseSignalR(options => { options.MapHub<MessageHub>("/MessageHub"); });
Add a Message Class
Add Angular 8 into the projectAdd Angular 8 into the project
public class Message { public string clientuniqueid { get; set; } public string type { get; set; } public string message { get; set; } public DateTime date { get; set; } }
We will scaffold Angular into our project. For this, we need to execute “ng new ClientApp --skip-install” on Visual Studio Code terminal. Here, --skip-install option is used to skip installation of the npm packages.
Now, let us enter the “npm install” command to install all Angular npm packages in the terminal. And then, update the SPA static file service configuration to the Angular output files folder location. For this, we will add the below code to the “Startup.Configure” method.
app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { //spa.UseProxyToSpaDevelopmentServer(""); spa.UseAngularCliServer(npmScript: "start"); } });
Here, UseAngularCliServer will pass the request through to an instance of Angular CLI server which keeps up-to-date CLI-built resources without having to run the Angular CLI server manually.
Now, add SignalR client library to connect MessageHub from the Angular as below screenshot.Create Chat Service to connect SignalR
Create chat.service.ts class to establish a connection with Message Hub and to publish & receive chat messages.
Then, we have added chat service as a provider in Ng Modules.
Create a Chat App ComponentCreate a Chat App Component
import { EventEmitter, Injectable } from '@angular/core'; import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr'; import { Message } from '../models/message'; @Injectable() export class ChatService { messageReceived = new EventEmitter<Message>(); connectionEstablished = new EventEmitter<Boolean>(); private connectionIsEstablished = false; private _hubConnection: HubConnection; constructor() { this.createConnection(); this.registerOnServerEvents(); this.startConnection(); } sendMessage(message: Message) { this._hubConnection.invoke('NewMessage', message); } private createConnection() { this._hubConnection = new HubConnectionBuilder() .withUrl(window.location.href + 'MessageHub') .build(); } private startConnection(): void { this._hubConnection .start() .then(() => { this.connectionIsEstablished = true; console.log('Hub connection started'); this.connectionEstablished.emit(true); }) .catch(err => { console.log('Error while establishing connection, retrying...'); setTimeout(function () { this.startConnection(); }, 5000); }); } private registerOnServerEvents(): void { this._hubConnection.on('MessageReceived', (data: any) => { this.messageReceived.emit(data); }); } }
app.component.html:
<div class="container"> <h3 class=" text-center chat_header">Chat Application</h3> <div class="messaging"> <div class="inbox_msg"> <div class="mesgs"> <div class="msg_history"> <div * <div class="incoming_msg" * <div class="incoming_msg_img"> </div> <div class="received_msg"> <div class="received_withd_msg"> <p> {{msg.message}} </p> <span class="time_date"> {{msg.date | date:'medium'}} </span> </div> </div> </div> <div class="outgoing_msg" * <div class="sent_msg"> <p> {{msg.message}} </p> <span class="time_date"> {{msg.date | date:'medium'}}</span> </div> </div> </div> </div> <div class="type_msg"> <div class="input_msg_write"> <input type="text" class="write_msg" [value]="txtMessage" (input)="txtMessage=$event.target.value" (keydown.enter)="sendMessage()" placeholder="Type a message" /> <button class="msg_send_btn" type="button" (click)="sendMessage()"><i class="fa fa-paper-plane-o" aria-</i></button> </div> </div> </div> </div> </div> </div>
app.component.ts :
import { Component, NgZone } from '@angular/core'; import { Message } from '../models/Message'; import { ChatService } from '../services/chat.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'ClientApp'; txtMessage: string = ''; uniqueID: string = new Date().getTime().toString(); messages = new Array<Message>(); message = new Message(); constructor( private chatService: ChatService, private _ngZone: NgZone ) { this.subscribeToEvents(); } sendMessage(): void { if (this.txtMessage) { this.message = new Message(); this.message.clientuniqueid = this.uniqueID; this.message.type = "sent"; this.message.message = this.txtMessage; this.message.date = new Date(); this.messages.push(this.message); this.chatService.sendMessage(this.message); this.txtMessage = ''; } } private subscribeToEvents(): void { this.chatService.messageReceived.subscribe((message: Message) => { this._ngZone.run(() => { if (message.clientuniqueid !== this.uniqueID) { message.type = "received"; this.messages.push(message); } }); }); } }
Now, our chat application is ready. Let's run the following command in terminal and test apps.
SummarySummary
dotnet run
In this article, we have learned how we can create a sample chat app using Angular 8 and ASP.NET Core with SignalR.
Please find the entire source code here as an attachment and also on GitHub.
Thanks!.Get Started with ASP.NET MVC.Create an Angular Project:Set up a Database for ASP.NET:
Add Authentication to Your Angular ApplicationAdd Authentication to Your Angular Application:
Set Up Your ASP.NET API EndpointsSet Up Your ASP.NET API Endpoints
.Set a Default Formatter for ASP.NET Web API 2 Up the Angular Application for ASP.NET MVC.Create a Model and API Service for Your Angular Application:
Fetch Data from the ASP.NET API EndpointFetch Data from the ASP.NET API Endpoint):
Test Out Your ASP.NET and Angular ApplicationTest Out Your ASP.NET and Angular Application
:Learn More | https://morioh.com/p/ba45ee4cb717 | CC-MAIN-2020-10 | en | refinedweb |
This is a document with tips and usage details about Jython that I've come across. I intend to document handy features of Python as well as some clever inter-op facilities provided by Jython.
I'm going to assume you're not a complete beginner to Java and Python languages. If you find anything off or have a suggestion to add, please do write to me. Thanks!
Logging and Printing¶
When using Apache's log4j, we can get an instance of a
Logger using the API just as we would in
Java:
>>> from org.apache.log4j import Logger >>> log = Logger.getLogger('jython_script')
When getting a
Logger instance for a module that is imported, a logger with a category specific to
that module can be obtained using the following code:
log = Logger.getLogger(__name__)
The
__name__ name is a variable containing the current module's name as a string. Note that
__name__ is set to the string
'__main__' if the module is run as a script and not imported from
another script. This should be kept in mind when using the above code.
The standard printing functions of Java can be imported into Python and used directly in the following way:
>>> from java.lang import System >>> System.out.println('Hola') Hola >>> System.err.println('Hello there') Hello there >>> System.out.print('Hola\n') Hola
However, it's usually more convenient to use Python's
print 'Hello world!'
Here's a table illustrating the
print* functions:
Bean Properties¶
Jython can implicitly call the
.get* and
.set* methods that are widely used in Java classes to
get and set the values of instance attributes. Here's an illustration of how this inter-op works:
Of course, when such
.get* and
.set* methods are not available, this falls back gracefully to
trying get/set the property values directly, just as Java would treat those statements.
Strings¶
Strings in Java (i.e., objects of type
java.lang.String) are converted to
unicode objects when
passed in to Python world. Whereas
str and
unicode objects in Python are converted to
java.lang.String instances when passed in to Java world. This conversion is seamless and we
usually don't have to worry about it.
However, if needed, we can explicitly create an instance of
java.lang.String from a
unicode
object in Python:
>>> from java.lang import String >>> greeting = String('Hello') >>> greeting Hello >>> type(greeting) <type 'java.lang.String'>
String formatting using
% operator in Python cannot be applied to Java
String objects. They have
to converted to
str or
unicode first.
Maps as Dictionaries¶
For the purposes of the following examples, let's work with the following
Map:
java.util.Map<String, Integer> data = new java.util.HashMap<>(); data.put("a", 1); data.put("b", 2); data.put("c", 3);
Maps support the getitem syntax very well so it is usually convenient to think of them as
python-style dictionaries. Here's an example:
>>> print data['a'] # data.get("a") 1 >>> print data['b'] # data.get("b") 2 >>> data['d'] = 4 # data.put("d", 4) >>> data['d'] # data.get("d") 4 >>> len(data) # data.size() 4 >>> 'c' in data # data.containsKey("c") True >>> del data['c'] # data.remove("c") >>> 'c' in data # data.containsKey("c") False >>> data {a=1, b=2, d=4} >>> len(data) # data.size() 3
Although this resembles the usage of a traditional python dictionary, the methods you'd expect in a
dictionary are not all available. This is a
Map object after all and it has the methods of the
Map class. However, it is easy to get see the parallels among some of the most used methods.
The
dict builtin can be called on the
Map object to get a python-style dictionary, if needed.
Additionally, just like a python dictionary, calling
list (or
set) on the
Map object gives a
list (or
set) of the keys in the
Map.
Using
for loops to iterate over
Maps yields the keys in the
Map, which is consistent with how
for loops work with python dictionaries.
for key in data: print key, data[key]
Prints the following:
a 1 b 2 d 4
In python, the
.items method returns each entry as a
tuple which lets us write the for loop like
the following:
# !!! Only works if `data` is a python-style dictionary, not if it is a `Map`. for key, value in data.items(): print key, value
But unfortunately, since
Map doesn't have the
.items method, this is not possible. However, we
can use the
.entrySet method to construct something slightly similar.
for entry in data.entrySet(): print entry.key, entry.value
To iterate over the values of a
Map, since the method is called
.values in both
dict and
Map, the same piece of code would work with any object.
for value in data.values(): print value
Empty
Map objects are treated as
False in boolean contexts, just as with python's dictionaries.
Collections¶
The two main collection types in Python are
list and
set. The equivalents in java are the
interfaces
List and
Set. Let's prepare some data for
our examples.
java.util.List<String> planets = new java.util.ArrayList<>(); planets.add("Mercury"); planets.add("Venus"); planets.add("Earth"); java.util.Set<String> colors = new java.util.HashSet<>(); colors.add("White"); colors.add("Black"); colors.add("Red"); colors.add("Green"); colors.add("Blue");
The getitem syntax can be used with
Lists seamlessly:
>>> planets[0] u'Mercury' >>> planets[1] u'Venus'
The slicing syntax, returns
Lists of the same type, not python-style
lists.
>>> planets[:2] [Mercury, Venus] >>> type(_) # `_` is a variable set to the return value of last expression. <type 'java.util.ArrayList'> >>> planets[::-1] [Earth, Venus, Mercury] >>> type(_) <type 'java.util.ArrayList'>
However, the getitem syntax is not supported for
Sets as it doesn't make sense there since
Sets are unordered collections. But the operator support available for
sets in python are
available with Java
Set objects as well.
>>> 'Red' in colors True >>> len(colors) 5
The
for loop can be used on any
Collection type objects to
iterate over the object's contents.
>>> for x in planets: ... print x ... Mercury Venus Earth >>> for x in enumerate(planets): ... print x ... (0, u'Mercury') (1, u'Venus') (2, u'Earth')
Here's equivalents for some of the methods available in Java's
Collections and Python's collection
types.
Empty
Collections are treated as
False in boolean contexts, just as with python's collections.
Java Arrays¶
Just as Java's
List is mirrored in Python with
list, Java's arrays are mirrored using the array
structure available in Jython's
array module.
That official documentation is quite exhaustive on this topic, so I suggest going over it to get an
idea of handling arrays in Jython.
The Iteration Protocol¶
Java's
Iterator style
iteration is supported by Jython's
for statements. For example, consider the following Java
Iterator that's trying to emulate a small fraction of Python's
range function:
package ssk.experiments; import java.util.Iterator; public class RangeIterator implements Iterator<Integer> { private Integer current = 0, max; public RangeIterator(int max) { this.max = max; } @Override public boolean hasNext() { return current < max; } @Override public Integer next() { return current++; } }
Since classes are instantiated without a
new keyword in Python, combined with the fact that
Jython's
for statement supports Java's
Iterators, we can use the above in the following way:
from ssk.experiments import RangeIterator for n in RangeIterator(5): print n
This gives the following output:
0 1 2 3 4
Since Jython's
for statement supports iterating over Java's
Enumeration type, the
above same
for loop would work with a
RangeEnumeration class as defined below:
package ssk.experiments; import java.util.Enumeration; public class RangeEnumeration implements Enumeration<Integer> { private Integer current = 0, max; public RangeEnumeration(int max) { this.max = max; } @Override public boolean hasMoreElements() { return current < max; } @Override public Integer nextElement() { return current++; } }
Jython seamlessly handles the getting of an instance of an
Iterator from a Java
Iterable. This is actually
how the
for statement works with the
List and
Set collections discussed earlier (
Collection
is a sub-interface of
Iterable).
Patching Java Classes¶
In Python, new methods and attributes can be added to existing classes. This comes from the dynamic nature of the programming language and the runtime. The JVM is also a dynamic runtime, but the Java language doesn't allow us to modify existing classes. This is where Jython comes in. Jython lets us add and override methods on existing Java classes. Although this is seldom needed, this can illustrate the extent of Jython's integration with the JVM.
Here's a Java class:
package ssk.experiments; import java.util.List; public class Country { private String name; public Country(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
There's nothing fancy with the above class. It's a regular class with one property with a
.get and
.set methods. Now, let's add a new method to this class.
from ssk.experiments import Country def upcase(self): self.name = self.name.upper() Country.upcase = upcase # Create a `Country` object and call `upper_name` method. largest_country = Country('Russia') largest_country.upcase() print largest_country.name
This would print
RUSSIA, as expected.
Note that this is an advanced feature and should be used with caution. In almost all cases, it is probably a better idea to modify the original Java class definition directly. But when that is not an option, creating a simple Python function that works with these objects should be considered. Modifying existing classes should only be used as a last resort.
Operator Overloading¶
One nice and practical case for adding methods on existing Java classes is to leverage Python's
support for operator overloading with Java classes. One good example for this is with the
BigDecimal class. Mathematical operations on objects of
BigDecimal are provided as individual
methods like
.add,
.subtract etc. We can add operator support (in Jython) for these objects
by adding the appropriate methods to the
BigDecimal class.
For instance, here's how we can add support for the
+ operator:
from java.math import BigDecimal BigDecimal.__add__ = lambda self, other: self.add(other) print BigDecimal(42) + BigDecimal(10)
This would print
52, as expected. More methods can be added to support all the mathematical
operators such as
__sub__ for subtraction and
__mul__ for multiplication etc. The full list of
such method names can be found on the official data model documentation
page.
Conclusion¶
This is not intended to be an exhaustive guide to what Jython can do. I hoped to give you a taste of how well Jython handles inter-op with Java and hopefully I've helped you write better Python - Java inter-op code. Thank you and any suggestions and feedback are very welcome.
View comments at | https://sharats.me/posts/jython-pillow-guide/ | CC-MAIN-2020-10 | en | refinedweb |
I got this effect from a very good French Flasher. I found
the code on his site,
flasheur.com , broke it down, and improved it a little
bit, all this just for you.
You'll find that in this tutorial, I also took the code from
the
Random motion tutorial, that I use the
swapDepths and duplication functions, and a lot of
actionscript-based motion.
So that's not an easy tutorial, and you'd better check the
other tutorials before attempting this one.
Take a
look at the effect:
[ see the bacteria melt? ]
You can grab an incomplete source to get you started by
clicking here.
Now, what we want is that the bacteria move randomly. We
need to put Supra's random motion code to the circle, and
make so that the outline follows somehow the fill.
We also need to duplicate our bacterium, so that there are
more than one on the scene
Create a new layer that you'll name code and add this
code:
//Random Movement: kirupa.com
//Thanks to Suprabeener for the original code!
function getdistance (x, y, x1, y1) {
var run, rise;
run = x1-x;
rise = y1-y;
return (hyp(run, rise));
}
function hyp (a, b) {
return (Math.sqrt(a*a+b*b));
}
MovieClip.prototype.reset = function () {
var dist, norm, movie_height, movie_width;
// movie_height: refers to the height of your movie
// movie_width: refers to the width of your movie
//---------------------------------
movie_height = 200;
movie_width = 400;
//---------------------------------
speed = Math.random()*4+2;
targx = Math.random()*(movie_width-_width);
targy = Math.random()*(movie_height-_height);
dist = _root.getdistance(_x, _y, targx, targy);
};
MovieClip.prototype.move = function () {
var cycle;
// cycle: specifies speed of the movement. The smaller
// number, the faster the objects move.
//--------------------------------------------
cycle = 200;
//--------------------------------------------
diffx = (targx-_x);
diffy = (targy-_y);
if (_root.getdistance(_x, _y, targx, targy)>speed) {
x += diffx/7;
y += diffy/7;
} else {
if (!this.t) {
t = getTimer();
}if (getTimer()-t>cycle) {
reset();
t = 0;
}
}
_x = x;
_y = y;
}
If you look very closely, you'll see that I removed two
or three lines from the move() and
reset function.
onClipEvent (enterFrame) {
move () ;
}
onClipEvent (enterFrame) {
_root.shadow._x = _root.circle._x;
_root.shadow._y = _root.circle._y;
// this makes the outline follow the fill
}
We get to the real actionscript part of the effect. We want
to duplicate our little bacteria, and make them all move,
and also make it so that it looks like they melt one into
each other.
In the code layer, under the random motion code, we are
going to put the duplication code.
// 1 : first level
i = 1;
// MAX : number of bacteria. Don't put too much, or you're going to kill your computer
MAX = 11 ;
// duplication loop. We could have used a for loop too.
do {
duplicateMovieClip (_root.circle, "circle"+i, 50+i);
duplicateMovieClip (_root.shadow, "shadow"+i, i);
_root["circle"+i].num = i ;
_root["shadow"+i].num = i ;
i++ ;
} while (i<MAX);
_root.circle._visible = 0 ;
_root.top.swapDepths(1000) ;
Everybody OK? I admit this isn't
really simple.
duplicateMovieClip (_root.circle, "circle"+i,
50+i);
This means you duplicate the movie
_root.circle
under the name "circle"+i in level
50+i.
At the beginning, i=1, so the name
of the duplicate will be circle1 and it will lay on
level 51. Logical. And so on and so forth 11 times
because of the do... while loop.
onClipEvent (enterFrame) {
i = 1;
do {
_root["shadow"+i]._x = _root["circle"+i]._x;
_root["shadow"+i]._y = _root["circle"+i]._y;
i++;
} while (i<_root.MAX);
}
That's it ! Finished ! Save your
work, and test the movie.
That last bit of code looks a lot like the one we first put
in the controller. The difference is that we loop so
that all the shadows follow their circle, and
that we have to give a general formula of the path to get to
the shadows and the circles. I like those NOTE things...
This
tutorial is written by Ilyas Usal. Ilyas is also known as
ilyaslamasse
on the
kirupa.com forums!
pom
Flash Transition Effects
Flash Effect Tutorials
Link
to Us
© 1999 - 2009 | http://www.kirupa.com/developer/actionscript/outline.htm | crawl-002 | en | refinedweb |
By: Oleg Zhukov
Abstract: The article explains how to implement the Command pattern in CodeGear ECO applications, making use of ECO Undo/Redo facilities
Implementing the Command pattern in ECO applications
The idea of turning operations into objects had great influence upon the software development methods. Expressed in the Command pattern this idea finds its application in many modern object-oriented systems. In this article we are going to demonstrate the Command pattern in action empowered by CodeGear ECO undo/redo facilities. Before we proceed to the implementation aspects of the Command pattern let us start by discussing the motivation for its usage.
Imagine an application that has items in the main menu to add/remove objects (actually there are many such applications). However the response to a menu item click cannot be hard-coded, since the reaction should depend on the current context. For example “Add” item may create either a new company object or a new department depending on what list is selected in the user interface. A good solution is to have an abstract Command class with AddCompanyCommand and AddDepartmentCommand subclasses, both overriding the Do() operation. “Add” menu item then just invokes addCommand.do() without any knowledge about the concrete command class.
Hide image
This shows how representing an operation with an object detaches the operation client (menu item) from the actual operation implementation, adding flexibility and allowing us to easily extend the system with new operations (command classes).
Another advantage of command objects over simple methods is that a method can only be executed, whereas a command may contain other than Do() methods for example Undo()/Redo() or Validate() methods. More generally the Command pattern makes operations live, each with its own lifecycle.
And although implementing the Command pattern with the undo/redo functionality always seemed to be a complicated task we will show how easy it can be with ECO framework. So let us start with creating basic command functionality and then we will extend it with undo/redo capabilities.
Create a new ECO WinForms application with the domain ECO model as follows:
Then create a simple GUI with a menu bar and two grids displaying companies and corresponding departments.
Now we are ready to introduce command classes. First create a Command abstract base class. It should hold a protected reference to the used ECO space instance, passed as a constructor parameter. It should also declare an abstract Do() operation. It is handy to design classes (not ECO, just plain classes) via the Together diagram editor. This is how the command class looks in the Together designer:
public Command( MyEcoSpace es ) {
this.es = es;
}
Commands for adding companies and departments will be concrete subclasses of the Command class. Each one will have its own constructor and Do() operation implementation.
public AddCompanyCommand( MyEcoSpace es ) : base(es) {}
public override void Do( ) {
new Company(es);
}
public AddDepartmentCommand( MyEcoSpace es, Company c ) : base(es) {
this.company = c;
}
public override void Do( ) {
Department d = new Department(es);
d.Company = company;
}
Next step is to link commands to the user interface. For this we define an addCommand property in the main form. This property should return an appropriate command object depending on which grid is focused: AddCompanyCommand if companies grid is selected, AddDepartmentCommand if departments grid is selected:
private Command addCommand {
get {
if (dgCompanies.ContainsFocus)
return new AddCompanyCommand(EcoSpace);
else if (dgDepartments.ContainsFocus)
return new AddDepartmentCommand(EcoSpace,
(Company)CurrencyManagerHandle.CurrentElement(dgCompanies).AsObject);
else return null;
}
}
The last thing here is to invoke the current add command. Just add the following handler for the “Add” menu item click:
private void addItem_Click(object sender, System.EventArgs e)
{
addCommand.Do();
}
What our implementation lacks at the moment is the feedback from commands to the user interface. For example the UI might set focus to added objects in a grid whenever it receives notifications from command objects. In order to add notifications support let us associate the Command class with ICommandListener interface. A listener instance should be passed to a command through the constructor. Another two public fields will hold the information about the command execution context: processedIObject:IObject will reference the object affected by the command, context:object will describe the context UI control, grid for example. The UI will use this context information to set cursor to the proper row in the proper gird.
public interface ICommandListener {
void update( Command c );
}
public Command( MyEcoSpace es, ICommandListener listener, object context) {
this.es = es;
this.listener = listener;
this.context = context;
}
Then make changes to both Command subclasses. Modify their constructors and Do() methods to make them assign processedIObject and send notifications to a listener. The code below illustrates the changes made to AddCompanyCommand class (for AddDepartmentCommand they are similar).
public AddCompanyCommand(MyEcoSpace es, ICommandListener listener, object context)
: base(es, listener, context) {}
public override void Do( ) {
Company c = new Company(es);
processedIObject = c.AsIObject();
listener.update(this);
}
The main form then should implement the ICommandListener interface and pass itself as a listener to the created commands. Data grids will serve as context for command objects.
// public class WinForm
private Command addCommand {
get {
if (dgCompanies.ContainsFocus)
return new AddCompanyCommand(EcoSpace, this, dgCompanies);
…
}
}
// public class WinForm
public void update(Command c) {
DataGrid contextGrid = (DataGrid)c.context;
ElementHandle contextHandle = contextGrid.DataSource as ElementHandle;
IObjectList contextList = (IObjectList)contextHandle.Element;
contextHandle.EnsureBindingList();
int newRowIndex = contextList.IndexOf(c.processedIObject);
contextGrid.CurrentCell = new DataGridCell(newRowIndex, 0);
}
Now the interface reflects changes done by commands setting cursor to added objects. The last thing remaining is to add Undo/Redo support.
Fortunately ECO allows caching all changes done to ECO objects in so called undo blocks. You may start such undo block then make some modifications to objects and then undo all these changes. This is possible because ECO keeps track of all modifications in the currently started undo block. Altogether undo blocks form two lists: one for done blocks (undo list), the other for undone ones (redo list). As soon as a block gets undone it is moved to the redo list and hence can be redone. All actions upon undo blocks in ECO are performed through the ECO Undo service. For example this shows how to start an undo block and get access to it:
EcoSpace.UndoService.StartUndoBlock();
IUndoBlock block = EcoSpace.UndoService.UndoList.TopBlock;
So how is it possible to undo/redo changes done by command objects? According to said above we may associate each command instance with its own undo block. Then the changes done by a command will be cached inside the associated undo block.
Now it is possible to undo/redo a command, but how do we know which command is the latest, which one goes before it and etc.? In order to maintain done (and undone) commands sequence there should be a class which will hold all previously done commands. Let us call it CommandsManager. It should reference two lists: one for done commands (undo list), the other for undone ones (redo list). Let us also make the CommandsManager responsible for dealing with the ECO undo service. Thus command instances will ask the CommandsManager to start undo block and to undo/redo them. To make the CommandsManager object unique and accessible from any point we will implement it as a Singleton.
public class CommandsManager {
public static readonly CommandsManager instance = new CommandsManager();
public MyEcoSpace es;
public ArrayList doneCommands = new ArrayList();
public ArrayList undoneCommands = new ArrayList();
public void start( Command c ) {
es.UndoService.StartUndoBlock();
c.uBlock = es.UndoService.UndoList.TopBlock;
undoneCommands.Clear();
doneCommands.Add(c);
}
public void undo( Command c ) {
es.UndoService.UndoBlock(c.uBlock.Name);
undoneCommands.Add(c);
doneCommands.Remove(c);
}
public void redo( Command c ) {
es.UndoService.RedoBlock(c.uBlock.Name);
doneCommands.Add(c);
undoneCommands.Remove(c);
}
}
Do not forget to link the CommandsManager to the used ECO space. This can be done in the main form constructor:
public WinForm() {
…
CommandsManager.instance.es = EcoSpace;
}
As we said above each command instance should hold the corresponding undo block. It should also make requests to the CommandsManager where necessary.
public abstract class Command {
…
public IUndoBlock uBlock;
…
public void Do() {
CommandsManager.instance.start(this);
doActions();
listener.update(this);
}
public void Undo() {
CommandsManager.instance.undo(this);
listener.update(this);
}
public void Redo() {
CommandsManager.instance.redo(this);
listener.update(this);
}
protected abstract void doActions();
}
Here we made use of the Template method pattern by defining Do() as a template with an abstract doActions() operation inside. Thus Command subclasses should only override the doActions() method. This is how it looks for the AddCompanyClass:
// public class AddCompanyClass
protected override void doActions( ) {
Company c = new Company(es);
processedIObject = c.AsIObject();
}
Now it is time to make changes to the user interface. Add “Undo” and “Redo” items to the main menu. Then create handlers for the corresponding item click events:
// public class WinForm
private void undoItem_Click(object sender, System.EventArgs e)
{
ArrayList doneCommands = CommandsManager.instance.doneCommands;
(doneCommands[doneCommands.Count - 1] as Command).Undo();
}
private void redoItem_Click(object sender, System.EventArgs e)
{
ArrayList undoneCommands = CommandsManager.instance.undoneCommands;
(undoneCommands[undoneCommands.Count - 1] as Command).Redo();
}
Another useful modification is to enable/disable “Undo” and “Redo” items depending on whether undo and redo lists are empty.
// public class WinForm
public void update(Command c) {
…
undoItem.Enabled = CommandsManager.instance.doneCommands.Count > 0;
redoItem.Enabled = CommandsManager.instance.undoneCommands.Count > 0;
}
This is how our application finally looks:
The article concerns the usage of the Command pattern in CodeGear ECO applications. One of the Command pattern features that is typically difficult to implement is the Undo/Redo functionality. However the power of ECO makes it quite a simple task and allows developers to construct more flexible and usable object-oriented solutions.
The full source code of the example can be downloaded from CodeGear CodeCentral portal. Here is link to it:. Also visit the author’s website.
Server Response from: SC4 | http://edn.embarcadero.com/article/36514 | crawl-002 | en | refinedweb |
Windows Live Hotmail, a completely rebuilt web based mail client set to replace MSN Hotmail, started its rollout to selected markets this week. This morning, I talked on the phone with two members of the Windows Live Hotmail team from their offices in Mountain View, California. Omar Shahine and Ellie Powers-Boyle have been working on "Kahuna" since 2004, and we talked about the code base, the beta, performance, and more.
Download and listen to the 10mb .mp3
Omar mentions 'MSN Calendar'. I wonder if that is an indication of the branding of the calendar. It would be a shame if it was.
That is too big for me to download (I'm on dial-up cos of my mum).
Can somebody please tell me what they said about "@live.com" email addresses?
foaf: I would be very surprised if it was branded MSN Calendar. I can't see any way in which they could justify that.
calum-r-: to paraphrase Omar, he said "short term concerns are around taking our existing user base and making sure they have a smooth transition. after that, will move onto things like the @live.com namespace." hope that was useful ;)
Hmm... there keeping quiet about the Calendar... I'm guessing they must have something in the works and it seems like it might be pretty big since they where so hush, hush about it.
I'm keeping my fingers crossed.
The fine folks over at the LiveSide blog had the chance to interview Omar Shahine and Ellie Powers-Boyle...
calum-r-
Yeah didn't mean to keep you in suspense but there wasn't much news to report. The @live.com addresses are coming but no set timetable as of yet.
And as for Omar's "MSN Calendar" reference, remember he kept calling it Kahuna the whole time, too. Sometimes I think that the code names and name changes are harder for 'Softies to keep straight than they are for us.
Thanks for the interview, good work! It's good that they will talk to people about their products!
I'm aching for this calendar to make an appearance, I really hope it's been worth the wait.
zlinko: they may also be very hush, hush because almost nothing has been done on it.
they changed the colour to white, that's quite a bit of work
Thank you Kip and Chris.
What do you mean rhann when you say they changed the colour to white? :-S
Microsoft just announced that Windows Live Hotmail is launching globally in 36 languages , double the
how to consolidate non federal student loans
state of ohio department education
university of north texas at dallas systems center
low cost online high school diploma programs
who is the best student loan consolidation program
Pingback from Podcast with liveside.net featuring Omar and Ellie | http://www.liveside.net/interview/archive/2007/04/18/windows-live-hotmail-rolls-out-our-interview-with-omar-shahine-and-ellie-powers-boyle.aspx | crawl-002 | en | refinedweb |
> hash.zip > hash.h
/* +++Date last modified: 05-Jul-1997 */ #ifndef HASH__H #define HASH__H #include
/* For size; } hash_table; /* ** This is used to construct the table. If it doesn't succeed, it sets ** the table's size to 0, and the pointer to the table to NULL. */ hash_table *construct_table(hash_table *table,size_t size); /* ** Inserts a pointer to 'data' in the table, with a copy of 'key' as its ** key. Note that this makes a copy of the key, but NOT of the ** associated data. */ void *insert(char *key,void *data,struct hash_table *table); /* ** Returns a pointer to the data associated with a key. If the key has ** not been inserted in the table, returns NULL. */ void *lookup(char *key,struct hash_table *table); /* ** Deletes an entry from the table. Returns a pointer to the data that ** was associated with the key so the calling code can dispose of it ** properly. */ void *del(char *key,struct hash_table *table); /* ** Goes through a hash table and calls the function passed to it ** for each node that has been inserted. The function is passed ** a pointer to the key, and a pointer to the data associated ** with it. */ void enumerate(struct hash_table *table,void (*func)(char *,void *)); /* **_table(hash_table *table, void (*func)(void *)); #endif /* HASH__H */ | http://read.pudn.com/downloads/sourcecode/math/1609/hash.h__.htm | crawl-002 | en | refinedweb |
07, 2008 01:11 PM
Patrick Smacchia is a Visual C# MVP involved in software development for over 15 years. He is the author of Practical .NET 2 and C# 2, a book about the .NET platform conceived from real world experience. After graduating in mathematics and computer science, he has worked on software in a variety of fields including stock exchange at Société Générale, an airline ticket reservation system at Amadeus as well as a satellite base station at Alcatel. He's currently the lead developer of the tool NDepend.
NEW: ANTS Memory Profiler 5 now out!
Give-away eBook – Confessions of an IT Manager
Effective Management of Static Analysis Vulnerabilities and Defects
Ensuring Code Quality in Multi-threaded Applications
NEW: ANTS Memory Profiler 5 just released!
Rob Bazinet (RB): What is NDepend?
Patrick Smacchia (PS): NDepend is a tool for .NET developers and architects. Code bases are very complex things and NDepend is a tool that helps getting information from the source code. For example, with NDepend knowing if your code base is correctly layered, knowing what has changed since the last release or assessing the code quality represents some immediate tasks that might take hours or days with traditional tools.
RB: How did you come with the idea for NDepend?
PS: 5 years ago I was consulting on a huge and dirty code base. At the same time I was reading the excellent book, Agile Software Development, Principles, Patterns, and Practices, from Robert C Martin. The book describes some cool metrics to assess componentization of a code base.
Finally at that time, I was coming to .NET from C++ and one of my preferred things was System.Reflection that was much more compelling than C++ RTTI. It was then natural to start developing a quick tool based on Reflection to see what Martin's metrics had to say on the huge and dirty code base. I then put the tool as OSS and it became more and more popular with many demands for features. At a point, I realized that if the tool would support some visual and querying facilities, it could represent a new step in how we deal with code complexity.
RB: How can NDepend help me with my coding tasks and/or development lifecycle?
PS: NDepend can be of great help in various tasks, including refactoring, code review, code quality check and enhancement, design erosion check, code discovering, code browsing, build process rule enforcement.
NDepend is useful for refactoring code because it can show dependencies between your components, your namespaces, your classes... thanks to a dependencies matrix panel and some 'boxes and arrows' graph generation.
NDepend supports more than 60 code metrics that can be used to assess the code quality:
The NDepend analysis process can be integrated into MSBuild or NAnt build process. A report about the build process health is emitted each time an analysis is performed.
Thanks to a language dedicated to code structure querying (Code Query Language, CQL), developers can ask for any kind of questions about their code bases:
This CQL language can be used to define some rules that can be checked for each build. When some rules get violated, the user gets notified from the report. NDepend comes with more than 50 predefined rules and it is designed to let users define seamlessly custom rule such as:
NDepend can be used to compare 2 versions of a code base. This feature is especially useful when you are about to release a new version and want to focus your smoke tests and code review on things that have changed. Here also the CQL language is a great help to explore the diff. For example, to list the methods that have been modified between 2 builds you just have to write:
Finally, NDepend comes with a Visual Studio 2005 and 2008 add-in and a Reflector add-in that helps accessing its features from these tools.
RB: How does one get started using NDepend? What is the recommended path?
PS: First, download NDepend and analyze your code base. This should be done seamlessly because the VisualNDepend UI has been polished to have the exact same look and feel than Visual Studio.
Once the analysis done, the VisualNDepend UI displays several panels to browse analysis results. At this point, the user need to choose if he wants to browse dependencies, browse metrics, query the code base with the CQL language, compare 2 analysis etc... More or less, each feature has its dedicated panel. There is also an embedded help section that contains some 'Getting Started' explanations. Some screencasts are also linked. They explain how to achieve each particular task. Finally, our website contains advanced documentation such as the complete CQL specifications.
Once the user masters each feature, she is able to use them all together to review and rationalize its code base.
RB: Does NDepend work with the .NET Framework 3.5? 3.0?
PS: Yes, the Visual Studio add-in of the new NDepend 2.6 version works with Visual Studio 2008. Also NDepend is able to analyze .NET 3.5 and 3.0 assemblies.
RB: NDepend is a product for .NET languages; do you have any plans for platforms beyond .NET? Any plans for analyzing dynamic code bases?
PS: Yes. NDepend is coded in C# but just 5% of our code is dedicated to .NET code analysis. It means that 95% of our code is abstracted from the platform of the code analyzed. In this context, a tier company, octo technology is currently developing a version of NDepend that will analyze Java code. Primarily octo technology, a French consultancy company focusing on software and information systems architecture, is a consulting company consisting of Java and .NET experts. Octo .NET consultants like NDepend and when the Java consultants were asking for the same tool. We then decided to do a partnership.
A beta version of the project XDepend (the Java NDepend version) will be available in Q1 2008.
RB: NDepend looks complicated for someone getting into code analysis; do you have tutorials or how-to for users?
PS: There is an embedded help section in the VisualNDepend UI that contains some 'Getting Started' explanations and some screencasts are also linked. There are some 3 minute screencasts to get started. Some others screencasts that describe main use-cases scenario are referenced on the main page here. To go further, we also provide some documentation such as the complete CQL specification, the description of all metrics, a summarizing poster done by Scott Hanselman, Stuart Celarier and Patrick Caulwell, Placemat Visualization Expert Pdf and more in our documentation section. Also, I am regularly feeding a blog on where I explain advanced usages of NDepend.
RB: Do you offer training for software teams to get them up and running quickly?
PS: We sometime visit clients that ordered enterprise licenses and wanted some special training. Even though training is not our main activity we will continue with it. It is very informative to have a direct contact with users. The product is full of features driven from users' feedback.
RB: What do you consider to be the most powerful or best feature of NDepend? And why?
PS: Tough questions, actually we use NDepend a lot to code NDepend. Personally I use the matrix every day to browse dependencies and make sure the architecture remains clean. We have more than 400 CQL rules that permanently care for the quality of our code. I am also addict to the comparison feature. I often use it to review code that is changing. I really believe that the devil lies in changes.
The good news is that doing so pays off and considerably improves our process and let us release new versions with a sustainable rhythm. More information can be found in our release notes.
RB: Patrick, thank you so much for taking the time with me today and teaching us about NDepend.
More information about NDepend can be found on the NDepend web site. Readers can learn more about Patrick at his | http://www.infoq.com/articles/patrick-smacchia-interview | crawl-002 | en | refinedweb |
Day 9: Tic tac toe
Who didn't play Tic tac toe with his friends? :)
What to expect
Today we will implement tic tac toe game in Nim, with 2 modes
- Human vs Human
- Human vs AI
Implementation
So, let's get it. The winner in the game is the first one who manages to get 3 cells on the board to be the same in the same column or row or diagonally first.
imports
import sequtils, tables, strutils, strformat, random, os, parseopt2 randomize()
Constraints and objects
As the game allow turns we should have a way to keep track of the next player
let NEXT_PLAYER = {"X":"O", "O":"X"}.toTable
Here we use a table to tell us the next player
Board
type Board = ref object of RootObj list: seq[string]
Here we define a simple class representing the board
- list is a sequence representing the cells
maybe cells is a better name
- please note list is just a sequenece of elements
0 1 2 3 4 5 6 7 8but we visualize it as
0 1 2 3 4 5 6 7 9
instead of using a 2d array for the sake of simplicity
let WINS = @[ @[0,1,2], @[3,4,5], @[6,7,8], @[0, 3, 6], @[1,4,7], @[2,5,8], @[0,4,8], @[2,4,6] ]
We talked
WIN patterns cells in the same row or the same column or in same diagonal
proc newBoard(): Board = var b = Board() b.list = @["0", "1", "2", "3", "4", "5", "6", "7", "8"] return b
this is the initializer of the board and sets the cell value to the string represention of its index
Winning
proc done(this: Board): (bool, string) = for w in WINS: if this.list[w[0]] == this.list[w[1]] and this.list[w[1]] == this.list[w[2]]: if this.list[w[0]] == "X": return (true, "X") elif this.list[w[0]] == "O": return (true, "O") if all(this.list, proc(x:string):bool = x in @["O", "X"]) == true: return (true, "tie") else: return (false, "going")
Here we check for the state of the game and the winner if all of the item in
WIN patterns are the same
proc `$`(this:Board): string = let rows: seq[seq[string]] = @[this.list[0..2], this.list[3..5], this.list[6..8]] for row in rows: for cell in row: stdout.write(cell & " | ") echo("\n--------------")
Here we have the string representation of the board so we can show it as 3x3 grid in a lovely way
proc emptySpots(this:Board):seq[int] = var emptyindices = newSeq[int]() for i in this.list: if i.isDigit(): emptyindices.add(parseInt(i)) return emptyindices
Here we have a simple helper function that returns the empty spots indices
the spots that doesn't have X or O in it, remember all the cells are initialized to the string representation of their indices.
Game
type Game = ref object of RootObj currentPlayer*: string board*: Board aiPlayer*: string difficulty*: int proc newGame(aiPlayer:string="", difficulty:int=9): Game = var game = new Game game.board = newBoard() game.currentPlayer = "X" game.aiPlayer = aiPlayer game.difficulty = difficulty return game # 0 1 2 # 3 4 5 # 6 7 8
Here we have another object representing the game and the players and the difficulty and wether it has an AI player or not and who is the current player
- difficulty is only logical in case of AI, it means when does the AI start calculating moves and considering scenarios, 9 is the hardest, 0 is the easiest.
proc changePlayer(this:Game) : void = this.currentPlayer = NEXT_PLAYER[this.currentPlayer]
Simple procedure to switch turns between players
Start the game
proc startGame*(this:Game): void= while true: echo this.board if this.aiPlayer != this.currentPlayer: stdout.write("Enter move: ") let move = stdin.readLine() this.board.list[parseInt($move)] = this.currentPlayer this.change_player() let (done, winner) = this.board.done() if done == true: echo this.board if winner == "tie": echo("TIE") else: echo("WINNER IS :", winner ) break
Here if we don't have
aiPlayer if not set it's just a game with 2 humans switching turns and checking for the winner after each move
Minmax and AI support
Minmax is an algorithm mainly used to predict the possible moves in the future and how to minimize the losses and maximize the chances of winning
-
-
type Move = tuple[score:int, idx:int]
We need a type Move on a certain idx to represent if it's a good/bad move
depending on the score
- good means minimizing chances of the human to win or making AI win => high score +10
- bad means maximizing chances of the human to win or making AI lose => low score -10
So let's say we are in this situation
O X X X 4 5 X O O
And it's
AI turn we have two possible moves (4 or 5)
O X X X 4 O X O O
this move (to 5) is clearly wrong because the next move to human will allow him to complete the diagonal (2, 4, 6) So this is a bad move we give it score -10 or
O X X X O 5 X O O
this move (to 4) minimizes the losses (leads to a TIE instead of making human wins) so we give it a higher score
proc getBestMove(this: Game, board: Board, player:string): Move = let (done, winner) = board.done() # determine the score of the move by checking where does it lead to a win or loss. if done == true: if winner == this.aiPlayer: return (score:10, idx:0) elif winner != "tie": #human return (score:(-10), idx:0) else: return (score:0, idx:0) let empty_spots = board.empty_spots() var moves = newSeq[Move]() for idx in empty_spots: # we calculate more new trees depending on the current situation and see where the upcoming moves lead var newboard = newBoard() newboard.list = map(board.list, proc(x:string):string=x) newboard.list[idx] = player let score = this.getBestMove(newboard, NEXT_PLAYER[player]).score let idx = idx let move = (score:score, idx:idx) moves.add(move) if player == this.aiPlayer: return max(moves) # var bestScore = -1000 # var bestMove: Move # for m in moves: # if m.score > bestScore: # bestMove = m # bestScore = m.score # return bestMove else: return min(moves) # var bestScore = 1000 # var bestMove: Move # for m in moves: # if m.score < bestScore: # bestMove = m # bestScore = m.score # return bestMove
Here we have a highly annotated
getBestMove procedure to calculate recursively the best move for us
Now our startGame should look like this
proc startGame*(this:Game): void= while true: ##old code ## AI check else: if this.currentPlayer == this.aiPlayer: let emptyspots = this.board.emptySpots() if len(emptyspots) <= this.difficulty: echo("AI MOVE..") let move = this.getbestmove(this.board, this.aiPlayer) this.board.list[move.idx] = this.aiPlayer else: echo("RANDOM GUESS") this.board.list[emptyspots.rand()] = this.aiPlayer ## oldcode
Here we allow the game to use difficulty which means when does the AI starts calculating the moves and making the tree? from the beginning 9 cells left or when there're 4 cells left? you can set it the way you want it, and until u reach the starting difficulty situation AI will use random guesses (from the available
emptyspots) instead of calculating
CLI entry
proc writeHelp() = echo """ TicTacToe 0.1.0 (MinMax version) Allowed arguments: -h | --help : show help -a | --ai : AI player [X or O] -l | --difficulty : destination to stow to """ proc cli*() = var aiplayer = "" difficulty = 9 for kind, key, val in getopt(): case kind of cmdLongOption, cmdShortOption: case key of "help", "h": writeHelp() # quit() of "aiplayer", "a": echo "AIPLAYER: " & val aiplayer = val of "level", "l": difficulty = parseInt(val) else: discard else: discard let g = newGame(aiPlayer=aiplayer, difficulty=difficulty) g.startGame() when isMainModule: cli()
Code is available on | https://xmonader.github.io/nimdays/day09_tictactoe_cli.html | CC-MAIN-2019-51 | en | refinedweb |
Initialize TensorFlow Variables With Matrix
Initialize TensorFlow variables with matrix of your choice. Example with identity matrix.
< > Code:
Transcript:
We import TensorFlow as tf.
import tensorflow as tf
Then we print out what version of TensorFlow we are using.
print(tf.__version__)
We are using TensorFlow 1.0.1.
In this video, we’re going to initialize a TensorFlow variable as the identity matrix of the size of our choosing using the TensorFlow variable functionality and the TensorFlow eye functionality.
All right, let’s get started.
First, remember that you can use the TensorFlow eye functionality to easily create a square identity matrix.
identity_matrix_ex = tf.eye(5, dtype="float32")
We create a 5x5 identity matrix with a data type of float32 and assign it to the Python variable identity matrix.
So we used tf.eye, give it a size of 5, and the data type is float32.
Note that the default data type for tf.eye is float32 but I like to specify it to make the code easier to read.
Now, let’s print out the identity_matrix_ex Python variable to see what we have.
print(identity_matrix_ex)
We see that it’s a TensorFlow variable, eye/MatrixDiag, the shape is 5x5 which is what we expect given we gave it a size of 5, and the data type is float32 which is what we specified.
Next, let’s initialize a TensorFlow variable using the identity matrix we just created.
identity_tensorflow_variable_ex = tf.get_variable("identity_tf_variable", initializer=identity_matrix_ex)
We use the tf.get_variable functionality, we give it a name of identity_tf_variable, and for the initializer, we use the identity_matrix_ex tensor that we just defined, and we assign that to the identity_tensorflow_variable_ex Python variable.
Let’s print out this identity_tensorflow_variable_ex Python variable to see what we have.
print(identity_tensorflow_variable_ex)
We see that it is a TensorFlow tensor, the name is identity_tf_variable, the shape is 5x5, and the data type is float32.
Now that we’ve set up our TensorFlow tensors and variables, it’s time to run the computational graph.\
sess = tf.Session()
We launch the graph in a session.
Then we initialize all the global variables in the graph.
sess.run(tf.global_variables_initializer())
Let’s print the identity_matrix_ex tensor in a TensorFlow session to see the values of the identity matrix.
print(sess.run(identity_matrix_ex))
We see that it is a 5x5 identity matrix where it has 1s down the diagonal, all the other entries are 0, and there is a decimal point after each number to show that it is indeed a float32 number.
Next, let’s print the Python variable identity_tensorflow_variable_ex’s initialized_value in a TensorFlow session to see the value.
print(sess.run(identity_tensorflow_variable_ex.initialized_value()))
Remember, this is what we are trying to do – create a TensorFlow variable that had the initialized value of the identity matrix.
When we evaluate this expression, we see that the TensorFlow variable has the initialized values of the identity matrix and the data type is float32.
Finally, we close the TensorFlow session to release the TensorFlow resources we used within the session.
sess.close()
That is how you initialize a TensorFlow variable as the identity matrix of the shape of your choosing using the TensorFlow variable functionality and the TensorFlow eye functionality. | https://aiworkbox.com/lessons/initialize-tensorflow-variable-as-identity-matrix | CC-MAIN-2019-51 | en | refinedweb |
0 Members and 1 Guest are viewing this topic.
Instead of exposing a global variable, you write a function that returns the value and another function that sets the value. Yes, hanging a global variable out in the wind is easier, in a Fortran kind of way, but it isn't better.
Einstein was right: Code should be as simple as possible. But no simpler!
Including a c file will upset many IDE's that have already added the files to the project. But the files will be loaded after the main.c file so the header file is needed to give information on function prototypes.
yes but that makes an awful mess.
#pragma onceextern int variable_that_needs_to_be_so_quick_you_cant_use_a_getter_function;void lcd_init();void lcd_print_text(char* text);
#include "lcd.h"int variable_that_needs_to_be_so_quick_you_cant_use_a_getter_function; // Actually defined only herestatic int internal_variable;static void internal_detail(){...}void lcd_init(){ internal_detail();}void lcd_print_text(char* text){ .... internal_variable = 123;}
#include "lcd_driver.h"void main(){ lcd_init(); lcd_print_text("hello world"); variable_that_needs_to_be_so_quick_you_cant_use_a_getter_function = 123; // Computer science people won't like this way, but you don't need to care.}
gcc -c lcd_driver.c -o lcd_driver.ogcc -c main.c -o main.old -o out.elf lcd_driver.o main.o
// Autogenerated, do not modifystatic const int8_t sin_lut[256] ={0, 3, 6, 9, 12, ... };
Yes, sometimes you include a .c file from another .c file - one typical example would be an autogenerated dataset like a large lookup table, which is only needed by that specific implementation. By having it in a separate file, it's easier to autogenerate again, overwriting the old file; or choose between files by changing the include line only; or just simply to keep it out of sight. It could be named .whatever, but .c is a logical extension if it's valid C code, such as:
Arduino turned on the switches that cause unused code to be omitted from the binary (even if they're in the same .C file as used code) about a decade ago. If your compiler still doesn't have a similar option, perhaps it's time to consider a new compiler.
.h file it's just a file being included in the compilation at the #include - exactly as if you copied and pasted. This is all there is to it (setting aside IDEs, syntax highlighters and such). It doesn't have to be .h, can have any extension you wish.Thus, every time you want to include the same text into two (or more) different files, you use the .h file. Or, if you want to generate a text externally and then include into the file being compiled, you use the .h file as well.
QuoteArduino turned on the switches that cause unused code to be omitted from the binary (even if they're in the same .C file as used code) about a decade ago.this is done not by the compiler but rather by the Wiring &C infrastructure.
Arduino turned on the switches that cause unused code to be omitted from the binary (even if they're in the same .C file as used code) about a decade ago.
Simon,Ditch your IDE. It's not helping you learn how this stuff works.These are really basic questions and if you were to spend a day writing batch scripts, makefiles, or whatever using only command line tools, you'd be able to master these concepts. As it is now, your understanding seems to stop at what the IDE does and that's simply not sufficient for professional work.Back to the topic... once you've factored out some code into a (shared) header file, you have to make sure that when that when the header is modified, every .c that depends on it is recompiled. Do you know how to do that without relying on an IDE?
Gnu make has become a bit feature rich, but it is consistent across all platforms [...]
Someone in GNU must have thought that it would have been "cool" improving the UNIX Tar into GNU Tar
Ah yes, makefiles. Haven't written one in decades.Do they still have the "feature" that tabs have a different meaning to spaces?
Quote from: tggzzz on January 22, 2019, 09:10:11 amAh yes, makefiles. Haven't written one in decades.Do they still have the "feature" that tabs have a different meaning to spaces?You betcha.I cut the program some slack because that design decision was made in 1976. OTOH, it's unfortunate that the Python world failed to learn from the experience and believes "significant" whitespace is a good idea. PS. Managing tabs in makefiles is easy if you're using emacs.
I have attached a makefile. [...]
-include $(OBJS:%.o=%.d)
########################define FLASH_BARE_CMDdevice $(SEGGER_DEVICE)log $(JLINK_LOG) # log what we dosi SWDspeed 4000hloadbin $(EXECUTABLE:.elf=.bin) 0x0rgexitendef#########################export FLASH_BARE_CMDjflash : $(EXECUTABLE:.elf=.bin) @echo "$$FLASH_BARE_CMD" | $(JLINKEXE) $(SELECT_JLINK) | https://www.eevblog.com/forum/microcontrollers/(c)-do-i-need-a-*-h-file-for-every-*-c-file/msg2138806/ | CC-MAIN-2019-51 | en | refinedweb |
convert a string to a node ID
#include <sys/vc.h> nid_t qnx_strtonid( const char *nodename, char **str );
The qnx_strtonid() function converts a string representing a node ID into an object of type nid_t. Typically, this function is used by programs that take a node ID as a command line parameter (for example, -n node).
The conversion ends at the first unrecognized character. A pointer to that character is stored in the character pointer to which str points, if str isn't NULL.
A valid numeric node ID on success. Even though a valid number is returned, the status of that node is not known (that is, whether it is "up" or "down"). On error, -1 is returned and errno is set.
QNX
errno, qnx_nidtostr() | https://users.pja.edu.pl/~jms/qnx/help/watcom/clibref/qnx/qnx_strtonid.html | CC-MAIN-2022-33 | en | refinedweb |
Monitoring Spring Boot Application With Prometheus and Grafana
Learn step by step process of monitoring your Spring Boot application with Prometheus and Grafana.
Join the DZone community and get the full member experience.Join For Free
In this article, we will be looking into how we can monitor our Spring Boot application using Grafana. We would be looking into the whole setup and creating a simple dashboard to view some metrics.
Every application that is deployed on production needs some kind of monitoring to see how the application is performing. This will give you some insights on whether the application is performing as aspected or if you would need to take some action in order to obtain the desired level of performance. In the modern world, this data is called Application Performance Metrics (APM). Now there are quite many commercial tools like Newrelic, Datadog APM, etc. which are SAAS services providing such capabilities.
Today we will be looking at two open-source tools called Grafana and Prometheus. Prometheus gathers and stores metrics data in a time series format while Grafana uses Prometheus as a data source to visualize the data on dashboards.
With this, Let’s start by creating an application and monitoring it using Grafana.
Creating a Spring Boot Application
Let’s go to and create a simple application with the following dependencies.
- Spring Boot Actuator (Ops)
- Prometheus (Observability)
- Spring Web ( Optional: only to create a simple REST controller.)
Next, we need to expose an actuator endpoint through which Prometheus will collect metrics data in the format that Prometheus understands. For this, we need to add the following properties.
management: endpoints: web: exposure: include: - prometheus
Next, Let’s add a simple controller that will produce some warning logs. We will use this to monitor the number of warnings we are getting.
@RestController @SpringBootApplication public class PrometheusIntegrationApplication { final static Logger logger = LoggerFactory.getLogger(PrometheusIntegrationApplication.class); public static void main(String[] args) { SpringApplication.run(PrometheusIntegrationApplication.class, args); } @GetMapping("/something") public ResponseEntity<String> createLogs() { logger.warn("Just checking"); return ResponseEntity.ok().body("All Ok"); }
With this, Let’s start the application and open the following URL:
Understanding the Metrics Data
After opening the above endpoint, you will find some metrics data in the following format
jvm_memory_used_bytes{area="heap",id="G1 Survivor Space",} 1005592.0
The first part i.e
jvm_memory_used_bytes is called the label, while the fields inside the curly braces are called attributes. Each of these labels represents a particular metric and the attribute provides you with a way to query so that you can get the values.
Next, Let's configure Prometheus to read this data.
Configuring Prometheus
To start Prometheus, we will be using a Prometheus docker image and provide it with some configuration to gather the metrics data from our application. It does so by creating jobs that will scrape data from an endpoint. So let’s define the job in the
prometheus.yamlconfiguration file as below.
scrape_configs: - job_name: 'Spring Boot Application input' metrics_path: '/actuator/prometheus' scrape_interval: 2s static_configs: - targets: ['localhost:8000'] labels: application: "My Spring Boot Application"
Here, I have defined a job that will call the actuator endpoint on our application every 2 seconds to get the metrics data.
Next, Let's create a docker-compose file that will bring the Prometheus docker image up and running.
services: prometheus: image: prom/prometheus:v2.35.0 network_mode: host container_name: prometheus restart: unless-stopped volumes: - ./data/prometheus/config:/etc/prometheus/ command: - "--config.file=/etc/prometheus/prometheus.yaml"
Here, we have the config file mounted at the location
/etc/prometheus and we use the location of the config file as an argument to the command. For simplicity, we are using the host network mode, so that Prometheus can access our application endpoint directly.
With this, let’s start the docker image with
docker compose up and open the URL on our browser.
Now let's search for the label
logback_events_total
As you can see, we get to see the metric that Prometheus gathered at a particular time.
In case you don't find the label, You can check if the job is running by navigating to “Status > Targets”. You should see the state as “UP” like this.
So with this, the data is getting ingested into Prometheus every 2 seconds.
Now let's visualize this using Grafana.
Visualizing Metrics in Grafana
We are going to be using Grafana’s docker image and let’s add it to the docker-compose file.
grafana: image: grafana/grafana-oss:8.5.2 pull_policy: always network_mode: host container_name: grafana restart: unless-stopped links: - prometheus:prometheus volumes: - ./data/grafana:/var/lib/grafana environment: - GF_SECURITY_ADMIN_PASSWORD=admin - GF_SERVER_DOMAIN=localhost
Here also we are making use of the host network mode, to make it easy for us and Grafana to access the Prometheus endpoint.
Next, let's open the URL and access Grafana using the username and password as “admin”
Configuring Grafana Data Source
Let’s first add the Prometheus data source. To do that, Navigate to “add a data source” and select Prometheus. Then you need to only add a single property i.e the Prometheus URL
Click “Save and test” and now, let's create our first Dashboard
Creating Grafana Dashboard
Click on the “+” icon on the left and then select “Create Dashboard”. Now let's add our first Panel.
Next, let's query for a label in the metric browser i.e
logback_events_total
As you can see here, we get counts of all types of logs. These counts are currently from our application’s startup logs and are shown in a time-series format.
Let’s drill down to only view the warning logs. For this, we would have to add the attribute
level=”warn” as below.
That's it. We just created a simple metric visualization panel to view the number of warning logs.
Now usually, we would like to view the rate of errors or warning logs over a certain period of time. This will help us to understand if there is some problem in our system. For this, we can use the
rate function to calculate the rate of logs over a particular period of time.
So after triggering the controller endpoint on our spring boot application, it generated some warning logs, that led to this graph.
Let’s save this panel and there we go. We just created our first Grafana Dashboard with warning logs metric panel.
Now, We don’t need to create dashboards from scratch. Rather there are quite many community-provided dashboards. This is what I really liked. Hence you can use a full-fledged dashboard for spring boot applications from here. However, I did find some problems while trying to use it as data was not getting visualized properly. So I updated the dashboard and you can find the JSON to the dashboard in my GitHub repo here.
In this article, we saw how we can monitor a Spring Boot application’s performance using Prometheus and Grafana. In My next article, we will be looking into Alerting on a certain event using Grafana.
You can find the complete code and Dashboard Json on my GitHub repo here.
I keep exploring and learning new things. If you want to know the latest trends and improve your software development skills, follow me on Twitter.
Published at DZone with permission of Amrut Prabhu. See the original article here.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/monitoring-spring-boot-application-with-prometheus | CC-MAIN-2022-33 | en | refinedweb |
hey, would appreciate advice from anybody more knowledgeable:)
i am plotting a figure, and below i have multiple fields that the user is to enter after inspecting a figure. i expect the user to zoom in, and then enter the values. problem is, that any time you enter anything, the plot resets. i don’t want that.
my desired behavior is as follows:
- zoom in on the plotly figure (client state of plotly figure is changed)
- enter a number / select an option
- press a button to update the plot based on number/select inputs
my problem is that the plotly figure resets itself after step 2 (after even an unsubmitted select, the client state of the plotly figure is reset).
i tried putting everything into an st.form(), tried caching / session-stating the figure; neither work. client changes to plotly figure always get reset
i attached a simple code snippet as an example.
would appreciate advice!
import streamlit as st import plotly.figure_factory as ff import numpy as np if 'bin_size' not in st.session_state: st.session_state['bin_size'] = 0.1 if 'plot_select' not in st.session_state: st.session_state['plot_select'] = 'plot1' # put figure inside a form? with st.form("form2"): submitted2 = st.form_submit_button(label='update plot') if submitted2: x = {'plot1': np.random.randn(100), 'plot2': np.random.randn(50)} fig = ff.create_distplot([x[st.session_state['plot_select']]], [st.session_state['plot_select']], bin_size=[st.session_state['bin_size']]) st.plotly_chart(fig, use_container_width=True) # put select inside a form? with st.form("form"): new_plot_select = st.selectbox("Select plot", ['plot1', 'plot2']) new_bin_size = st.number_input('Enter bin size', value = 0) submitted = st.form_submit_button(label='i want plot to reset on button press only') if submitted: st.session_state['bin_size'] = new_bin_size st.session_state['plot_select'] = new_plot_select st.header("zoom in on the plot before selecting/entering values") st.header("any action would cause the plot to reset; i don't want that") | https://discuss.streamlit.io/t/cant-enter-values-without-updating-a-plotly-figure/28066 | CC-MAIN-2022-33 | en | refinedweb |
README
¶
service-catalog
Introduction
The service-catalog project is.
As an example:
Most applications need a datastore of some kind. The service-catalog allows Kubernetes applications to consume services like databases that exist somewhere in a simple way:
A user wanting to consume a database in their application browses a list of available services in the catalog
The user asks for a new instance of that service to be provisioned
Provisioning means that the broker somehow creates a new instance of a service. This could mean basically anything that results in a new instance of the service becoming available. Possibilities include: creating a new set of Kubernetes resources in another namespace in the same Kubernetes cluster as the consumer or a different cluster, or even creating a new tenant in a multi-tenant SaaS system. The point is that the consumer doesn't have to be aware of or care at all about the details.
The user requests a binding to use the service instance in their application
Credentials are delivered to users in normal Kubernetes secrets and contain information necessary to connect to and authenticate to the service instance.
For more introduction, including installation and self-guided demo instructions, please see the introduction doc.
For more details about the design and features of this project see the design doc.
Video links
Overall Status
We are currently working toward a beta-quality release to be used in conjunction with Kubernetes 1.8. See the milestones list for information about the issues and PRs in current and future milestones.
The project roadmap contains information about our high-level goals for future milestones.
We are currently making weekly releases; see the release process for more information.
Documentation
Our goal is to have extensive use-case and functional documentation.
See here for detailed documentation.
See here for examples and here for broker servers that are compatible with this software.
Terminology
This project's problem domain contains a few inconvenient but unavoidable overloads with other Kubernetes terms. Check out our terminology page for definitions of terms as they are used in this project.
Contributing
Interested in contributing? Check out the contributing documentation.
Also see the developer's guide for information on how to build and test the code.
We have weekly meetings - see Kubernetes SIGs (search for "Service Catalog") for the exact date and time. Our agenda/notes doc can be found here
Previous Agenda
For more information about sig-service-catalog such as meeting times and agenda, check out the community site.
Code of Conduct
Participation in the Kubernetes community is governed by the Kubernetes Code of Conduct. | https://pkg.go.dev/github.com/ericavonb/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog | CC-MAIN-2022-33 | en | refinedweb |
pip install aiobotocore
The Python aiobotocore library is among the top 100 Python libraries, with more than 43,241,528 downloads. This article will show you everything you need to get this installed in your Python environment.
How to Install aiobotocore on Windows?
- Type
"cmd"in the search bar and hit
Enterto open the command line.
- Type “
pip install aiobotocore” (without quotes) in the command line and hit
Enteragain. This installs aiobotocore for your default Python installation.
- The previous command may not work if you have both Python versions 2 and 3 on your computer. In this case, try
"pip3 install aiobotocore"or “
python -m pip install aiobotocore“.
- Wait for the installation to terminate successfully. It is now installed on your Windows machine.
Here’s how to open the command line on a (German) Windows machine:
First, try the following command to install aiobotocore on your system:
pip install aiobotocore
Second, if this leads to an error message, try this command to install aiobotocore on your system:
pip3 install aiobotocore
Third, if both do not work, use the following long-form command:
python -m pip install aiobotoc aiobotocore on Linux?
You can install aiobotocore on Linux in four steps:
- Open your Linux terminal or shell
- Type “
pip install aiobotocore” (without quotes), hit Enter.
- If it doesn’t work, try
"pip3 install aiobotocore"or “
python -m pip install aiobotocore“.
- Wait for the installation to terminate successfully.
The package is now installed on your Linux operating system.
How to Install aiobotocore on macOS?
Similarly, you can install aiobotocore on macOS in four steps:
- Open your macOS terminal.
- Type “
pip install aiobotocore” without quotes and hit
Enter.
- If it doesn’t work, try
"pip3 install aiobotocore"or “
python -m pip install aiobotocore“.
- Wait for the installation to terminate successfully.
The package is now installed on your macOS.
How to Install aiobotocore in PyCharm?
Given a PyCharm project. How to install the aiobotoc
"aiobotocore"without quotes, and click
Install Package.
- Wait for the installation to terminate and close all pop-ups.
Here’s the general package installation process as a short animated video—it works analogously for aiobotocore if you type in “aiobotocore” in the search field instead:
Make sure to select only “aiobotocore” because there may be other packages that are not required but also contain the same term (false positives):
How to Install aiobotocore in a Jupyter Notebook?
To install any package in a Jupyter notebook, you can prefix the
!pip install my_package statement with the exclamation mark
"!". This works for the aiobotocore library too:
!pip install my_package
This automatically installs the aiobotocore library when the cell is first executed.
How to Resolve ModuleNotFoundError: No module named ‘aiobotocore’?
Say you try to import the aiobotocore package into your Python script without installing it first:
import aiobotocore # ... ModuleNotFoundError: No module named 'aiobotocore'
Because you haven’t installed the package, Python raises a
ModuleNotFoundError: No module named 'aiobotocore'.
To fix the error, install the aiobotocore library using “
pip install aiobotocore” or “
pip3 install aiobotocore” in your operating system’s shell or terminal first.
See above for the different ways to install aiobotoc. | https://blog.finxter.com/how-to-install-aiobotocore-in-python/ | CC-MAIN-2022-33 | en | refinedweb |
In this user guide, we will learn how to incorporate Wi-Fi manager with our ESP32/ESP8266 boards. WiFi manager let us connect ESP32 or ESP8266 to a network without having to hardcode our network credentials in a script. We will be using a previous example when we learned how to build a web server (ESP32/ESP8266 MicroPython Web Server – Control Outputs) and include the wi-fi manager in it for better functionality.
Table of Contents
Introducing Wi-Fi Manager
With the addition of the Wi-fi manager library in MicroPython, we no longer have to separately provide the SSID and password of the local network. No hard coding would be required. We will be able to connect through other networks (Access Points) with our ESP32/ESP8266 boards automatically without any hassle of manually entering the network credentials every time. Multiple SSID connections, as well as additional custom variables, can also be implemented through this.
The Process of Integrating Wi-Fi Manager
The following flow chart taken from shows the process behind the execution of wi-fi managers with Esp boards in MicroPython.
- Initially, our Esp32 or Esp8266 will be set up as an Access Point when it starts.
- Next, to connect to your ESP board which acts as an AP, we will go to the IP address 192.164.4.1.
- A web page containing different network will be shown from which we will choose the one which we want to configure.
- These network credentials of the network we chose, will get saved in our ESP32/8266.
- Then we will set up a new SSID and password for our selected network. The ESP32/8266 will restart and now will be able to connect with the network we selected. In this phase the ESP board acts in the Station mode.
- If the connection is not successful, the ESP board goes back to AP mode and we will set the SSID and password again.
Wi-Fi Manager Library in MicroPython
MicroPython does not contain the library for the wi-fi manager so we will need to upload it ourselves. We will learn how to do this by using two different IDE for MicroPython:
import network import socket import ure import time <span style="color: #ff0000;"> Wi-Fi Client Setup </span> </h1> <form action="configure" method="post"> <table style="margin-left: auto; margin-right: auto;"> <tbody> """) while len(ssids): ssid = ssids.pop(0) client.sendall("""\ <tr> <td colspan="2"> <input type="radio" name="ssid" value="{0}" />{0} </td> </tr> """.format(ssid)) client.sendall("""\ <tr> <td>Password:</td> <td><input name="password" type="password" /></td> </tr> </tbody> </table> <p style="text-align: center;"> <input type="submit" value="Submit" /> </p> </form> <p> </p> <hr /> <h5> <span style="color: #ff0000;"> Your ssid and password information will be saved into the "%(filename)s" file in your ESP module for future usage. Be careful about security! </span> </h5> <hr /> <h2 style="color: #2e6c80;"> Some useful infos: </h2> <ul> <li> Original code from <a href="" target="_blank" rel="noopener">cpopp/MicroPythonSamples</a>. </li> <li> This code available at <a href="" target="_blank" rel="noopener">tayfunulu/WiFiManager</a>. </li> </ul> </html> """ % dict(filename=NETWORK_PROFILES)) client.close() def handle_configure(client, request): match = ure.search("ssid=([^&]*)&password=(.*)", request) if match is None: send_response(client, "Parameters not found", status_code=400) return False # version 1.9 compatibility try: ssid = match.group(1).decode("utf-8").replace("%3F", "?").replace("%21", "!") password = match.group(2).decode("utf-8").replace("%3F", "?").replace("%21", "!") except Exception: ssid = match.group(1).replace("%3F", "?").replace("%21", "!") password = match.group(2).replace("%3F", "?").replace("%21", "!") if len(ssid) == 0: send_response(client, "SSID must be provided", status_code=400) return False if do_connect(ssid, password): <span style="color: #ff0000;"> ESP successfully connected to WiFi network %(ssid)s. </span> </h1> <br><br> </center> </html> """ % dict(ssid=ssid) send_response(client, response) try: profiles = read_profiles() except OSError: profiles = {} profiles[ssid] = password write_profiles(profiles) time.sleep(5) return True else: <span style="color: #ff0000;"> ESP could not connect to WiFi network %(ssid)s. </span> </h1> <br><br> <form> <input type="button" value="Go back!" onclick="history.back()"></input> </form> </center> </html> """ % dict(ssid=ssid) send_response(client, response) return False def handle_not_found(client, url): send_response(client, "Path not found: {}".format(url), status_code=404) def stop(): global server_socket if server_socket: server_socket.close() server_socket = None def start(port=80): global server_socket addr = socket.getaddrinfo('0.0.0.0', port)[0][-1] stop() wlan_sta.active(True) wlan_ap.active(True) wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode) server_socket = socket.socket() server_socket.bind(addr) server_socket.listen(1) print('Connect to WiFi ssid ' + ap_ssid + ', default password: ' + ap_password) print('and access the ESP via your favorite web browser at 192.168.4.1.') print('Listening on:', addr) while True: if wlan_sta.isconnected(): return True client, addr = server_socket.accept() print('client connected from', addr) try: client.settimeout(5.0) request = b"" try: while "\r\n\r\n" not in request: request += client.recv(512) except OSError: pass print("Request is: {}".format(request)) if "HTTP" not in request: # skip invalid requests continue # version 1.9 compatibility try: url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).decode("utf-8").rstrip("/") except Exception: url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).rstrip("/") print("URL is {}".format(url)) if url == "": handle_root(client) elif url == "configure": handle_configure(client, request) else: handle_not_found(client, url) finally: client.close()
Uploading wiFi Manager Library in uPyCraft IDE
Click on the New file icon in the tools section and a file will open up.
Write down all the code available at GitHub by clicking here. This code initializes the wi-fi manager library.
Click the Save button, and set wifimgr.py as the name of the file. You can save this file by giving in your preferred directory.
When you press the save button, the following window will appear:
To upload the wifi manager library, click the Download and Run button. You will see the wifimgr library under device option.
We have successfully installed the wifi manager library in uPyCraft IDE.
Uploading Wi-Fi Manager in Thonny IDE
Open a new file and write the library code available at GitHub which can be accessed from here.
Click on the Save button and set the file name as wifimgr.py
When you click on the save button, you will see the following window will appear. Select, MicroPython device to upload the library to ESP32 or ESP8266.
Note: The Device options in the menu bar to upload scripts are available in the previous versions of Thonny IDE.
After following these steps, we have successfully installed the Wi-Fi manager library in Thonny IDE.
Wi-Fi manager with ESP32 and ESP8266
As we have set up the wi-fi manager library in our respective IDEs, we can now see how to configure the wi-fi manager with our ESP boards. We will be using a previous example where we created a webpage that controlled the output GPIO pins of ESP32 and ESP8266. You can view that tutorial here.
The web page contains an ON and an OFF button indicating the status of an LED connected to the GPIO of the ESP boards. Instead of manually hard coding the network credentials, we will provide the SSID and password of our WiFi router to our ESP boards with the wi-fi manager instead.
MicroPython Script
We will first open a new file and save it as main.py. Save it in the same directory as wifimgr.py. Now copy the code which is given below in your main.py file.
import wifimgr # importing the Wi-Fi manager library from time import sleep import machine import gc try: import usocket as socket except: import socket led = machine.Pin(2, machine.Pin.OUT) wlan = wifimgr.get_connection() #initializing wlan if wlan is None: print("Could not initialize the network connection.") while True: pass print("ESP OK")</i> <a href=\"?led_2_on\"><button class="button">LED ON</button></a> </p> <p> <i class="far fa-lightbulb fa-3x" style="color:#000000;"></i> <a href=\"?led_2_off\"><button class="button button1">LED OFF</button></a> </p> </body> </html>""" return html s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: try: if gc.mem_free() < 102000: gc.collect() conn, addr = s.accept() conn.settimeout(3.0) print('Received HTTP GET connection request from %s' % str(addr)) request = conn.recv(1024) conn.settimeout(None) request = str(request) print('GET Rquest Content = %s' % request) led_on = request.find('/?led_2_on') led_off = request.find('/?led_2_off') if led_on == 6: print('LED ON -> GPIO2') led_state = "ON" led.on() if led_off == 6: print('LED OFF -> GPIO2') led_state = "OFF" led.off() response = web_page() conn.send('HTTP/1.1 200 OK\n') conn.send('Content-Type: text/html\n') conn.send('Connection: close\n\n') conn.sendall(response) conn.close() except OSError as e: conn.close() print('Connection closed')
How the Code works?
The web server part of this code is taken from our previously published project here (ESP32/ESP8266 MicroPython Web Server – Control Outputs). You can refer to that for a code explanation of the web server part.
We will be importing the Wi-Fi manager library in the main.py file so that we will be able to use the wi-fi manager functionality.
import wifimgr
Then, we will be handling the Wi-fi manager by initializing WLAN. This will automatically set our ESP board in the station mode as it uses the instance ‘network.WLAN(STA_IF).’ The get_connection() function waits for the user to enter the ssid and password of your network.
wlan = wifimgr.get_connection() if wlan is None: print("Could not initialize the network connection.") while True: pass
We will be using try and except statements so that we are not left with an open socket. This occurs when the ESP board boots initially. Next, we will bind the socket to an IP address and a port number. This is achieved by using the bind() method. In our case, we will pass an empty string followed by ‘80’ to the bind() function. The empty string portrays the default IP address of our Esp32/Esp8266 board and ‘80’ specifies the port number set for the Esp web servers.
try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', 80)) s.listen(5)
The ESP board would reset if there is a failure and we get an OS error. This shows that there was an open socket left. With the help of the reset() function, the open socket would be deleted.
except OSError as e: machine.reset()
Once we set the network credentials using the Wifi manager, the ESP board sets as a station instead of an access point and connects through the wi-fi manager.
MicroPython Wi-Fi Manager Demo
To see Wi-Fi manager demo, upload wifimgr.py and main.py files to ESP32 or ESP8266. After uploading press the reset button on your ESP board:
After pressing the reset button, you will see this message on shell console. Thats means ESP32/ESP8266 board has setup as a access point.
Now connect to soft access point using either your desktop computer or mobile phone. Open Wi-Fi settings in your mobile and you will see WifiManager as wireless connection.
Connect to WiFi manager by using a default password tayfunulu.
After successfully connecting with WiFiManager, open any web browser and type the IP address 192.168.4.1. You wil see the following page og Wi-Fi manager:
Select your network and enter the password in password window. After that press enter button. You will get the message that the ESP has successfully connected to a Wi-Fi network.
That means our ESP board has succesfully connected to WiFi network and it has setup in station mode. Now ESP32/ESP8266 will work in station mode as soon as you press the reset button. When you press the reset button, it will print the ESP web server IP address in station mode.
Now again connect your desktop computer or mobile phone with your local network that is router and paste the IP address in your web browser.
You will see this web page in your web browser which control GPIO2 of ESP32.
In summary
By using the Wi-Fi manager library, we do not have to hardcode our network credentials in our MicroPython script. WiFi-Manager library sets the ESP32/ESP8266 in soft access point mode and displays available network connections on a web page. It will let you select your network and connect to it using its name and password. Once your ESP board connected to the network, it will automatically work in station mode.
If you find this tutorial useful, you can read our MicroPython web server project here:
- ESP32/ESP8266 MicroPython Web Server – Control Outputs
- MicroPython: BME680 Web Server with ESP32 and ESP8266
- BME280 Web Server with ESP32/ESP8266 (Weather Station)
- MicroPython ESP32/ESP8266: Send Sensor Readings via Email (IFTTT)
- DS18B20 Web Server with ESP32/ESP8266(Weather Station)
- MicroPython: OpenWeatherMap API with ESP32/ESP8266 – Sensorless Weather Station
- DHT11/DHT22 Web Server with ESP32/ESP8266 (Weather Station)
- MicroPython: ESP32/ESP8266 Access Point – Web Server Example | https://microcontrollerslab.com/micropython-wi-fi-manager-esp32-esp8266/ | CC-MAIN-2022-33 | en | refinedweb |
External data representation and marshalling
SENG 41283 — Distributed and Cloud Computing
External data representation
The information stored in running programs is represented as data structures. In a distributed system information in messages transferring between components consists of sequences of bytes. So, to communicate any information these data structures must be converted to a sequence of bytes before transmission. Also in the arrival of messages, the data should be re-converted into its original data structure.
There are several different types of data that use in computers and these types are not the same in every place that data needed to transfer. Let’s see how these types differ from one to another.
- Integers have two different types — big-endian and little-endian
- Floats — Different representation in different architectures
- Characters — ASCII and Unicode
To effectively communicate these different types of data between computers there should be a way to convert every data to a common format. External data representation is the data type that act as the intermediate data type in the transmission.
Marshalling
Marshalling is the process of taking a collection of the data structures to transfer and format them into an external data representation type which suitable for transmission in a message.
Unmarshalling
Unmarshalling is the inverse of this process, which is reformatting the transferred data on arrival to produce the original data structures at the destination.
Let’s find how this external data representation works in different use cases.
CORBA’s common data representation
Common Object Request Broker Architecture aka CORBA is a specification developed by Object Management Group (OMG) currently the leading middleware solutions in most distributed systems. Its a specification for creating, distributing, and managing objects in distributed networks. CORBA describes a messaging mechanism by which objects distributed over a network can transfer messages with each other irrespective of the platform or language used to create those objects. This enables collaboration between systems on different architectures, operating systems, programming languages as well as computer hardware.
CORBA’s Common Data Representation specification includes 15 primitive data types and other constructed types.
Java’s object serialization
In Java remote method invocation (RMI), both objects and primitive data values may be passed as arguments and results of method invocations. In Java, the term serialization refers to the activity of flattening an object(An instance of a class) or a connected set of objects into a serial form that is suitable for storing on disk or transmitting in a message.
XML (Extensible Markup Language)
XML is a markup language that was defined by the World Wide Web Consortium for general use on the web. XML was initially developed for writing structured documents for the web. XML is used to enable clients to communicate with web services and for defining the interfaces and other properties of web services.
Conclusion
In CORBA’s common data representation and Java’s object serialization, the marshalling and unmarshalling activities are intended to be carried out by a middleware layer without any involvement on the part of the application programmer. Even in the case of XML, which is textual and therefore more accessible to hand-encoding, software for marshalling and unmarshalling is available for all commonly used platforms and programming environments. Because marshalling requires the consideration of all the finest details of the representation of the primitive components of composite objects, the process is likely to be error-prone if carried out by hand. Compactness is another issue that can be addressed in the design of automatically generated marshalling procedures.
In CORBA’s common data representation and Java’s object serialization, the primitive data types are marshalled into a binary form. In XML, the primitive data types are represented textually. The textual representation of a data value will generally be longer than the equivalent binary representation. The HTTP protocol, which is described in Chapter 5, is another example of the textual approach.
Another issue with regard to the design of marshalling methods is whether the marshalled data should include information concerning the type of its contents. For example, CORBA’s representation includes just the values of the objects transmitted and nothing about their types. On the other hand, both Java serialization and XML do include type information, but in different ways. Java puts all of the required type information into the serialized form, but XML documents may refer to externally defined sets of names (with types) called namespaces.
Although we are interested in the use of an external data representation for the arguments and results of RMIs and RPCs, it does have a more general use for representing data structures, objects or structured documents in a form suitable for transmission in messages or storing in files. | https://nsa94.medium.com/external-data-representation-and-marshalling-fcd51381b513?source=user_profile---------6---------------------------- | CC-MAIN-2022-33 | en | refinedweb |
On 9/1/06, Daniel Rall <dlr@collab.net> wrote:
> Any particular reason why one error message complains about the lock
> element "wrong location", while the other complains about an element
> at an "unexpected location"?
Because I was kind of inconsistent ;-)
I'll make one of them consistent with the other.
> ...
> > -/* This implements the `ne_xml_endelm_cb' prototype. */
> > -static int getlocks_end_element(void *userdata, int state,
> > - const char *ns, const char *ln)
> > +/* This implements the `svn_ra_dav__endelm_cb_t' prototype. */
> > +static svn_error_t *
> > +getlocks_end_element(void *userdata, int state,
> > + const char *ns, const char *ln)
> > {
> > get_locks_baton_t *baton = userdata;
> > const svn_ra_dav__xml_elm_t *elm;
> > - svn_error_t *err;
> >
> > elm = svn_ra_dav__lookup_xml_elem(getlocks_report_elements, ns, ln);
> >
> > /* Just skip unknown elements. */
> > if (elm == NULL)
> > - return NE_XML_DECLINE;
> > + return SVN_NO_ERROR;;
>
> This seems like a subtle change in behavior in the information
> returned by this function, and a difference in the API (lacking an
> "int *elem" parameter). I guess the loss of "declined" vs. "no error"
> doesn't matter in this case?
I don't think it matters. NE_XML_DECLINE is a zero return value,
which Neon defines as meaning "do nothing". Non-zero aborts the
parse. We return zero from that wrapper callback in any case where
there's no svn error returned.
> ...
> > @@ -1638,11 +1647,8 @@
> > || (! baton->current_lock->token)
> > || (! baton->current_lock->owner)
> > || (! baton->current_lock->creation_date))
> > - {
> > - baton->err = svn_error_create(SVN_ERR_RA_DAV_MALFORMED_DATA, NULL,
> > - _("Incomplete lock data returned"));
> > - return NE_XML_ABORT;
> > - }
> > + SVN_ERR(svn_error_create(SVN_ERR_RA_DAV_MALFORMED_DATA, NULL,
> > + _("Incomplete lock data returned")));
>
> Ditto.
Should be fine, since if we get an error there it will return
NE_XML_ABORT higher up.
> ...
> > - /* unrecognized encoding! */
> > - return NE_XML_ABORT;
> > + return svn_error_createf(SVN_ERR_RA_DAV_MALFORMED_DATA,
> > + NULL,
> > + _("Got unrecognized encoding '%s'"),
> > + baton->encoding);
>
> Ditto.
>
> (In case any other reviewers are curious, we discontinued use of the
> baton->err field because it was removed from the baton structure.)
Yep.
> ...
> > rc = validate_element(NULL, parent_state, elm->id);
> >
> > if (rc != SVN_RA_DAV__XML_VALID)
> > - return (rc == SVN_RA_DAV__XML_DECLINE) ? NE_XML_DECLINE : NE_XML_ABORT;
> > + {
> > + if (rc == SVN_RA_DAV__XML_DECLINE)
> > + {
> > + *elem = NE_XML_DECLINE;
> > + return SVN_NO_ERROR;
> > + }
> > + else
> > + return svn_error_createf(SVN_ERR_RA_DAV_MALFORMED_DATA, NULL,
> > + _("Got unexpected element '%s:%s'"),
>
> It's nice that we supply the unexpected element's name here. Why not
> do that above also? (And do we need to check the element's name for
> null before using it?)
I think the elt_name has to be non-null, although I suspect the
namespace might be, I'll look into it further. I'll also look at
making the other errors return the element names. Sometimes it wasn't
convenient to figure out what element was actually causing the
problem, but in many cases it should be possible.
> > --- trunk/subversion/libsvn_ra_dav/file_revs.c (original)
> > +++ trunk/subversion/libsvn_ra_dav/file_revs.c Fri Sep 1 13:14:27 2006
> ...
> > switch (parent_state)
> > {
> > case ELEM_root:
> > if (elm->id != ELEM_file_revs_report)
> > - return NE_XML_ABORT;
> > + return svn_error_create(SVN_ERR_RA_DAV_MALFORMED_DATA, NULL,
> > + _("Got unexpected element"));
> > break;
>
> As above -- dropping some error context, and not supplying the element
> name in the error message. More of the same throughout this file.
The error returned will be the same, but yeah, I agree we should use
the name if possible.
> ...
> > switch (elm->id)
> > {
> > case ELEM_rev_prop:
> > case ELEM_set_prop:
> > att = svn_xml_get_attr_value("name", atts);
> > if (!att)
> > - return NE_XML_ABORT;
> > + return svn_error_create(SVN_ERR_RA_DAV_MALFORMED_DATA, NULL,
> > + _("Element is missing name attr"));
>
> Out of context, this error message would probably be a bit tough to
> digest. It would help to quote "name". More of the same below.
Keep in mind, these errors are only going to occur if the server is
broken or something is actually removing stuff from the XML. I agree
it could be made better (most of these errors could), but jumping
through hoops to improve the clarity of errors that almost never
happen may not be the best use of time.
> > --- trunk/subversion/libsvn_ra_dav/ra_dav.h (original)
> > +++ trunk/subversion/libsvn_ra_dav/ra_dav.h Fri Sep 1 13:14:27 2006
> ...
> > +/* Our equivalent of ne_xml_startelm_cb, the difference being that it
> > + * returns errors in a svn_error_t, and returns the element type via
> > + * ELEM. To ignore the element *ELEM should be set to NE_XML_DECLINE
> > + * and SVN_NO_ERROR should be returned.
> > + */
> > +typedef svn_error_t * (*svn_ra_dav__startelm_cb_t)(int *elem,
> > + void *baton,
> > + int parent,
> > + const char *nspace,
> > + const char *name,
> > + const char **atts);
> > +
> > +/* Our equivalent of ne_xml_cdata_cb, the difference being that it returns
> > + * errors in a svn_error_t.
> > + */
> > +typedef svn_error_t * (*svn_ra_dav__cdata_cb_t)(void *baton,
> > + int state,
> > + const char *cdata,
> > + size_t len);
>
> As mentioned above, why do some APIs allow return of the Neon error
> code through the int *elem parameter, and some do not?
Because the start callback needs to be able to return the state entry
for this element, so they need to be able to return arbitrary
integers. The cdata and end element callbacks only need to return
either zero (for no problem at all), which is what the wrapper returns
when you return SVN_NO_ERROR from your callback, or non-zero to break
out of the parse, which is what gets returned whenever you return an
actual error from your callback.
> > --- trunk/subversion/libsvn_ra_dav/replay.c (original)
> > +++ trunk/subversion/libsvn_ra_dav/replay.c Fri Sep 1 13:14:27 2006
>
> I have similar questions/comments as for replay.c as for the other .c
> files in ra_dav.
>
> > --- trunk/subversion/libsvn_ra_dav/util.c (original)
> > +++ trunk/subversion/libsvn_ra_dav/util.c Fri Sep 1 13:14:27 2006
> > @@ -555,6 +555,70 @@
> > }
> >
> >
> > +typedef struct {
> > + svn_error_t *err;
> > +
> > + void *baton;
> > +
> > + svn_ra_dav__startelm_cb_t startelm_cb;
> > + svn_ra_dav__cdata_cb_t cdata_cb;
> > + svn_ra_dav__endelm_cb_t endelm_cb;
> > +} parser_wrapper_baton_t;
>
> This Neon wrapper data structure should be documented per the info
> from the change log message for this commit. Good doc here would
> largely obviate the need to document the implementing functions below.
I'll improve the docs there.
-garrett
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org
For additional commands, e-mail: dev-help@subversion.tigris.org
Received on Tue Sep 5 17:21:21 2006
This is an archived mail posted to the Subversion Dev
mailing list. | http://svn.haxx.se/dev/archive-2006-09/0064.shtml | CC-MAIN-2013-20 | en | refinedweb |
In some situations it is desirable to use editable combo boxes which keep a historical list of choices for future reuse. This conveniently allows the user to select a previous choice rather than typing identical text. A typical example of an editable combo box with memory can be found in find/replace dialogs in many modern applications. Another example, familiar to almost every modern computer user, is provided in many Internet browsers which use an editable URL combo box with history mechanism. These combo boxes accumulate typed addresses so the user can easily return to any previously visited site by selecting it from the drop-down list instead of manually typing it in again.
The following example shows how to create a simple browser application using an editable combo box with memory. It uses the serialization mechanism to save data between program sessions, and the JEditorPane component (described in more detail in chapters 11 and 19) to display non-editable HTML files.
Figure 9.3 JComboBox with memory of previously visited URLs.
<<file figure9-3.gif>>
The Code: Browser.java
see \Chapter9\3
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class Browser extends JFrame
{
protected JEditorPane m_browser;
protected MemComboBox m_locator;
protected AnimatedLabel m_runner;
public Browser() {
super("HTML Browser [ComboBox with Memory]");
setSize(500, 300);
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.add(new JLabel("Address"));
p.add(Box.createRigidArea(new Dimension(10, 1)));
m_locator = new MemComboBox();
m_locator.load("addresses.dat");
BrowserListener lst = new BrowserListener();
m_locator.addActionListener(lst);
p.add(m_locator);
m_runner = new AnimatedLabel("clock", 8);
p.add(m_runner);
getContentPane().add(p, BorderLayout.NORTH);
m_browser = new JEditorPane();
m_browser.setEditable(false);
m_browser.addHyperlinkListener(lst);
JScrollPane sp = new JScrollPane();
sp.getViewport().add(m_browser);
getContentPane().add(sp, BorderLayout.CENTER);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
m_locator.save("addresses.dat");
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
m_locator.grabFocus();
}
class BrowserListener implements ActionListener, HyperlinkListener
{
public void actionPerformed(ActionEvent evt) {
String sUrl = (String)m_locator.getSelectedItem();
if (sUrl == null || sUrl.length() == 0 ||
m_runner.getRunning())
return;
BrowserLoader loader = new BrowserLoader(sUrl);
loader.start();
}
public void hyperlinkUpdate(HyperlinkEvent e) {
URL url = e.getURL();
if (url == null || m_runner.getRunning())
BrowserLoader loader = new BrowserLoader(url.toString());
class BrowserLoader extends Thread
protected String m_sUrl;
public BrowserLoader(String sUrl) { m_sUrl = sUrl; }
public void run() {
setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
m_runner.setRunning(true);
try {
URL source = new URL(m_sUrl);
m_browser.setPage(source);
m_locator.add(m_sUrl);
}
catch (Exception e) {
JOptionPane.showMessageDialog(Browser.this,
"Error: "+e.toString(),
"Warning", JOptionPane.WARNING_MESSAGE);
m_runner.setRunning(false);
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
public static void main(String argv[]) { new Browser(); }
}
class MemComboBox extends JComboBox
public static final int MAX_MEM_LEN = 30;
public MemComboBox() {
super();
setEditable(true);
public void add(String item) {
removeItem(item);
insertItemAt(item, 0);
setSelectedItem(item);
if (getItemCount() > MAX_MEM_LEN)
removeItemAt(getItemCount()-1);
public void load(String fName) {
try {
if (getItemCount() > 0)
removeAllItems();
File f = new File(fName);
if (!f.exists())
FileInputStream fStream =
new FileInputStream(f);
ObjectInput stream =
new ObjectInputStream(fStream);
Object obj = stream.readObject();
if (obj instanceof ComboBoxModel)
setModel((ComboBoxModel)obj);
stream.close();
fStream.close();
catch (Exception e) {
e.printStackTrace();
System.err.println("Serialization error: "+e.toString());
public void save(String fName) {
FileOutputStream fStream =
new FileOutputStream(fName);
ObjectOutput stream =
new ObjectOutputStream(fStream);
stream.writeObject(getModel());
stream.flush();
stream.close();
class AnimatedLabel extends JLabel implements Runnable
protected Icon[] m_icons;
protected int m_index = 0;
protected boolean m_isRunning;
public AnimatedLabel(String gifName, int numGifs) {
m_icons = new Icon[numGifs];
for (int k=0; k<numGifs; k++)
m_icons[k] = new ImageIcon(gifName+k+".gif");
setIcon(m_icons[0]);
Thread tr = new Thread(this);
tr.setPriority(Thread.MAX_PRIORITY);
tr.start();
public void setRunning(boolean isRunning) {
m_isRunning = isRunning;
public boolean getRunning() { return m_isRunning; }
public void run() {
while(true) {
if (m_isRunning) {
m_index++;
if (m_index >= m_icons.length)
m_index = 0;
setIcon(m_icons[m_index]);
Graphics g = getGraphics();
m_icons[m_index].paintIcon(this, g, 0, 0);
else {
if (m_index > 0) {
setIcon(m_icons[0]);
}
try { Thread.sleep(500); } catch(Exception ex) {}
Understanding the Code
Class Browser
This class extends JFrame to implement the frame container for our browser. Instance variables:
JEditorPane m_browser: text component to parse and render HTML files.
MemComboBox m_locator: combo box to enter/select URL address.
AnimatedLabel m_runner: traditional animated icon alive while the browser is requesting a URL.
The constructor creates the custom combo box, m_locator, and an associated explanatory label. Then it creates the m_runner icon and places all three components in the northern region of our frame's content pane. JEditorPane m_browser is created and placed in a JScrollPane to provide scrolling capabilities. This is then added to the center of the content pane.
Note that the WindowListener, as used in many previous examples to close the frame and terminate execution, receives an additional function: it invokes our custom save() method (see below) on our custom combo box component before destroying the frame. This saves the list of visited URLs entered as a file called "addresses.dat" in the current running directory.
Class Browser.BrowserListener
This inner class implements both the ActionListener and HyperlinkListener interfaces to manage navigation to HTML pages. The actionPerformed() method is invoked when the user selects a new item in the combo box . It verifies that the selection is valid and the browser is not currently running (i.e. requesting a URL). If these checks are passed it then creates and starts a new BrowserLoader instance (see below) for the specified address.
Method hyperlinkUpdate() is invoked when the user clicks a hyperlink in the currently loaded web page. This method also determines the selected URL address and starts a new BrowserLoader to load it.
Class Browser.BrowserLoader
This inner class extends Thread to load web pages into the JEditorPane component. It takes a URL address parameter in the constructor and stores it in a instance variable. The run() method sets the mouse cursor to hourglass (Cursor.WAIT_CURSOR) and starts the animated icon to indicate that the browser is busy.
The core functionality of this thread is enclosed in its try/catch block. If an exception occurs during processing of the requested URL, it is displayed in simple dialog message box (we will learn discuss JOptionPane in chapter 14).
The actual job of retrieving, parsing, and rendering the web page is hidden in a single call to the setPage() method. So why do we need to create this separate thread instead of making that simple call, say, in BrowserListener? The reason is, as we discussed in chapter 2, by creating separate threads to do potentially time-consuming operations we avoid clogging up the event-dispatching thread.
Class MemComboBox
This class extends JComboBox to add a historical mechanism for this component. The constructor creates an underlying JComboBox component and sets its editable property to true.
The add() method adds a new text string to the beginning of the list. If this item is already present in the list, it is removed from the old position. If the resulting list is longer than the pre-defined maximum length then the last item in the list is truncated.
Method load() loads a previously stored ComboBoxModel from file "addresses.dat" using the serialization mechanism. The significant portion of this method reads an object from an ObjectInputStream and sets it as the ComboBoxModel. Note that any possible exceptions are only printed to the standard output and purposefully do not distract the user (since this serialization mechanism should be considered an optional feature).
Similarly, the save() method serializes our combo box's ComboBoxModel. Any possible exceptions are, again, printed to standard output and do not distract the user.
Class AnimatedLabel
Surprisingly, Swing does not provide any special support for animated components, so we have to create our own component for this purpose. This provides us with an interesting example of using threads in Java.
Note: Animated GIFs are fully supported by ImageIcon (see chapter 5) but we want complete control over each animated frame here.
AnimatedLabel extends JLabel and implements the Runnable interface. Instance variables:
Icon[] m_icons: an array of images to be used for animation.
int m_index: index of the current image.
boolean m_isRunning: flag indicating whether the animation is running.
The constructor takes a common name of a series of GIF files containing images for animation, and the number of those files. These images are loaded and stored into an array. When all images are loaded a thread with maximum priority is created and started to run this Runnable instance.
The setRunning() and getRunning() methods simply manage the m_isRunning flag.
In the run() method we cyclically increment the m_index variable and draw an image from the m_icons array with the corresponding index, exactly as you would expect from an animated image. This is done only when the m_isRunning flag is set to true. Otherwise, the image with index 0 is displayed. After an image is painted, AnimatedLabel yields control to other threads and sleeps for 500 ms.
The interesting thing about this component is that it runs in parallel with other threads which do not necessary yield control explicitly. In our case the concurrent BrowserLoader thread spends the main part of its time inside the setPage() method, and our animated icon runs in a separate thread signaling to the user that something is going on. This is made possible because this animated component is running in the thread with the maximum priority. Of course, we should use such thread priority with caution. In our case it is appropriate since our thread consumes only a small amount of the processor's time and does yield control to the lesser-priority threads (when it sleeps).
Note: As a good exercise try using threads with normal priority or Swing's Timer component in this example. You will find that this doesn't work as expected: the animated icon does not show any animation while the browser is running.
Running the Code
Figure 9.3 shows the Browser application displaying a web page. Note that the animated icon comes to life when the browser requests a URL. Also note how the combo box is populated with URL addresses as we navigate to different web pages. Now quit the application and re-start it. Note that our addresses have been saved and restored (by serializing the combo box model, as discussed above).
Note: HTML rendering functionality is not yet matured. Do not be surprised if your favorite web page looks signigicantly different in our Swing-based browser. As a matter of fact even the JavaSoft home page throws several exceptions while being displayed in this Swing component. (These exceptions occur outside our code, during the JEditorPane rendering--this is why they are not caught and handled by our code.)
The example given here is a good usage for such a device. However, a memory combobox will not always be appropriate. Remember the advice that usability of an unsorted comboboxes tends to degrade rapidly as the number of items grows. Therefore, it is sensible to deploy this technique where the likelihood of more than say 20 entries is very small. The browser example is good because it is unlikely that a user would type more than 20 URLs in a single web surfing session.
Where you have a domain problem which is likely to need a larger number of memory items but you still want to use a memory combobox, consider adding a sorting algorithm, so that rather than most recent first, you sort into a meaningful index such as alphabetical order. This will improve usability and mean that you could easily populate the list up to 2 or 3 hundred items. | http://www.javafaq.nu/java-bookpage-20-4.html | CC-MAIN-2013-20 | en | refinedweb |
csDirtyAccessArray< T, ElementHandler > Class Template ReferenceA templated array class. More...
#include <csutil/dirtyaccessarray.h>
Inheritance diagram for csDirtyAccessArray< T, ElementHandler >:
Detailed Description
template<class T, class ElementHandler = csArrayElementHandler<T>>
A templated array class.
class csDirtyAccessArray< T, ElementHandler > 46 of file dirtyaccessarray.h.
Constructor & Destructor Documentation
Initialize object to hold initially 'ilimit' elements, and increase storage by 'ithreshold' each time the upper bound is exceeded.
Definition at line 53 of file dirtyaccessarray.h.
Member Function Documentation
Get the pointer to the start of the array.
Definition at line 66 of file dirtyaccessarray.h.
Get the pointer to the start of the array.
Definition at line 57 of file dirtyaccessarray.h.
Get a copy of the array.
The caller is responsible for deleting this with 'delete[]'. Returns 0 if there are no items in the array.
Definition at line 79 of file dirtyaccessarray.h.
The documentation for this class was generated from the following file:
- csutil/dirtyaccessarray.h
Generated for Crystal Space 1.0.2 by doxygen 1.4.7 | http://www.crystalspace3d.org/docs/online/api-1.0/classcsDirtyAccessArray.html | CC-MAIN-2013-20 | en | refinedweb |
jdbc mysql - JDBC
jdbc mysql import java.sql.*;
public class AllTableName...=DriverManager.getConnection("jdbc:mysql://localhost:3306/ram","root","root... this problemm thank u
---------- java ----------
Listing all table name in Database!
SDKH
jdbc mysqll - JDBC
jdbc mysqll import java.sql.*;
public class AllTableName{
public...("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql...();
}
}
}
this is O/P please solve this problemm thank u
---------- java
jdbc
jdbc sir
i want a java code which have some method(new a/c(),update a/c(),serchUser(through id ),getuser(id , pass),changePass(id, id));
using oracle 10g
thank u
MySQL connectivity - JDBC
....
thank u.. Hi friend,
This error occur due to "com.mysql.jdbc.Driver" class not found
In the lib folder "mysql-connector-java-5.0.6-bin.jar...MySQL connectivity hi all,
i am not able to connect Mysql
jdbc - JDBC
...? if u replyed its very useful for me... Hi,
Please read JDBC tutorial at
Thanks
Hi,
You...");
Read at
Thanks
Thank U - Java Beginners
Thank U Thank U very Much Sir,Its Very Very Useful for Me.
From SUSHANT
jdbc - JDBC
conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName...jdbc how to get tablecount in jdbc hai frnd...
wat do u want to get the table count in a database or row count in a table?
if u want
JDBC - JDBC
there are any contents in the ResultSet
this is done at if(!(rs.next()))
Thank u
All...JDBC connection to database and show results Check if the database...("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin
jdbc - JDBC
= null;
String url = "jdbc:mysql://localhost:3306/";
String dbName...
thank y sir Hi friend,
Please implement following code.
import....
Thanks - Java Beginners
,
For running jdbc on Mysql, first u have to create a table in SQL.
You can refer the following example.
hope this inf. is useful for u.
thank u,
srujana
online quiz program coding using jsp, jdbc odbc connection with ms. access.. Thank you.
.. Thank you. please provide online quiz program coding using jsp, jdbc...").newInstance();
Connection connection = DriverManager.getConnection("jdbc:mysql... = DriverManager.getConnection("jdbc:mysql://localhost:3306/register","root";, "root
jdbc driver for mysql - Java Beginners
of jdbc-mysql database connectivity and idea about jdbc and mysql driver...jdbc driver for mysql I need jdbc driver program for connecting java progrma to mysql. Please
any one send me the url to download the driver
jdbc
jdbc - JDBC
JDBC Query to Connect Database JDBC Query to connect to database will u supply me the block of code where it throws the exception
JDBC - JDBC
://
Thanks...JDBC JDBC driver class not found:com.mysql.jdbc.Driver.....
Am getting an error like this......
i have added the jar files for mysql inside
jdbc - JDBC
jdbc Hi,
Could you please tell me ,How can we connect to Sql server through JDBC.
Which driver i need to download.
Thank You Hi Friend,
Please visit the following code:
ResultSetMetaData - JDBC
!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306... in Database!");
Connection con = null;
String url = "jdbc:mysql...();
}
}
}
For more information on JDBC-Mysql visit
[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName.../jdbc/
Thanks
jdbc - JDBC
static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306... on Netbeans and jdbc visit to :
http - JDBC
void main(String[] args) {
System.out.println("Inserting values in Mysql database table!");
Connection con = null;
String url = "jdbc:mysql... implementing class. Hi friend,
Example of JDBC Connection with Statement
j2ee - JDBC
.
Thank u. First of all you did not give the what type of runtime error...("Oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle....
Extract the zip file : C:\oracle\ora81\jdbc\lib\classes111.zip (ex)
and put
JDBC - JDBC
");
con = DriverManager.getConnection("jdbc:mysql://192.168.10.211...://
Java - JDBC
Java sir i want to make a login form in servlet with session and cookies in java(netBeans6.1). plz help me to sove my problem.i shall be thank full to u
jdbc - JDBC
jdbc Hi..
i am running the servlet program with jdbc connections
in this porgram i used two 'esultset' objects.. in this wat ever coding...
please sent to me response
thank u
Its updated ,inserted
jdbc - JDBC
main(String[]args){
try{
Connection con = null;
String url = "jdbc:mysql...();
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test...://
Thanks
jdbc - JDBC
("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost... con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ram","root","root... MySql visit to :
Thanks
jdbc - JDBC
= DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root...:
Retrieve Image using Java
jdbc - JDBC
Example!");
Connection con = null;
String url = "jdbc:mysql://localhost...;
String url = "jdbc:mysql://192.168.10.211:3306/amar";
String driver...();
}
}
}
---------------------------------------------
Visit for more information:
jdbc - JDBC
("jdbc:mysql://localhost:3306/ram","root","root");
System.out.println("Connect... information.
Thanks
Java - JDBC
Java sir i want to make a login form in servlet with session and cookies in java(netBeans6.1)also with run time database(MS-Access). plz help me to sove my problem.i shall be thank full to u
mysql jdbc connectivity
mysql jdbc connectivity i want to connect retrieve data from mysql using jdbc
creating jdbc sql statements - JDBC
.");
Connection con = null;
String url = "jdbc:mysql://192.168.10.211...creating jdbc sql statements I had written the following program and when i compile it it is giving some errors...can u give the reason
JDBC-SERVLET
.
Thank u for you solution...JDBC-SERVLET *while doing connectivity of jdbc with servlet I m...=DriverManager.getConnection("jdbc:odbc:{Microsoft Access Driver(*.mdb
java - JDBC
url = "jdbc:mysql://localhost:3306/";
String dbName = "databasename... for each while execution........
but this is not need as u have the direct sql... Hi
Read for more information.
JAVA - JDBC
have sent me the following code. First of all I thank u very much. But there was a small problem the log-out code(sent by u) was working fine with the "Internet... that it was going back.
Thank u very much... u helped me a lot for solving many problems
Prepared statement JDBC MYSQL
Prepared statement JDBC MYSQL How to create a prepared statement in JDBC using MYSQL? Actually, I am looking for an example of prepared statement.
Selecting records using prepared statement in JDBC
jsp - JDBC
;<%Connection con = null; String url = "jdbc:mysql://localhost:3306.../viewanswers/272.html Thank you for ur
Mysql & java - JDBC
;
String url = "jdbc:mysql://localhost:3306/";
String dbName... on JDBC visit to : & java Hi guys, please help! I'm new to mysql, I want
Multi value data - JDBC
with mysql database.
thank you Hi friend,
Plz explain your problem in details what you want and visit to :
Thanks
mysql problem - JDBC
= "jdbc:mysql://localhost:3306/test";
Connection con=null;
try...mysql problem hai friends
please tell me how to store the videos in mysql
plese help me as soon as possible
thanks in advance
ClassNotFoundException - JDBC
MySql ClassNotFoundException Dear sir,
i am working in Linux platform with MySQL database , actually i finished all installation in MySQL... install in linux any software making connection between java and MySQL. Or how can i
JAVA & MYSQL - JDBC
JAVA & MYSQL How can we take backup of MySQL 5.0 database by using...;Hi Friend,
Please visit the following page for working example of MySQL backup. This may help you in solving your problem.
mysql installation problem - JDBC
mysql installation problem Hi,
when i installing mysql server on my pc in
MySQL Server Instance Configuration Wizard,I enter the root pw... information.
xml configuration file - JDBC
a xml configuration file . We have mysql database in some other system. I have to access the data from different system. For this jdbc connectivity how to create a xml file. Please help me out.
Thank you Hi Friend,
Try
Connection to jdbc - Java Beginners
from Postgresql JDBC.
i used the following code... but its not working... can u suggest me with the correct solution.
my.jsp
my form...,
We have used Mysql database.
Try the following code
Retrieving cells in MySQL - JDBC
SERVLETS AND MYSQL - JDBC
jdbc question - JDBC
(),"jdbc:mysql://localhost/commons",pros);
KeyedObjectPoolFactory kopf =new...jdbc question
Up to now i am using just connection object for jdbc... a database connection for each user.
In JDBC connection pool, a pool of Connection
jdbc code - JDBC
jdbc code Dear Sir,
i have created one jsp with two fields... is the code to extract them and display them in jsp
if u want to display current user and his/her password use ServletContext.
or like this.
if u want
Connections with MicroSoft SQL - JDBC
;
Statement st = null;
ResultSet rs = null;
String url = "jdbc...) {
e.printStackTrace();
}
}
}
can u send whats the wrong with this ...
Thank You
Iranagouda
java servlets - JDBC
java servlets First thank you sir for your reply
sir i am using... that situation how i am connect to the "Oracle Database" when u r installing oracle database it asks global sid what u give it is hoststring default
using Blob in jdbc - JDBC
");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost...();
}
}
can u give me solution plz
JAVA(JDBC) - JDBC
";
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql...JAVA(JDBC) Hello friends, please tel me, how can we retrieve... for more information.
jsp-jdbc - JDBC
jsp-jdbc Hi!
html- jsp-jdbc program
from the html form where...="DriverManager.getConnection("jdbc:odbc:ashokdb","scott","tiger");
Statement st...;br> <br>Dear Rajanikanth,
thank you very much for posting
JDBC
JDBC why we use batch in jdbc
jdbc
jdbc display the records using index in jdbc
jdbc
jdbc Hai ,
Give a steps for jdbc connectivity
CLOB example - JDBC
("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection ("jdbc:mysql...CLOB example Hi everybody
can u tell me the method to use CLOB...; Hi Friend,
In MySql database,TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT
Multi-value data - JDBC
database.only i dont know just how to begin creating it.what i need is mysql syntax to cater for that.thank u
Ask Questions?
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions. | http://www.roseindia.net/tutorialhelp/comment/74806 | CC-MAIN-2013-20 | en | refinedweb |
Timeline
10/12/08:
- 16:16 Changeset [2938] by
- ThePimp?: target GTK# 2.10 instead of 2.12.
- 16:04 Changeset [2937] by
- Improve the Win32 cross-build script. Still doesn't work well.
- 16:03 Changeset [2936] by
- Add a bunch of .gitignore files for git-svn users.
- 16:03 Changeset [2935] by
- Do not install example programs.
- 16:03 Changeset [2934] by
- libpipi: sometimes imlib_load_image() succeeds but imlib_image_get_data() …
- 16:03 Changeset [2933] by
- Better autotools/Monodevelop integration.
- 16:03 Changeset [2932] by
- ThePimp?: minor GUI changes.
- 16:03 Changeset [2931] by
- ThePimp?: do not attempt to save a file if there is no open image.
- 16:03 Changeset [2930] by
- pipi-sharp: make .config really absolute.
- 13:20 Changeset [2929] by
- win32: remove the executable bit on MonoPosixHelper?.dll.
- 13:04 libpipi/oric edited by
- fix links (diff)
- 13:00 libpipi/devel edited by
- << back to libpipi (diff)
- 12:58 libpipi edited by
- link to thepimp and development notes (diff)
- 12:57 libpipi/examples edited by
- << back to libpipi (diff)
- 12:57 libpipi/oric edited by
- << back to libpipi (diff)
- 12:56 libpipi/devel edited by
- libpipi development notes (diff)
- 12:42 libpipi/devel created by
- starting to work on the libpipi developer notes
- 12:22 thepimp edited by
- (diff)
10/11/08:
- 23:56 Changeset [2928] by
- pipi-sharp: make the .dll.config file contents absolute.
- 23:56 Changeset [2927] by
- Update the Monodevelop projects.
- 23:56 Changeset [2926] by
- ThePimp?: make image loading more robust.
- 23:56 Changeset [2925] by
- Tell git to ignore generated pipi/pipi_types.h.
- 17:40 libpipi edited by
- (diff)
- 17:11 Changeset [2924] by
- Fix paths in Trac configuration.
- 17:09 Changeset [2923] by
- Fix paths in Trac configuration.
- 17:06 Changeset [2922] by
- Branch web trunk for tests.
- 17:05 Changeset [2921] by
- Create branches and tags for the website.
- 16:41 Changeset [2920] by
- Merge www/ and trac/ into a single web/ project.
- 14:02 Changeset [2919] by
- pipi-sharp: copy libpipi.dll before building test-csharp.
- 13:55 Changeset [2918] by
- ThePimp?: the Visual Studio solution now builds a working Pimp.exe
- 13:54 Changeset [2917] by
- Update the win32 contribs with Mono 2.0 libraries.
- 12:19 Changeset [2916] by
- Tune Visual Studio files so that they work with Monodevelop.
- 12:19 Changeset [2915] by
- Put back ● as the TextEntry? invisible character and tell gmcs our files …
- 11:55 Changeset [2914] by
- Create Visual Studio build files for libpipi, pipi-sharp and The Pimp.
- 11:10 Changeset [2913] by
- Fix C include paths for separate directory builds.
- 11:10 Changeset [2912] by
- Make the GTK# detection code more robust.
- 11:10 Changeset [2911] by
- libpipi: include <stdlib.h> in files where NULL is used.
- 10:20 Changeset [2910] by
- ThePimp?: add namespace before resource names.
- 03:30 Changeset [2909] by
- libpipi: fix a sign bug in the GDI loader.
- 02:52 Changeset [2908] by
- Set PACKAGE_VERSION instead of VERSION in the win32 config.h file.
- 01:41 Changeset [2907] by
- Add Mono.Posix.dll to the shipped binary assemblies for Win32.
10/10/08:
- 00:24 Changeset [2906] by
- * Cleanup my term after a grab
10/09/08:
- 01:53 Changeset [2905] by
- Remove tabs in the code here and there.
- 01:50 Changeset [2904] by
- Start writing Visual Studio projects.
10/08/08:
- 10:56 Changeset [2903] by
- libpipi: fix file headers.
- 02:14 Changeset [2902] by
- Support C99 types on Win32 through the same hacks as in libcaca.
- 01:43 Changeset [2901] by
- Update the Win32 cross-build script to reflect recent reorganisation.
- 01:27 Changeset [2900] by
- Renamed msvc into win32.
- 00:06 Changeset [2899] by
- Reorganise win32 files and add proper svn:ignore properties everywhere.
10/07/08:
- 23:26 Changeset [2898] by
- Reorganise MSVC files so that each project is with its source code.
- 20:10 Changeset [2897] by
- * Added preliminary support of CoreImage? (Cocoa/Mac? OS X) Changed …
- 18:06 Changeset [2896] by
- Move stubs.h to caca/caca_stubs.h since it's only used by the library.
- 18:06 Changeset [2895] by
- Fix the library suffix detection.
- 01:36 Changeset [2894] by
- Fix the library suffix detection.
- 00:40 Changeset [2893] by
- ThePimp?: store Win32 GTK# in SVN (but not in distributed tarballs).
- 00:38 Changeset [2892] by
- ThePimp?: add missing NewFile? source files.
- 00:14 Changeset [2891] by
- ThePimp?: deactivate toolbox for now.
- 00:11 Changeset [2890] by
- ThePimp?: the "New" button now works.
10/06/08:
- 23:33 Changeset [2889] by
- ThePimp?: middle mouse drag now scrolls the image.
- 22:45 Changeset [2888] by
- Detect shared library suffix at configure stage.
- 22:44 Changeset [2887] by
- ThePimp?: toolbox test.
- 22:44 Changeset [2886] by
- Detect shared library suffix at configure stage.
- 22:44 Changeset [2885] by
- ThePimp?: creating the BEST FUCKING ABOUT BOX IN THE WORLD!
- 21:53 Changeset [2884] by
- * Reverted dll.config.in stuff as it doesn't work as expected
- 21:41 Changeset [2883] by
- * Added temporary autoconf support for OSX
- 21:33 Changeset [2882] by
- caca-sharp: support systems with .dylib or .sl shared libraries.
- 21:33 Changeset [2881] by
- .gitignore: ignore files generated by MonoDevelop?.
- 21:33 Changeset [2880] by
- Clean up the web server directories before copying the documentation …
- 21:33 Changeset [2879] by
- doc: rewrite the tutorial to reflect recent API updates.
- 21:33 Changeset [2878] by
- libcaca: fix an infinite loop in the .pc file.
- 10:55 thepimp edited by
- link to libpipi (diff)
- 10:47 Changeset [2877] by
- ThePimp?: fix URL in the FUCKING ABOUT BOX!
- 00:19 Changeset [2876] by
- ThePimp?: we now have a FUCKING ABOUT BOX. That's right. Now we're a real …
- 00:14 thepimp created by
- creating The Pimp page:
Note: See TracTimeline for information about the timeline view. | http://caca.zoy.org/timeline?from=2008-10-12T16%3A03%3A48%2B02%3A00&precision=second | CC-MAIN-2013-20 | en | refinedweb |
in the games plugin i set the palette, before i draw anything the first time: for (int i=0; i<COLORS; i++) { #if VDRVERSNUM < 10307 if (screen) screen->AddColor(PALETTE(i)); #else if (screen) { screen->GetBitmap(0)->SetColor(i, PALETTE(i)); } #endif } is this useful in any way, except that i know which color is on a specific index? if cOsd would provide a SetIndex() methode it would speed up setting a pixel a little bit. or should i dump that code anyway? thx & best regards ... clemens -- Info: To unsubscribe send a mail to ecartis@linuxtv.org with "unsubscribe vdr" as subject. | http://www.linuxtv.org/mailinglists/vdr/2004/05-2004/msg00568.html | CC-MAIN-2013-20 | en | refinedweb |
How To: Use Regular Expressions to Constrain Input in ASP.NET input.
Overview:
- Constrain the acceptable range of input characters.
- Apply formatting rules. For example, pattern-based fields, such as tax identification numbers, ZIP Codes, or postal codes, require specific patterns of input characters.
- Check lengths.
Regular expression support is available to ASP.NET applications through the RegularExpressionValidator control and the Regex class in the System.Text.RegularExpressions namespace.
Using a RegularExpressionValidator Control
- Add a RegularExpressionValidator control to your page.
- Set the ControlToValidate property to indicate which control to validate.
- Set the ValidationExpression property to an appropriate regular expression.
- Set the ErrorMessage property to define the message to display if the validation fails..
Using ^ and $.
Using the Regex Class
- Add a using statement to reference the System.Text.RegularExpressions namespace.
- Call the IsMatch method of the Regex class, as shown in the following example.
// >
Use Regular Expression Comments);
Common Regular Expressions
Some common regular expressions are shown in Table 1.
Table 1. Common Regular Expressions
Additional Resources
For more information, see the regular expression tutorial at.
Feedback
Provide feedback by using either a Wiki or e-mail:
- Wiki. Use the Security Guidance Feedback Wiki page at
We are particularly interested in feedback regarding the following:
- Technical issues specific to our recommendations
- Usefulness and usability issues
Technical Support
Technical support for the Microsoft products and technologies referenced in this guidance is provided by Microsoft Support Services. For; Chris Ullman, Content Master; David Raphael, Rudolph Araujo, Foundstone Professional Services; Manoranjan M. Paul
- Microsoft Consulting Services and PSS Contributors and Reviewers: Adam Semel, Nobuyuki Akama, Tom Christian, Wade Mascia
- Microsoft Product Group Contributors and Reviewers: Stefan Schackow, Vikas Malhotra, Microsoft Corporation
- MSDN Contributors and Reviewers: Kent Sharkey, Microsoft Corporation
- Microsoft IT Contributors and Reviewers: Eric Rachner, Shawn Veney (ACE Team), Microsoft Corporation
-, Linda Werner & Associates Inc
- Release Management: Sanjeev Garg, Microsoft Corporation | http://msdn.microsoft.com/en-us/library/ff650303.aspx | CC-MAIN-2013-20 | en | refinedweb |
I'm still early into learning to code, so sorry if the code is wonky...
I'm making a number guessing game that guesses based on a first guess from two numbers the user gives and then puts those numbers into a list ascending. then my issue, i want to remove numbers lower/higher from my first guess then just do random.choice(list) code to follow....
import random
print("\nLets see if I can guess the number you're thinking.\nI've got some questions first")
tryNumber=1)+".\n")
firstGuess=random.randint(numberRangeLow, numberRangeHigh)
numbers=[]
nums=[]
while numberRangeLow < numberRangeHigh+1:
numbers.append(numberRangeLow)
nums.append(numberRangeLow)
numberRangeLow+=1
while tryNumber < trys:
print("Is your number", str(firstGuess), "?")
answer=input("Enter 'higher', 'lower' or correct (Case-Sensitive)")
if answer == "higher":
numbers.remove('''nums >= firstGuess''')
firstGuess=random.choice(numbers)
print("Is your number", str(firstGuess), "?")
First off,
while numberRangeLow < numberRangeHigh+1: do stuff is basically the same as
range.
For the same result, you can use
numbers = range(numberRangeLow, numberRangeHigh + 1), which will build the list for you.
You also don't need to warn about it being case sensitive, if you use
str.lower() it'll automatically put it into lower case. For example, you could do
if answer.lower() == "higher".
To remove numbers, you can do list slicing. For example, if you have
a = [1, 2, 3, 4], and it's lower than 3, you can get the index of 3 by using
a.index(3), which in this case, will give 2.
By then cutting off anything higher than this index with
a[2:], you have removed any higher numbers than 3.
Here's a quick update to your code doing the bits I mentioned.) #New bits: numbers = range(numberRangeLow, numberRangeHigh + 1) for i in range(trys): guess = random.choice(numbers) print("Is your number", str(guess), "?") answer = input("Enter 'higher', 'lower' or 'correct'").lower() if answer == 'correct': break elif answer == 'higher': list_index = numbers.index(guess) numbers = numbers[list_index + 1:] elif answer == 'lower': list_index = numbers.index(guess) numbers = numbers[:list_index]
I rearranged the last part of the code so you didn't have 2 copies of the random choice. Also for the record, it's seen as better practice to
name_variables_like_this and
notLikeThis.
Edit: Kevins way is slightly different from mine, a simple comparison would be assuming you have written the numbers down on paper, this way would rip the paper in half and discard one part, whereas Kevins way would be writing it out again on a fresh sheet of paper, so you get more control, but it's a bit slower.
Edit 2: Since I'm bored, I wrote it how I'd do it with a function (with some comments). Bear in mind it's python 2 not python 3 I'm using so copy + paste won't work for you.
def number_guess(tries, low, high): #Error if low is more than or the same as high if low >= high: raise ValueError('invalid range') #Build number list num_list = range(low, high + 1) print 'I have got {} tries'.format(tries) print 'And the number is between {} and {}'.format(low, high) for i in range(tries): guess = random.choice(num_list) print 'Is {} your number?'.format(guess) answer = input('Enter higher, lower or correct').lower() #Empty answer if not answer: continue #Correct answer if answer[0] in ('c', 'y'): print 'I guessed in {} tries'.format(i) return True #Number is higher if answer[0] == 'h': list_index = num_list.index(guess) num_list = num_list[list_index + 1:] #Number is lower elif answer[0] == 'l': list_index = num_list.index(guess) num_list = num_list[:list_index] #If it hits this point there are no tries left print 'I failed to guess' return False tries = int(input('How many tries will you let me have?' )) low = int(input('What is the lowest number I can guess?' )) high = int(input('And what is the highest?' )) success = number_guess(tries, low, high) | https://codedump.io/share/e9TqnLB6b1oL/1/remove-numbers-from-a-list-less-than-variable | CC-MAIN-2017-47 | en | refinedweb |
With Statement (Redux)
My previous implementation of the with_statement in ruby had one major flaw: It allowed only a single context manager per with block. While effective, it leads to cluttered code, like the following:
with(open("hello.txt")){|f| with(open("bonjour.txt")){|g| puts f.read() puts g.read() } }
Effective, but it isn't as clear as it could be and introduces more nesting than is really necessary. This coupled with my desire to explore varargs methods and blocks in ruby has lead me to a more robust implementation that can take an arbitrary number of managers as a parameter.
def with(*managers, &block) def with_(managers, resources, block) if managers.nitems > 0 begin resource = managers.delete_at(0) resources << resource.enter() with_(managers, resources, block) ensure resource.exit() end else block.call(*resources) end end with_(managers, [], block) end
The preceding implementation is more complex than the original. In addition to introducing "star magic"1, it relies on recursive creation of begin-ensure blocks which complicates exception handling; however, this implementation allows for such beautiful usage as:
with(open("hello.txt"), open("bonjour.txt")) {|f, g| puts f.read() puts g.read() }
Should a manager's exit method raise an exception, that exception will supersede any exception raised within the block, though it will not interfere with exiting other managers.
An implementation and unittests are available in a Mercurial repository. The implementation can be retrieved as follows:
hg clone
Both the implementation and unittests are licensed under the MIT license. | http://aaron.maenpaa.ca/blog/entries/2008/04/19/with-statement-redux/ | CC-MAIN-2017-47 | en | refinedweb |
Developing
- Manuel StrehlOverwrite PHP’s built-in functions in unit testsIn unit tests you might run in problems, when your code uses PHP built-in functions, that emit certain hard-coded values like
session_start(). When you use PHP namespaces, however, you can solve this problem in an elegant way.
- Manuel StrehlMinimal contents of a .git folderWhat does a minimal usable .git folder looks like? Let’s see.
-.
- Manuel StrehlPage Layout ExperimentThis small experiment allows to try out interactively the so-called Gutenberg canon for page layout on different page sizes.
-. | http://www.manuel-strehl.de/dev/index.en.html | CC-MAIN-2017-47 | en | refinedweb |
So, I'm a big fan of creating global namespaces in javascript. For example, if my app is named Xyz I normally have an object XYZ which I fill with properties and nested objects, for an example:
XYZ.Resources.ErrorMessage // = "An error while making request, please try again"
XYZ.DAL.City // = { getAll: function() { ... }, getById: function(id) { .. } }
XYZ.ViewModels.City // = { .... }
XYZ.Models.City // = { .... }
// route.js file
var cityModel = require('./models/city');
var cityService = require('./services/city');
app.get('/city', function() { ...........});
XYZ.Models.City = require('./models/city');
XYZ.DAL.City = require('./services/city');
// route.js file
var cityModel = XYZ.Models.City;
var cityService = XYZ.DAL.City;
app.get('/city', function() { ...........});
I think that's a bad idea, because you are going to serve a ton of modules every single time, and you may not need them always. Your namespaced object will get quite monstrous.
require will check the module cache first, so I'd use standard requires for each request / script that you need on the server. | https://codedump.io/share/p86HCG7OMU65/1/nodejs-single-object-with-all-requires-or-quotstandardquot-paths-in-code | CC-MAIN-2017-47 | en | refinedweb |
querylocale(3) BSD Library Functions Manual querylocale(3)
NAME
querylocale -- Get locale name for a specified category
SYNOPSIS
#include <xlocale.h> const char * querylocale(int mask, locale_t loc);
DESCRIPTION
Returns the name of the locale for the category specified by mask. The mask is scanned starting at the least significant bit, until the first set bit is found. This happens to scan the categories alphabetically, not including LC_ALL_MASK, but it is best to specify one category at a time. The available categories are documented in xlocale(3) and newlocale(3).
SEE ALSO
duplocale(3), freelocale(3), newlocale(3), uselocale(3), xlocale(3) BSD March 11, 2005 BSD
Mac OS X 10.8 - Generated Thu Aug 30 10:53:54 CDT 2012 | http://www.manpagez.com/man/3/querylocale/ | CC-MAIN-2017-47 | en | refinedweb |
Hi and thanks in advance for helping me out. I am writing a class in C++ called PolyLine.cc I am supposed to include prototypes for all my methods in a header file (PolyLine.h). I am working on a unix server using the GNU compiler.
I have experience in Java and a little in C but this is my first real C++ program. So far my PolyLine.h file looks like this:
#ifndef PolyLine_h
#define PolyLine_h
#include <iostream.h>
class PolyLine
{
public:
ostream & operator <<(ostream& os, const PolyLine& p1);//operator <<
PolyLine(double *x, double *y, int len);// c-tor
PolyLine(const PolyLine& src);//copy c-tor
PolyLine& operator=( PolyLine& src);// operator =
~PolyLine ();//d-tor
int points();
double value(double x);
double max();
double max(double x1, double x2);
private:
double *xArray;
double *yArray;
int length;
};
#endif
and my PolyLine.cc file looks like this:
#include "PolyLine.h"
#include <iostream.h>
ostream& operator <<(ostream& os, const PolyLine& p1)
{return os;}
int points(){}
double value(double x){}
double max(){}
double max(double x1, double x2){}
PolyLine::PolyLine(double *x, double *y, int len){}
PolyLine::PolyLine(const PolyLine& src){}
PolyLine PolyLine& ::operator=( PolyLine& src)
{return *this;}
PolyLine::~PolyLine () {}
as you can see I have left the methods all empty in hopes of compiling it first and then expanding on it later but the complier returns the following error (borg is the name of the server I am working from):
borg:~/cs3132/a2$ g++ PolyLine.cc
In file included from PolyLine.cc:1:
PolyLine.h:8: `PolyLine::operator <<(ostream &, const PolyLine &)' must take exactly one argument
PolyLine.cc:12: syntax error before `&'
I am sure that operator << can take more than one argument, not sure why I am getting this error. If someone out there can help me, please do! =)
thank you very much for your time in any event. Happy coding | https://cboard.cprogramming.com/cplusplus-programming/2296-simple-class-header-file-printable-thread.html | CC-MAIN-2017-47 | en | refinedweb |
I dont understand why my code does not work. Here it is:
n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
print x[i]
It returns an error message saying " It looks like you either didn't call print_list(n) or there is something wrong because 3 wasn't printed."
Any help is more than appreciated!
Well you didn't call print_list, you created this function but so far you didn't use it. Also have a look at this:As indents are part of the syntax in python it is important that you display code as code and not as plain text.
Hi, thank you for your answer. I tryied that but it didn't work either.
n = [3, 5, 7]def print_list(x):----for i in range(0, len(x)):--------print x[i]print print_list(x)
Sorry, I changed x for n and worked, I don't really understand why.
As said see the link on how to format your code
```
code
```
And about the rest. Well what you enter at the () when calling the function is assigned to the variable in the () of the function definition. So in this case the list n gets assigned to the parameter x. Also you don't need a print before print_list as it doesn't return a value and has its own print statement inside.
Hi, thank you again.I was trying to follow the instructions of the exercise since I have difficulty with programming. I actually don't understand much of what I do but I'm trying.Thank you for your help.
If something is unclear you can for example test it here: see how it is executed here: just ask questions here.
Hi I had the same issue, the function wouldn't take "x" or "num" or whatever else I could think of as an argument. In the end I tried the "v" and that worked out... The instructions were somewhat misleading for this particular exercise. Instructions are usually remarkably clear otherwise.
Thank you for these links! They are very helpful for double checking that I actually know what's going on with the code.
Hello guys, I don't know what wrong in the following code:Please can somebody help me on this
Even i had the same issue and this worked for me
n = [3, 5, 7]
def print_list(v): for i in range(0, len(v)): print v[i]
print_list(n)
This is what what I did and it worked
def print_list(x): --for i in range(0, len(x)): -----print x[i]
print print_list(n)
I don't know what kind of problem you can call this but after making my code shorter it kind of worked. What I did is (as you can see from the screen shot that I posted earlier) I deleted the commented part from the code from line 2 to 4 and thus reduced the length of the code to 6 lines. What a frustrating thing. Even though the code was correct it didn't used work. At last I got it correct. So I don't think there is a need to change x to v or num or anything else..
thank you, you helped me figure out a simple error i made in my program.
you probably just have to delete the commented lines.
I had the same issue.. no change to the code I wrote, just had to remove the existing comments, which shouldn't have any affect at all.
That is because you didn't really call that function to be used.Your code should look like this:
def print_list(x): for i in range(0, len(x)): print x[i]print_list(n)
I tried commenting the "scaffolding" out and was still getting the "the body of your function should not contain any references to n" error. Deleting that scaffolding fixed it. This lesson is bugged.
That did it for me, it is a bug. Thanks
you are missing calling for print for print_list(n) | https://discuss.codecademy.com/t/12-printing-out-a-list-item-by-item-in-a-function-error/26323 | CC-MAIN-2017-47 | en | refinedweb |
I want select all the elements of this array that begin with a. Here is my code
a = ['bananas', 'apples', 'pears', 'avocados']
def select_elements_starting_with_a(a)
a.select { |str| str.start_with?('a') }
end
puts select_elements_starting_with_a
Untitled.rb:3:in `select_elements_starting_with_a': wrong number of arguments (0 for 1) (ArgumentError)
from Untitled.rb:6:in `<main>'
@Ursus and @Adam are right. But there is another point I'd like to make.
When you are programming, the way you name things sometimes show how clear is the definition of the problem in you mind. You've made this small confusion probably because
a takes many roles in your code:
a is the name of the array with the names of the fruits;
a is also the name of the formal parameter used by your method.
Besides, this method is very specific. Too specific to be good, I must tell you. Assume your program should later identify all elements starting with letter b. I'd have to create another method, with almost the same code.
My suggestion, to make your code really reusable redefining the method as
def select_elements_starting_with(arr,letter) arr.select { |str| str.start_with?(letter) } end
Now you may find elements starting with ANY letter in ANY array, and you won't risk forgeting to pass the paramenter because you'll make no confusion between the formal parameter and the real array instance being processed. | https://codedump.io/share/vuOxQfDzZzw7/1/select-elements-from-an-array-starting-with-a-certain-character | CC-MAIN-2017-47 | en | refinedweb |
Pointer analysis.
This class is the main analysis class for pointer detection. See the Rose::BinaryAnalysis::PointerDetection namespace for details.
Definition at line 165 of file BinaryPointerDetection.h.
#include <BinaryPointerDetection.h>
Default constructor.
This creates an analyzer that is not suitable for analysis since it doesn't know anything about the architecture it would be analyzing. This is mostly for use in situations where an analyzer must be constructed as a member of another class's default constructor, in containers that initialize their contents with a default constructor, etc.
Definition at line 184 of file BinaryPointerDetection.h.
Construct an analysis using a specific disassembler.
This constructor chooses a symbolic domain and a dispatcher appropriate for the disassembler's architecture.
Definition at line 190 of file BinaryPointerDetection.h.
Construct an analysis using a specified dispatcher.
This constructor uses the supplied dispatcher and associated semantic domain. For best results, the semantic domain should be a symbolic domain that uses MemoryCellList and RegisterStateGeneric. These happen to also be the defaults used by InstructionSemantics2::SymbolicSemantics.
Definition at line 201 of file BinaryPointerDetection.h.
Property: Analysis settings.
Returns the settings that are being used for this analysis. Settings are read-only, initialized by the constructor.
Definition at line 208 of file BinaryPointerDetection.h.
Analyze one function.
This analysis method uses Partitioner2 data structures which are generally faster than using the AST. The specified function need not be attached to the partitioner. Results of the analysis are stored in this analysis object to be queried after the analysis completes.
Whether a function has been analyzed.
Returns true if this analysis object holds results from analyzing a function. The results might be only approximations depending on whether didConverge also returns true.
Definition at line 221 of file BinaryPointerDetection.h.
Whether the analysis results are valid.
Returns true if hasResults is true and the analysis converted to a solution. If the analysis did not converge then the other results are only approximations.
Definition at line 227 of file BinaryPointerDetection.h.
Clear analysis results.
Resets the analysis results so it looks like this analyzer is initialized but has not run yet. When this method returns, hasResults and didConverge will both return false.
Clears everything but results.
This resets the virtual CPU to the null pointer, possibly freeing some memory if the CPU isn't being used for other things. Once the CPU is removed it's no longer possible to do more analysis with this object.
Property: Code pointers.
These are memory addresses that store a value that was used to initialize the instruction pointer register. If
sort is true then the return value is sorted lexically.
Definition at line 245 of file BinaryPointerDetection.h.
Property: Data pointers.
These are memory addresses that store a value that was used as an address to dereference other memory. If
sort is true then the return value is sorted lexically.
Definition at line 253 of file BinaryPointerDetection.h.
Initial state for analysis.
Returns symbolic state that initialized the analysis. This is the state at the function entry address and is reinitialized each time analyzeFunction is called. This state is cleared by calling clearNonResults, after which this function returns a null pointer.
Definition at line 262 of file BinaryPointerDetection.h.
Final state for analysis.
Returns the symbolic state for the function return point. If the function has multiple return points then this is the state resulting from merging the states after each return. This state is initialized by calling analyzeFunction. It is cleared by calling clearNonResults, after which it returns a null pointer.
Definition at line 271 of file BinaryPointerDetection.h. | http://rosecompiler.org/ROSE_HTML_Reference/classRose_1_1BinaryAnalysis_1_1PointerDetection_1_1Analysis.html | CC-MAIN-2017-47 | en | refinedweb |
We don't always need to loop through the whole list in the first place.
I believe most of us are using the two pointers. So if k is greater than the list's length, the fast pointer will iterate to the end of the list while iterating from 1 to k. And at this point we know the length of the list, which equals i (current iteration times). Then we could set i to 0 and k to k%i and iterate again. For long list and a small 'k', this code would work a bit faster.
Codes:
public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next==null || k==0){return head;} ListNode fast = head; ListNode slow = head; for(int i=1;i<=k;i++){ fast = fast.next; if(fast == null){fast=head;k=k%i;i=0;} } while(fast.next!=null){ fast = fast.next; slow = slow.next; } fast.next = head; ListNode newHead=slow.next; slow.next = null; return newHead; } }
But aren't you iterating through the whole list when you do
for(int i=1;i<=k;i++){
fast = fast.next;
if(fast == null){fast=head;k=k%i;i=0;}
}
while(fast.next!=null){
fast = fast.next;
slow = slow.next;
}
So at least one iteration is required right?
@neha25
You're absolutely right. I think we always need to iterate the list at least once. But most solutions I saw here iterate the whole list first to get the length of the list which I think is unnecessary. That's why I think my solution will be a bit faster for a long list with a small 'k'.
Thanks! | https://discuss.leetcode.com/topic/52681/java-1ms-solution-without-iterating-the-whole-list-first | CC-MAIN-2017-47 | en | refinedweb |
Name
CYGPKG_DEVS_FLASH_M68K_MCFxxxx_CFM — eCos Flash Driver for MCFxxxx CFM On-chip Flash
Description
Some members of the Freescale MCFxxxx family, for example the MCF5213,
come with on-chip flash in the form of a ColdFire Flash Module or CFM.
This package
CYGPKG_DEVS_FLASH_M68K_MCFxxxx_CFM
provides an eCos flash device driver for CFM hardware. Normally the
driver is not accessed directly. Instead application code will use the
API provided by the generic flash driver package
CYGPKG_IO_FLASH, for example by calling functions
like
cyg_flash_program.
Configuration Options
The CFM flash driver package will be loaded automatically when
configuring eCos for a target with suitable hardware. However the
driver will be inactive unless the generic flash package
CYGPKG_IO_FLASH is loaded. It may be necesary to
add this generic package to the configuration explicitly before the
driver functionality becomes available. There should never be any need
to load or unload the CFM driver package.
The driver contains a small number of configuration options which application developers may wish to tweak.
Misaligned Writes
The CFM hardware only supports writes of a whole 32-bit integer at a
time. For most applications this is not a problem and the driver
imposes this restriction on higher-level code, so when calling
cyg_flash_program the destination address must be
on a 32-bit boundary and the length must be a multiple of four bytes.
If this restriction is unacceptable then support for misaligned writes
of arbitrary lengths can be enabled via configuration option
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_MISALIGNED_WRITES.
The implementation involves reading in the existing flash contents and
or'ing in the new data. The default behaviour is to leave this
disabled since most applications do not require the functionality and
it just adds to the code size.
Locking
CFM has a somewhat unusual approach to implementing lock and unlock
support. The first 1K of on-chip flash is normally reserved for the
M68K exception vectors, on the assumption that the processor will or
may boot from here. This is immediately followed by a
hal_mcfxxxx_cfm_security_settings data
structure at offset 0x400. The structure has a 32-bit field
cfm_prot which determines the initial
locking status. The whole CFM flash array is split into 32 sectors.
Each bit in
cfm_prot determines the initial
locked state of all blocks within that sector, with 1 for locked and 0
for unlocked. Locking and unlocking can only affect a whole sector at
a time, not individual flash blocks (unless of course the flash is
organized such that there exactly 32 flash blocks).
In typical usage the on-chip flash will be used for bootstrap and hence the security settings are part of the boot image. The default security settings are supplied by the processor or platform HAL and will be such that all flash sectors are unlocked. This is the most convenient setting when developing software. However an application can override this and thus lock part or all of the flash.
The driver provides two configuration options related to flash
locking.
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_AUTO_UNLOCK
causes all of flash to be unlocked automatically during driver
initialization. This gives simple and deterministic behaviour
irrespective of the current contents of the flash security settings
structure. However it leaves the flash more vulnerable to accidental
corruption by an errant application.
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_SUPPORT_LOCKING
enables support for fine-grained locking using the generic functions
cyg_flash_lock and
cyg_flash_unlock. This provides more protection
against errant applications, at the cost of increased application
complexity.
RAM Functions and Interrupts
When performing a flash erase or program operation part or all of the flash may become inaccessible. The exact details of this vary between ColdFire processors. Obviously this means that the low-level functions which manipulate the flash cannot reside in the same area of flash as any blocks that may get erased or programmed. Worse, if an interrupt happens during an erase or program operation and the interrupt handler involves code or data in the same area of flash, or may cause a higher priority thread to wake up which accesses that area of flash, then the system is likely to fail. To avoid problems the flash driver takes two precautions by default:
- The low-level flash functions are located in RAM. If necessary they are copied from ROM from RAM during system initialization.
- The low-level flash functions disable interrupts around any code which may leave parts of the flash inaccessible.
This combination avoids problems but at the cost of increased RAM
usage and often increased interrupt latency. In some circumstances
these precautions are unnecessary. For example suppose there is 512K
of flash split into two logical blocks of 256K each, such that an
erase or program operation affects all of one logical block but not
the other. If the application has been arranged such that all code and
constant data resides in the bottom 256K and flash operations are only
performed on the remaining 256K then there is no need to place the
low-level flash functions in RAM. The configuration option
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_FUNCTIONS_IN_RAM
can then be disabled. In a similar scenario, if the top 256K of flash
are only ever accessed via the flash API then there is no need to
disable interrupts: the generic flash layer ensures only one thread
can perform flash operations on a given device via a mutex. The
configuration option
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_LEAVE_INTERRUPTS_ENABLED
can then be enabled.
Additional Functionality
The driver exports two functions which offer functionality not accessible via the standard flash API:
#include <cyg/io/mcfxxxx_cfm_dev.h> externC void cyg_mcfxxxx_cfm_unlockall(void); externC cyg_bool cyg_mcfxxxx_cfm_is_locked(const cyg_flashaddr_t addr);
The first can be used to unlock all flash sectors, effectively bypassing any locking set by the hal_mcfxxxx_cfm_security_settings structure. The second can be used to query whether or not the block containing the specified address is currently locked. Both functions should be called only after flash has been initialized.
Instantiating a CFM Flash device
The CFM package only provides the device driver functions needed for manipulating CFM flash. It does not actually create a device instance. The amount of on-chip flash varies between ColdFire processors and the driver package does not maintain any central repository about the characteristics of each processor. Instead it is left to other code, usually the processor HAL, to instantiate the flash device. That makes it possible to add support for new processors simply by adding a new processor HAL, with no need to change the flash driver package.
The CFM package provides a utility macro for instantiating a device. Typical usage would be:
#include <cyg/io/mcfxxxx_cfm_dev.h> CYG_MCFxxxx_CFM_INSTANCE(0x00000000, 0x0003FFFF, 2048);
The first two arguments specify the base and end address of the flash in the memory map. In this example there is 256K of flash mapped to location 0. Typically the base address is set via the FLASHBAR system register and the size is of course determined by the specific ColdFire processor being used. The final argument is the size of a flash block, in other words the unit of erase operations. This will have to obtained from the processor documentation.
The
CYG_MCFxxxx_CFM_INSTANCE macro may
instantiate a device with or without software locking support, as
determined by the driver configuration option
CYGIMP_DEVS_FLASH_M68K_MCFxxxx_CFM_SUPPORT_LOCKING
.
If for some reason the
CYG_MCFxxxx_CFM_INSTANCE
is inappropriate for a specific processor then the mcfxxxx_cfm_dev.h
header file exports all the device driver functions, so code can
create a flash device instance explicitly. | http://doc.ecoscentric.com/ref/mcfxxxx-cfm.html | CC-MAIN-2019-30 | en | refinedweb |
hi all,
I am trying to create a most simple 1 linear layer network to fit a linear regression. Just to help myself better understand how Pytorch works. However, I encountered a strange issue with the model training.
in my model’s init() method, I have to add a manual initialization step(shown below) to have the model quickly converge to my regression function. (the weight value 2, 3 are random number, I could put any value here and the model will still converge)
self.layer1.weight = torch.nn.Parameter(torch.Tensor([2, 3]))
Without this line, the model never converge, the training loss just randomly oscillates in the range of hundreds of thousands. With this line, it quickly decreases to near 1.
I have postulated that it is because default initial weight parameters were too small if I do not initialize them to be far away from zero. Then I changed the initial values and found out the convergence always work as long as I have this line, the exact value I set does not matter. Could someone explain what is going on behind the scene here? Thanks.
My entire script:
import torch import numpy as np class Net(torch.nn.Module): def __init__(self, input_dim, output_dim): super(Net, self).__init__() self.layer1 = torch.nn.Linear(input_dim, output_dim, bias=False) self.layer1.weight = torch.nn.Parameter(torch.Tensor([2, 3])) def forward(self, x): x = self.layer1(x) x.squeeze() return x # generate data using the linear regression setup y = 5 * x1 + 3 * x2 sample_size = 10000 input_dim = 2 output_dim = 1 epoch = 30 bs = 100 data = np.random.randn(sample_size, 3) data[:, :2] = data[:, :2] * 100 # add a normal noise term data[:, 2] = 5 * data[:, 0] + 3 * data[:, 1] + np.random.randn(sample_size) data = torch.Tensor(data) train_x = data[:, :input_dim] train_y = data[:, input_dim] net = Net(input_dim, output_dim) net.zero_grad() criterion = torch.nn.MSELoss() optimizer = torch.optim.RMSprop(net.parameters(), lr=.01) for i in range(epoch): batch = 0 while batch * bs < train_x.shape[0]: batch_x = train_x[batch * bs : (batch + 1) * bs, :] batch_y = train_y[batch * bs : (batch + 1) * bs] pred_y = net.forward(batch_x) loss = criterion(pred_y, batch_y) optimizer.zero_grad() loss.backward() optimizer.step() if batch % 100 == 0: #print(f"{i} {batch} {loss}") print(net.layer1.weight) batch += 1 | https://discuss.pytorch.org/t/why-the-model-fail-to-converge-without-a-manul-weight-initialization/50431 | CC-MAIN-2019-30 | en | refinedweb |
Hello Andrew,After the discussion with Eric and Vivek the following patchseems to be a good solution to me. Could you accept this patch?When two CPUs call panic at the same time there is apossible race condition that can stop kdump. The firstCPU calls crash_kexec() and the second CPU callssmp_send_stop() in panic() before crash_kexec() finishedon the first CPU. So the second CPU stops the first CPUand therefore kpanic that allows only one CPU to process crash_kexec() andthe subsequent panic code.Signed-off-by: Michael Holzheu <holzheu@linux.vnet.ibm.com>--- kernel/panic.c | 8 ++++++++ 1 file changed, 8 insertions(+)--- a/kernel/panic.c+++ b/kernel/panic.c@@ -59,6 +59,7 @@ EXPORT_SYMBOL(panic_blink); */ NORET_TYPE void panic(const char * fmt, ...) {+ static DEFINE_SPINLOCK(panic_lock); static char buf[1024]; va_list args; long i, i_next = 0;@@ -82,6 +83,13 @@ NORET_TYPE void panic(const char * fmt, #endif /*+ * Only one CPU is allowed to execute the panic code from here. For+ * multiple parallel invocations of panic all other CPUs will wait on+ * the panic_lock. They are stopped afterwards by smp_send_stop().+ */+ spin_lock(&panic_lock);++ /* * If we have crashed and we have a crash kernel loaded let it handle * everything else. * Do we want to call this before we try to display a message? | https://lkml.org/lkml/2011/10/26/153 | CC-MAIN-2019-30 | en | refinedweb |
You want to match all section headers in an INI file.
This one is easy. INI section headers appear at the beginning of
a line, and are designated by placing a name within square brackets
(e.g.,
[Section1]). Those rules are
simple to translate into a regex:
^\[[^\]\r\n]+]
There aren’t many parts to this regex, so it’s easy to break down:
The leading ‹
^› matches the position at the beginning of
a line, since the “^ and $ match at line breaks” option is
enabled.
‹
\[› matches a
literal
[ character. It’s
escaped with a backslash to prevent
[ from starting a character
class.
‹
[^\]\r\n]› is
a negated character class that matches any character except
], a carriage return (
\r), or a line feed (
\n). The immediately following ‹
+› quantifier lets the class
match one or more characters, which brings us to....
The trailing ‹
]› matches a literal
] character to end the section header.
There’s no need to escape this character with a backslash because
it does not occur within a character class.
If you only want to find a specific section header, that’s even
easier. The following regex matches the header for a section called
Section1:
^\[Section1]
In this case, the only difference from a plain-text search for “[Section1]” is that the match must ...
No credit card required | https://www.oreilly.com/library/view/regular-expressions-cookbook/9780596802837/ch08s12.html | CC-MAIN-2019-30 | en | refinedweb |
public class Scope extends java.lang.Object
A Scope defines a SINGLE THREADED local lifetime management context,
stored in Thread Local Storage. Scopes can be explicitly entered or exited.
User keys created by this thread are tracked, and deleted when the scope is
exited. Since enter & exit are explicit, failure to exit means the Keys
leak (there is no reliable thread-on-exit cleanup action). You must call
Scope.exit() at some point. Only user keys & Vec keys are tracked.
Scopes support nesting. Scopes support partial cleanup: you can list Keys you'd like to keep in the exit() call. These will be "bumped up" to the higher nested scope - or escaped and become untracked at the top-level.
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
public Scope()
public static void enter()
public static Key[] exit(Key... keep)
public static Key[] pop()
public static <T extends Keyed> Keyed<T> track_generic(Keyed<T> keyed)
public static Vec track(Vec vec)
public static Frame track(Frame... frames)
Frames, and return the first one. The tracked frames will be removed from DKV when
exit(Key[])is called.
public static void untrack(Key<Vec>... keys)
public static void untrack(java.lang.Iterable<Key<Vec>> keys) | http://docs.h2o.ai/h2o/latest-stable/h2o-core/javadoc/water/Scope.html | CC-MAIN-2019-30 | en | refinedweb |
The
Find / Hey: down to find "hey" / [Az]: look down to find lower case letters, enter n: Find next match at the input after the N: the last match at the ? Hey: look up "hey" Replace : S / vim / vi: vim replace the next vi :% S / vim / vi
case letters, linux, vim, lower case, last matchJuly 27
mysqld process - the directory and file references basedir = path Use the given directory as the root directory (installation directory). character-sets-dir = path gives the store a character set directory. datadir = path from a given directory to re
default character, case letters, windows environment, server communication, table names, unix linux, linux systems, collation, language settings, default sort, process id, process communication, windows 2000 xp, set option, socket option, mysql client, set directory, security reference, compatible with earlier versions, communication networkingJuly 15
Author: Zhou Sibo (Joel Spolsky) Translation: Chen Bin 2001 Year in January 27 Today In 1982, my family ordered the IBM PC (IBM produced the first personal computer, the standardization of modern popular personal computers ancestors). Our family may
case letters, language development, joel spolsky, ancillary equipment, chen bin, pascal language, first personal computer, pc dos, import duties, assembly language compiler, sibo, daisy wheel printer, dot matrix printer, machine gun fire, pascal compilers, pin dot matrix, mechanical typewriters, computer translator, draft printing, pc ibmJuly 3
oracle regular expression (regular expression) briefly present, the regular expression has a lot of software is widely used, including * nix (Linux, Unix, etc.), HP and other operating system, PHP, C #, Java and other development environments. Oracle
square brackets, case letters, regular expression, substr, input string, newline, positive integer, regexp object, instr, string position, lower case, occurrences, effective solution, new location, posix, development environments, multiline property, blank check, precise number, word identificationJune 1
oracle regular expression (regular expression) briefly present, the regular expression has a lot of software is widely used, including * nix (Linux, Unix, etc.), HP and other operating systems, PHP, C #, Java and other development environment. Oracle
square brackets, case letters, regular expression, substr, input string, positive integer, regexp object, decomposition, instr, string position, oracle 10g, lower case, occurrences, effective solution, posix, percent sign, multiline property, data availability, precise range, word identificationJune 1
shell convert uppercase and lowercase letters 2008-05-07 10:25 #! / Bin / sh #------------------------------------------------- --------- # [: Upper:] [A - Z] # [: Lower:] [a - z] # [: Digit:] [0 - 9] # [: Alnum:] [0 - 9 a - z AZ] # [: Space:] Space
quot quot, case letters, file names, lowercase letters, abcdefghijklmnopqrstuvwxyz, mv, upper case, space space, case file, shell caseMay 10
racle regular expression oracle regular expression (regular expression) a brief Currently, the regular expression has been widely in many software applications, including * nix (Linux, Unix, etc.), HP and other operating system, PHP, C #, Java and ot
square brackets, case letters, regular expression, substr, input string, positive integer, regexp object, instr, string position, lower case, occurrences, effective solution, posix, newline character, development environments, locati, multiline property, blank check, precise number, word identificationApril 28
Transfer from: MaDe1nZEAL In MySQL, databases and tables on those directories to the directory and files. Thus, the operating system, database and determine the sensitivity of the case sensitive table name. This means d
alias, parameters, configuration file, database name, scripts, case letters, system database, operating system, capital letters, table names, column names, operating systems, lower case, strange thing, mysql databases, case sensitivity, aliases, unix systems, uppercase characters, reservation statusJanuary 12
ORACLE regular expression support in the following four main functions: 1, REGEXP_LIKE: similar to the LIKE function 2, REGEXP_INSTR: INSTR function with similar 3, REGEXP_SUBSTR: SUBSTR function with similar 4, REGEXP_REPLACE: REPLACE function with
square brackets, oracle sql, case letters, regular expression, lowercase letters, input string, capital letters, positive integer, regexp object, string position, oracle 10g, lower case, letters and numbers, meta characters, technical exchange, posix, newline character, hexadecimal number, multiline property, precise numberJanuary 11
ORACLE regular expressions in the following four main functions: 1, REGEXP_LIKE: similarities with the LIKE function 2, REGEXP_INSTR: INSTR function with similar 3, REGEXP_SUBSTR: SUBSTR function with similar 4, REGEXP_REPLACE: similarities with the
square brackets, oracle sql, case letters, regular expression, lowercase letters, input string, capital letters, positive integer, regexp object, string position, oracle 10g, letters and numbers, meta characters, posix, percent sign, hexadecimal numbers, newline character, multiline property, technology exchange, precise rangeJanuary 11
concat () - two or more combinations of text characters and returns a new string. indexOf () - returns a substring in the string appears at the first index. If no match, returns -1. charAt () - Returns the character position. lastIndexOf () - Returns
return string, case letters, match, array, regular expression, checks, string search, substring, combinations, string manipulation functions, lower case, charat, character positionDecember 22
Web Production specification: A: naming convention 01: File naming principles: the letters to at least the most easily understood meaning. General file and directory naming conventions: Each directory should contain a default html file, the file name
quot, naming convention, case letters, file names, analogy, title news, naming conventions, lower case, decorative patterns, letters and numbers, file extension, english letters, web production, cgi programs, aboutus, banner ads, example banner, logo police, gif logo, image categoriesDecember 18
Original Address: File and directory naming conventions All lower case, must be a word or product name in English spelling, more than one word with a hyphen (-) connection. Appe
chinese version, naming convention, source file, case letters, js, gbk, new projects, class names, naming conventions, html css, taobao, independent development, lower case, chinese pinyin, uniform application, gif jpg, suitable name, kissy, performance supplement, hyphenated wordsDecember 17
Written test and interview study computer is the most common variety of string operations. String handling daily work of our programmers the most common problems that can reflect the basic skills of programmers. I have since last month following a va
lt, null return, google, case letters, programmers, malloc, string operations, lowercase letters, capital letters, lower case, abd, sizeof, strcpy, simple questions, strlen, english alphabet, interview study, interview column, dhz, study computerDecember 6
Principle: ASCII code: ASCII American Standard Code for Information Interchange is short. 7-bit ASCII code is the base 2 yards, a total of 128, and its ranking as the b6 b5 b4 b3 b2 b1 b0, where the high part of the b6 b5 b4, b3 b2 b1 b0 for the lowe
string args, main string, case letters, character encoding, c amp, american standard, b0, alphabetical order, correspondence, lower case, case package, american standard code for information interchange, char c, b2, ascii code, uppercase, conversion rules, b5, case conversion, code asciiDecember 4
Note! Case letters on BSD is completely different. telnet connection to the specified host (can be IP or host name). telnet 210.240.119.251 or telnet bbs.pnjh.ttct.edu.tw exit to leave the currently connected host, Or exit the current incarnation of
space bar, case letters, host name, directory copy, home directory, hosts, tw, working environment, ditto, directory cd, temp directory, mv, file attributes, note case, directory ls, bsd, wheel group, telnet connection, incarnation, resoNovember 29
Attention! Case letters in the BSD are completely different. telnet connection to the specified host (can be IP or host name). telnet 210.240.119.251 or telnet bbs.pnjh.ttct.edu.tw exit to leave the current connection of the host, Or exit the current
space bar, case letters, host name, directory copy, home directory, root directory, tw, working environment, ditto, directory cd, temp directory, mv, directory ls, current connection, bsd, wheel group, page pause, telnet connection, incarnation, resoNovember 29
When the program was doing some coding problems will inevitably arise, if there is some understanding of the character code, that would be handy to solve some of the time Speaking from the ASCII code Speaking of character encoding, have to say a brie
character code, case letters, maximum number, character encoding, 8 bits, de facto standard, different computer, ambiguity, processing unit, ascii code, ascii codes, digital computing, brief history, octet, ascii character set, modern computer, bit group, parity, invention of the computer, bit bytesNovember 17
Configure Tomcat to use SSL so the following two main steps: First, generate a certificate 1, the command line, execute:% Java_home% \ bin \ keytool-genkey-alias tomcat-keyalg RSA In this command, keytool is generating the certificate that comes with
lt, alias, configuration file, case letters, element, home directory, compatibility, file server, connector port, lower case, coyote, changeit, jdk tools, contact name, rsa algorithm, secure socket, company contact, certificate password, security algorithm, enter keyNovember 10
1, strlen () / / get string length function 2, ltrim () / / remove the string on the left of the box 3, rtrim () / / remove the string to the right of space 4, trim () / / remove the spaces on both sides of the string 5, strrev () / / reverse the ord
quot, demo, case letters, string length, lowercase, lower case, result string, uppercase letters, word string, strrevNovember 10
<! DOCTYPE HTML PUBLIC "- / / W3C / / DTD XHTML 1.0 Transitional / / EN" " "> <HTML xmlns = " "> <head> <meta http-equi
lt, amp, quot quot, case letters, prototype, content type, text html, meta, html xmlns, transitional dtd, images, gb2312, new image, doctype html public, tolowercase, px, lower case, upload pictures, fileextNovember 3
] [Switched Character encoding of the problem seems small, often overlooked by technical staff, but can easily lead to some strange problems. I came up with a bit universal character en
case letters, character encoding, 8 bits, de facto standard, different computer, ambiguity, processing unit, strange problems, ascii code, binary stream, ascii codes, digital computing, octet, ascii character set, modern computer, bit group, universal character, parity, invention of the computer, bit bytesOctober 30
ORACLE regular expression support in the following four main functions: 1, REGEXP_LIKE: similar to the LIKE function 2, REGEXP_INSTR: INSTR function with similar 3, REGEXP_SUBSTR: SUBSTR function with similar 4, REGEXP_REPLACE: they are similar with
square brackets, oracle sql, case letters, regular expression, lowercase letters, input string, capital letters, positive integer, regexp object, string position, lower case, letters and numbers, occurrences, meta characters, posix, newline character, hexadecimal number, multiline property, sql functions, precise numberOctober 29
Aix ftp-v-d-i-n-g [host name], where -V displays all remote server response information; Ftp-n limit the automatic login, which is not used;. N etrc documents; -D Use debugging mode; -G to cancel the global file names. Aix ftp command uses the intern
case letters, system resources, file names, host name, carriage return, server response, remote server, default mode, chmod 777, transfer mode, host file, automatic login, ftp command, macro name, interactive shell, mget, computer beep, etrc, disconnection, open mappingOctober 28
Note: The Wikipedia and Baidu moon from the blog Regular expression for string processing, form validation, and so on, practical and efficient. Here are some symbols and the corresponding description: Metacharacter Description Dot (.) Match any singl
case letters, regular expressions, brackets, match, parentheses, form validation, regular expression, expression string, wikipedia, intervals, complement, uppercase letters, hyphen, wildcard characters, dollar sign, dot character, weasels, when in the course of human events, aou, weaselOctober 25
Naming File naming principle: the letters to achieve the most with the least easy to understand the meaning. General file and directory naming conventions: Each directory should contain a default html file, the file name index.htm unified with the Un
quot, naming convention, case letters, file names, analogy, title news, naming conventions, lower case, decorative patterns, letters and numbers, digits, file extension, english letters, cgi programs, aboutus, banner ads, example banner, logo police, gif logo, image categoriesOctober 22
Download: mysql files are installed: the first server installed after the client installation MySQL-server-5.1.51-1.glibc23.i386.rpm MySQL-client-5.1.51-1.glibc23.i386.rpm rpm-ivh MySQL-server-5.1.51-1.gl
lib, case letters, match, existence, server side, complete solution, conflicts, rpm, linux, presence, lower case, arabic numerals, tragedy, version conflict, column countOctober 21
Two very cattle vim tips (1) Please note before reading this article: 1. This paper aims to provide skills in the use of vim, vim use of these techniques can improve operational efficiency. Some skills can also be used in vi, but now basically use th
operational efficiency, case letters, circumstances, lt c, command mode, copy and paste, cursor, collation, efficient use, arrow keys, vim tips, visual mode, cv, cattle, yy, right arrow, zc, yw, relevant letterOctober 20
Write a program that outputs a string in the number of uppercase letters, lowercase letters, and the number of non-English letters. Write a method, the output in a string that specifies the number of occurrences of the string. The Liezi defines a Str
lt, import java, java util, amp, public void, println, main string, case letters, string object, test class, capital letters, indexof, lower case, char c, occurrences, scanner, uppercase letters, charat, english letters, indexsOctober 17
Overall still very valuable, and some places do not agree. Preface The specification for web developers to write, read before you learn some XHTML, CSS basic knowledge to facilitate the understanding of written content. The purpose of this specific
personal habits, naming convention, directory name, case letters, web developers, web interface, special circumstances, root directory, css style, basic knowledge, backup files, high efficiency, quick time, different places, lower case, public documents, multimedia files, directory images, catalog images, efficiency productionOctober 14
One-way function characteristics: 1, the single function of the single-line operation 2, each line returns a result 3, it is possible to return values consistent with the original parameters of data type (conversion function) 4, one-way function can
column name, parameters, case letters, type conversion, single line, substr, substring, date function, lower case, conversion function, character length, string head, parameter type, character format, type case, n2, case conversion, case characters, check character, upper columnOctober 14
Quote oracle regular expressions (10g only available) oracle regular expression (regular expression) briefly present, the regular expression has a lot of software is widely used, including * nix (Linux, Unix, etc.), HP and other operating systems, PH
square brackets, case letters, regular expression, substr, input string, positive integer, regexp object, decomposition, instr, string position, oracle 10g, lower case, occurrences, effective solution, posix, percent sign, multiline property, data availability, precise range, word identificationOctober 7
FTP commands are Internet users one of the most frequently used commands, both in DOS or UNIX operating system using FTP, FTP will encounter a large number of internal commands. Familiar and flexible application of the internal FTP commands, can grea
case letters, carriage return, server response, multiplier effect, chmod 777, host file, automatic login, flexible application, ftp command, macro name, interactive shell, unix operating system, ftp commands, mget, computer beep, format ftp, internal ftp, etrc, command ftp, open mappingSeptember 28
1. New students - curriculum database three tables: Student Table: Student (Sno, Sname, Ssex, Sage, Sdept) Sno-based code; Class Schedule: Course (Cno, Cname, Cpno, Credeit) Cno-based code; Students taking this table: SC (Sno, Cno, Grade) Sno, Cno, t
case letters, student id, system 1, table columns, data structure, three tables, lower case, host system, query table, structure 7, document questions, detailed records, new students, pascal language, liu chen, curriculum databaseSeptember 25
View article PHP constants dirname (__file__) Learning September 2, 2008 at 15:42 PHP constant dirname (__file__) __FILE__: Magic constants known as PHP, PHP script that returns the current implementation of the full path and file name that contains
directory structure, relative path, development environment, case letters, test results, previous version, description line, method names, class names, constants, absolute path, web directory, lower case, php 5, php script, environment web, system root directory, php 4, php fileSeptember 16
Depressed: powerdesigner generate table script oracle construction, but the resulting table can not insert, exp, update, drop reported ORA-00942: table or trying to absence of an exception, where the thought of moving the oracle configuration caused
database table, oracle, table structure, oracle table, quot quot, field names, case letters, primary key, constraint, quotation marks, lowercase letters, table names, comrades, double quotes, powerdesigner, sid, lower case, resignation, table script, script oracleSeptember 1
1, the use of separator In order for search engines to identify the English name of the URL in the form of keywords, we need to use the appropriate symbols of the word between phrases separated, common separator include: space "", dash "-&q
quot quot, relationship, google, case letters, expression, underscore, comma, separator, space character, meaning of the word, search engines, search engine system, phrases, dashes, digital camera battery, word case, cibieAugust 22
Chapter 1 To prevent the header files are repeated references, should be used ifndef / define / endif preprocessing block structure generated Use # include <filename.h> reference standard library header files, use # include "filename.h" qu
programming guide, case letters, global variables, switch statement, capital letters, standard library, blank line, integer variables, static variable, cpu cycles, case statement, block structure, zero value, class data members, quality c, order of operations, library header files, gt eps, word combinations, word combinationAugust 16
Windows → Preferences → Java → Editor → Content Assist We see them AutoActivation Delay default value is 200 (in milliseconds) that is in play "." Remain after 200 milliseconds to appear IntelliSense prompt. Then change it to 20 will do? Try, wa
eclipse, quot quot, case letters, notepad, java program, abc, milliseconds, shortcut keys, templates, lower case, java editor, cursor position, example input, template set, increase speed, epf, intelligence enhancement, option autoAugust 15
Always report this error today, because I drawable folder name in the picture below uppercase letters, changed to OK the The layout file name can only lower case letters and numbers 26, select 0 to 9. Therefore, our file name in capital letters will
case letters, source folder, capital letters, letters and numbers, folder name, uppercase lettersAugust 11
1. Cross-platform Maintaining platform compatibility, data, and path names to lower case letters, the path to use relative path. 2.Interfaces ArcObject the interface name to I begin unity, the interface proxy class named in the interface name followe
public interface, relative path, case letters, array element, proxy class, delivery method, lower case, java api, abstract classes, interface name, feature class, path names, api development, queryinterface, platform compatibility, arcobject, compatibility data, ipoint, transition issues, correct deliveryAugust 10
First thing to remember is: regular expressions and wildcards are not, they are not the same as the meaning of that! Regular expression is just a representation, as long as the tools to support this representation, then the tool can handle the regula
google, case letters, regular expression, nginx, expression string, capital letters, number 0, string search, search keyword, lower case, ae, regularization, oriented web, awk, best tools, example search string, goooooogle, txt search, football game, favorite foodJuly 29
With the Twitter micro-blog site similar to the appearance of the character of the limit of URL shortening services increasing. With URL shortening service provider web site tracking services, the business gradually rise. Famous URL shortening servic
cn, case letters, len, lowercase letters, substr, url address, twitter, sina, pow, num num, realization, shu, seq, tencent, digits, address check, index users, address numbers, service provider web, numbers indexJuly 22
After learning of individual methods, classes, interfaces, etc. After testing, then to see so create Test Suite, look at an example: public static Test Suite(){ TestSuite suite = new TestSuite(); suite.addTest(new MoneyTest("testEquals")); suite
public void, case letters, test suite, test code, test case, class hierarchy, test method, class test, test methods, static test, lower case, quotes, class declaration, superclass, default test, junit test, uniform requirements, instance level, addtest, test componentsDecember 29
ajax login form jquery mysqlgwt gilead is slow during developmentlibffmpeg_armv5te.so para downloadadfs clearAuthenticationCache()http: 59.212.213.227 xzsplocalhost:8089 Yigo Yigo.jsphttp: 111.75.216.223:8088 web index.isphttp: 171.215.17.6000. system logihshan.safetxee.com.cmdelphi chromium | http://www.quweiji.com/tag/case-letters/ | CC-MAIN-2019-30 | en | refinedweb |
If you searching the internet for jqGrid and ASP.NET MVC you will find many examples,
but all of them always define the jqGrid columns – see for an example the blog post from Phil Haack.
If you have a lot of jqGrids in your project you don’t want to define every single column for all the grids.
>
So I came up with the idea, why not just pass the data model class and let the grid create itself based
on the model!
So here is my solution.
First of all I wanted an easy syntax to create the Grid – for that reason I created a HtmlHelper extension
which takes the data model class.
public static Grid<T> Grid<T>(this HtmlHelper htmlHelper, string name) where T : class { return new Grid<T>(name, htmlHelper.ViewContext.Writer); }
Now you can create a grid simple like in the following example:
<%=Html.Grid<Question>("MyDynamicGrid")%>
Looks nice or? So what about the ajax data?
The data has to come as a JsonResult – for that I created a GridExtension where you pass the data
and the information for sorting and paging.
So the only thing you have to call in the controller is the extension method AsJqGridResult.
Here is an example:
[HttpPost] public ActionResult DynamicGridData(string sidx, string sord, int page, int rows){ var context = new HaackOverflowDataContext(); return (context.Questions.AsQueryable() .AsJqGridResult(sidx, sord, page, rows)); }
Every time you change the DataModel it will create the columns based on it and you
don’t have to change the jqGrid column definitions.
One of the next steps to make everything even better would be to create DataViewModel classes
where you can define the ModelMetadata so that you have more control over which columns you
want to show and to have nice column names. – You can see this is in my second post.
If you are interested in the code or want to use it – here is the source code.
Cool Post – that should make my life easier 😉
Nice Simon, i try your solution on another database, and something error on GetType because of NULL value from database i think. Currently i’m working on it so we could get a better solution.
Hi rudysetyo,
we just published a new version. Please look at the blog to download the new source code. If the exception still exists please tell me exactly at which file and line thanks.
Simon
THIS IS SO AWESOME!!!!!! many thanks!!
I like the concept. I’m currently using a JQuery Grid for a corporate MVC website. I would definitely like to use your grid, but it doesn’t use razor syntax. Do you have a version that uses razor syntax? | https://blog.lieberlieber.com/2010/07/07/asp-net-mvc-and-a-generic-jqquery-grid-jqtgrid/ | CC-MAIN-2019-30 | en | refinedweb |
Created on 2008-02-28 18:26 by bwmcadams, last changed 2016-03-08 12:48 by deronnax. This issue is now closed.
URLLIB2 seems to have issues attempting to digest authenticate against a
Windows-based IIS 6.x server. The IIS server requests MD5-sess support,
and URLLIB2 throws an exception that ... far from explains this:
Traceback (most recent call last):
File "/usr/lib64/python2.5/runpy.py", line 95, in run_module
filename, loader, alter_sys)
File "/usr/lib64/python2.5/runpy.py", line 52, in _run_module_code
mod_name, mod_fname, mod_loader)
File "/usr/lib64/python2.5/runpy.py", line 32, in _run_code
exec code in run_globals
File "/srv/pubPal/test/test_auth.py", line 16, in <module>
print opener.open(uri)
File "/usr/lib64/python2.5/urllib2.py", line 380, in open
response = meth(req, response)
File "/usr/lib64/python2.5/urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib64/python2.5/urllib2.py", line 412, in error
result = self._call_chain(*args)
File "/usr/lib64/python2.5/urllib2.py", line 353, in _call_chain
result = func(*args)
File "/usr/lib64/python2.5/urllib2.py", line 992, in http_error_401
host, req, headers)
File "/usr/lib64/python2.5/urllib2.py", line 884, in http_error_auth_reqed
return self.retry_http_digest_auth(req, authreq)
File "/usr/lib64/python2.5/urllib2.py", line 889, in
retry_http_digest_auth
auth = self.get_authorization(req, chal)
File "/usr/lib64/python2.5/urllib2.py", line 920, in get_authorization
H, KD = self.get_algorithm_impls(algorithm)
File "/usr/lib64/python2.5/urllib2.py", line 972, in get_algorithm_impls
return H, KD
UnboundLocalError: local variable 'H' referenced before assignment
The offending code is urllib2.py line 972:
def get_algorithm_impls(self, algorithm):
# lambdas assume digest modules are imported at the top level
if algorithm == 'MD5':
H = lambda x: hashlib.md5(x).hexdigest()
elif algorithm == 'SHA':
H = lambda x: hashlib.sha1(x).hexdigest()
# XXX MD5-sess
KD = lambda s, d: H("%s:%s" % (s, d))
return H, KD
I'm not sure what's meant by the # XXX MD5-sess comment there... But
what ends up happening is that MD5-sess matches neither the if or the
elif, and when return attempts to return, H is undefined.
This could be easily patched, but support for MD5-sess would be great as
well.
In my estimation, at the least, urllib2 shouldn't crap out in such an
obscure way when encountering an unsupported algorithm.
I'd suggest changing line 970 (The # XXX MD5-sess line) to:
raise Exception, "Unsupported Digest Authentication Algorithm '%s'" %
(algorithm)
Sorry, this isn't a crash. It doesn't crash the interpreter. I'll
assume "behavior' is the correct categorization.
Marking as easy, assuming you add the exception; implementing MD5-sess
is probably not easy.
Here is a patch for supporting MD5-sess, following RFC2617 specification.
Some comments/warnings:
* I've only tested the patch against IIS 6.0. I don't know about other servers supporting MD5-sess.
* IIS 6.0 expects the User Agent to send the URI (in the Authorization header) without the query string.
* This patch doesn't add support for Digest sessions. For each request we make, we get a new [401|407] message with a new nonce (depending if we're talking about a proxy with digest authentication or a web server). Then we generate another authenticated request using that nonce. For Digest sessions to be fully supported, we should be adding an [WWW|Proxy]-Authenticate header in each following request we made to the server using the last nonce. This includes both MD5-sess and MD5 digest implementations.
* A1 is being recalculated for every request. Given the above, this is not a real problem.
I'll open a new ticket regarding Digest sessions.
I tried to test the patch but got:-
c:\Python26>python.exe lib\test\test_urllib2_localnet.py
Traceback (most recent call last):
File "lib\test\test_urllib2_localnet.py", line 325, in <module>
class DigestMD5sessClientAuthTests(BaseTestCase):
NameError: name 'BaseTestCase' is not defined
Is this moving anywhere? I was asked to apply this patch locally and am curious as to whether it is moving into the stdlib.
Adding some minor fixes to the original patch to apply cleanly to current 2.7 tip.
Also, add a conditional branch in the case that the server returns none of the supported algorithm strings, to raise a ValueError (the previous patch adds support for 'MD5-sess' but the original non-descript stack trace would be seen again with some other unsupported algorithm string).
Just got bitten by this as well, what still needs to happen with the patch?
One question is whether this is a bug fix or a feature request.
Other than that, I'd like to see the test classes collapsed into a single test class, considering that each one only has a single test in it. Probably ProxyAuthTests should be refactored so that the stuff that is currently in setUp is a method that gets called with appropriate parameters instead, and all the new tests moved on to ProxyAuthTests.
Also, a version of the patch for 3.x would be most helpful, since it won't port cleanly due to the renamings.
Yes, it is a feature. Sorry that I have not paid attention to this. The Windows (IIS) part led me to delay as I did not have any to test. Let me take this up and see through it in 3.3.
Hmm, I'd argue it's a bug:
File "/usr/lib64/python2.5/urllib2.py", line 972, in get_algorithm_impls
return H, KD
UnboundLocalError: local variable 'H' referenced before assignment
...does not say anything like:
"The digest authentication scheme you have requested is not supported"
Now, as to whether it's a bug that 'MD5-sess' isn't supported is a tougher call. The XXX indicates the intention was certainly for it to be supported...
Oh, the bad error message is definitely a bug. The question is whether we can also add md5-sess support while fixing it. Sounds like Senthil thinks no, in which case this issue needs to be split into two parts.
...which is, of course, rather disappointing.
When *would* md5-sess land? 2.7? 3.3?!
3.3.
IMO this is in the grey area between feature and bug fix. I think it is possible to argue that it can be treated as a bug fix, but I think we need opinions from other developers if we want to try to go that route.
The reason I think it can be argued that it can be treated as a bug fix is that (if I understand correctly) there is no difference in the application code. The only difference is whether or not one can successfully communicate with IIS 6. That may not be a sufficient argument, but it is an argument :)
Who with and where does the argument need to be had?
Hmm. How about python-committers? I would suggest python-dev, but that feels like invoking the dragon :)
Python 3.3 has been released a while ago and is in bug fix mode.
Personally I'm against this enhancement. It adds a digest auth scheme that is based on a broken and insecure hashing algorithm.
Could we at least do something cleaner that let the interpreter raise an UnboundLocalError ? Maybe something like "NotImplemented" ?
Sure. Would you like to propose a patch? It does seem that NotImplementedError would be the most appropriate. It could give Christian's reason why it is not implemented.
here is the patch, for the trunk
and here for the 2.7 branch
But I think md5-sess should really be integrated. It's a standard mechanism described by a RFC (), and people need it, however insecure it may be (aren't other method (md5) insecure too ?).
up
python 2.7
python current
I do wonder if NotImplementedError is the right exception. According to the documentation it is derived from RuntimeError and is meant for abstract methods, i.e. it is a programmer error. Other cases in urllib.request raise ValueError (e.g. AbstractBasicAuthHandler), which is fairly normal for protocol errors like this.
Also it would be nice to add a test case for the bug fix.
I can see in the tests (test_urllib2_localnet.py) that Digest auth is tested only through "ProxyAuthTests". Is that sufficient ? Isn't it a bug ? If no, should I add the test in that class ?
first draft
I'm waiting for reviews.
New changeset 22eab50cb585 by Berker Peksag in branch '3.5':
Issue #2202: Fix UnboundLocalError in AbstractDigestAuthHandler.get_algorithm_impls
New changeset 046c75c9cd33 by Berker Peksag in branch 'default':
Issue #2202: Fix UnboundLocalError in AbstractDigestAuthHandler.get_algorithm_impls
New changeset d135799e952b by Berker Peksag in branch '2.7':
Issue #2202: Fix UnboundLocalError in AbstractDigestAuthHandler.get_algorithm_impls
Thanks, Mathieu! I went with a simpler approach to test the code.
Much better indeed. Thanks. | https://bugs.python.org/issue2202 | CC-MAIN-2019-30 | en | refinedweb |
Hide Forgot
Description of problem:
I started the program from Gnome's program search (super button, then type in the program name) and it crashed.
Version-Release number of selected component:
texstudio-2.10.4-1.fc23
Additional info:
reporter: libreport-2.6.3
backtrace_rating: 4
cmdline: texstudio
crash_function: qglx_findConfig
executable: /usr/bin/texstudio
global_pid: 15699
kernel: 4.2.5-300.fc23.x86_64
runlevel: N 5
type: CCpp
uid: 1000
Truncated backtrace:
Thread no. 1 (10 frames)
#0 qglx_findConfig at glxconvenience/qglxconvenience.cpp:157
#1 qglx_findVisualInfo at glxconvenience/qglxconvenience.cpp:192
#2 QXcbWindow::create at qxcbwindow.cpp:459
#3 QXcbIntegration::createPlatformWindow at qxcbintegration.cpp:201
#4 QWindowPrivate::create at kernel/qwindow.cpp:391
#5 QWindow::create at kernel/qwindow.cpp:547
#6 QWidgetPrivate::create_sys at kernel/qwidget.cpp:1454
#7 QWidget::create at kernel/qwidget.cpp:1318
#8 QWidget::setVisible at kernel/qwidget.cpp:8057
#9 TexstudioApp::init at main.cpp:64
Created attachment 1096238 [details]
File: backtrace
Created attachment 1096239 [details]
File: cgroup
Created attachment 1096240 [details]
File: core_backtrace
Created attachment 1096241 [details]
File: dso_list
Created attachment 1096242 [details]
File: environ
Created attachment 1096243 [details]
File: exploitable
Created attachment 1096244 [details]
File: limits
Created attachment 1096245 [details]
File: maps
Created attachment 1096246 [details]
File: mountinfo
Created attachment 1096247 [details]
File: namespaces
Created attachment 1096248 [details]
File: open_fds
Created attachment 1096249 [details]
File: proc_pid_status
Created attachment 1096250 . | https://bugzilla.redhat.com/show_bug.cgi?id=1283359 | CC-MAIN-2019-30 | en | refinedweb |
Here is the documentation of the LeptoquarkModel class. More...
#include <LeptoquarkModel.h>
Here is the documentation of the LeptoquarkModel class.
Definition at line 24 of file LeptoquarkModel.h.
Make a simple clone of this object.
Reimplemented from Herwig::StandardModel.
Return the coupling of the leptoquark to right-handed leptons.
Definition at line 100 of file LeptoquarkModel.h.
Return the coupling of the leptoquark to right-handed leptons.
Definition at line 136 of file LeptoquarkModel.h. 207 of file LeptoquarkModel.h. | https://herwig.hepforge.org/doxygen/classHerwig_1_1LeptoquarkModel.html | CC-MAIN-2019-30 | en | refinedweb |
public class Rapids extends java.lang.Object
Rapids is an interpreter of abstract syntax trees.
This file contains the AstRoot parser and parser helper functions. AstRoot Execution starts in the AstExec file, but spreads throughout Rapids.
Trees have a Lisp-like structure with the following "reserved" special characters:
Variables are lexically scoped inside 'let' expressions or at the top-level looked-up in the DKV directly (and must refer to a known type that is valid on the execution stack).
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
public static AstRoot parse(java.lang.String rapids)
rapids- expression to parse
public static Val exec(java.lang.String rapids)
rapids- expression to parse
public static Val exec(java.lang.String rapids, Session session)
rapids- expression to parse | http://docs.h2o.ai/h2o/latest-stable/h2o-core/javadoc/water/rapids/Rapids.html | CC-MAIN-2019-30 | en | refinedweb |
android.hidl.manager@1.0
IServiceManager
interface IServiceManager
Manages all the hidl hals on a device.
All examples in this file assume that there is one service registered with the service manager, "android.hidl.manager@1.0::IServiceManager/manager"
Terminology:Package:"android.hidl.manager" Major version:"1" Minor version:"0" Version:"1.0" Interface name:"IServiceManager" Fully-qualified interface name:"android.hidl.manager@1.0::IServiceManager" Instance name:"manager" Fully-qualified instance name:"android.hidl.manager@1.0::IServiceManager/manager"
Properties
Transport
enum Transport: uint8_t
PidConstant
enum PidConstant: int32_t
Special values for InstanceDebugInfo pids.
InstanceDebugInfo
struct InstanceDebugInfo {string interfaceName; string instanceName; int32_t pid; vec clientPids; Architecture arch}
Returned object for debugDump().
Methods
get
get (string fqName, string name) generates (/***/interface service)
Retrieve an existing service that supports the requested version.
WARNING:This function is for libhidl/HwBinder use only.You are likely looking for 'IMyInterface::getService("name")' instead.
add
add (string name, /***/interface service) generates (bool success)
Register a service.The service manager must retrieve the(inherited)interfaces that this service implements, and register them along with the service.
Each interface must have its own namespace for instance names.If you have two unrelated interfaces IFoo and IBar, it must be valid to call:
add("my_instance", foo);//foo implements IFoo add("my_instance", bar);//bar implements IBar
WARNING:This function is for libhidl/HwBinder use only.You are likely looking for 'INTERFACE::registerAsService("name")' instead.
getTransport
getTransport (string fqName, string name) generates (Transport transport)
Get the transport of a service.
list
list () generates (vec<string> fqInstanceNames)
List all registered services.Must be sorted.
listByInterface
listByInterface (string fqName) generates (vec<string> instanceNames)
List all instances of a particular service.Must be sorted.
registerForNotifications
registerForNotifications (string fqName, string name, IServiceNotification callback) generates (bool success)
Register for service notifications for a particular service.Must support multiple registrations.
onRegistration must be sent out for all services which support the version provided in the fqName.For instance, if a client registers for notifications from "android.hardware.foo@1.0", they must also get notifications from "android.hardware.foo@1.1".If a matching service is already registered, onRegistration must be sent out with preexisting = true.
debugDump
debugDump () generates (vec<InstanceDebugInfo> info)
Similar to list, but contains more information for each instance.
registerPassthroughClient
registerPassthroughClient (string fqName, string name)
When the passthrough service manager returns a service via get(string, string), it must dispatch a registerPassthroughClient call to the binderized service manager to indicate the current process has called get().Binderized service manager must record this PID, which can be retrieved via debugDump. | https://source.android.com/reference/hidl/android/hidl/manager/1.0/IServiceManager | CC-MAIN-2019-30 | en | refinedweb |
STRTOK(3P) POSIX Programmer's Manual STRTOK(3P)
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
strtok, strtok_r — split string into tokens
#include <string.h> char *strtok(char *restrict s, const char *restrict sep); char *strtok_r(char *restrict s, const char *restrict sep, char **restrict state);
For strtok(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2017‐2017 calls strtok()..
No errors are defined. The following sections are informative.TOK(3P)
Pages that refer to this page: string.h(0p), localeconv(3p) | https://www.man7.org/linux/man-pages/man3/strtok.3p.html | CC-MAIN-2022-33 | en | refinedweb |
I use VS Code as text editor, and I install jQuery library as local
I make link to my js file(custom.js) like this
`import 'jquery'`
In VS Code the auto-import work, which mean the editor can suggest the syntax for me. But the problem is when I try to open the file in browser(index.html with the link to custom.js) it doesn’t work. The error is unexpected identifier
When I deleted the
import 'jquery' part and link the jquery library directly to html file(index.html) then it work. I first guess it because my browser doesn’t support the ES6 syntax, but when I check my chrome is latest version (ver 72)
Can you help me with this problem? | https://forum.freecodecamp.org/t/how-to-link-jquery-library-to-my-javascript-file/260967 | CC-MAIN-2022-33 | en | refinedweb |
On Fri, Sep 18, 2020 at 10:38 AM Steven D'Aprano steve@pearwood.info wrote:
On Fri, Sep 18, 2020 at 09:05:39AM +1000, Chris Angelico wrote:
f-strings are not literals. They are a form of eval().
Oh, that makes 'em sound way too scary :) They're more akin to a list display - a syntactic structure that yields a well-defined object, and has expressions inside it.
*shrug*
Okay, but either way they certainly aren't a literal. Anyone who doubts that ought to disassemble an f-string and see for themselves:
import dis code = compile("f'{x+1} {x-1}'", '', 'eval') dis.dis(code)
Agreed. The advantage of them being a syntactic structure (rather than some sort of masked eval() call) is that the proposal at hand DOES make sense. Consider:
# List display (or tuple w/o the brackets) x = [spam, ham] # Unpacking assignment (ditto) [spam, ham] = x
# Formatted string txt = f"foo bar {qty:d} quux" # Proposed string unpacking f"foo bar {qty:d} quux" = txt
It doesn't make sense to assign to a function call. It does make sense to assign to a construct that is handled by the parser. We have assignment forms that look just like lookups ("x = a[1]" and "a[1] = x").
But yes, all of this is also predicated on f-strings NOT being literals.
ChrisA | https://mail.python.org/archives/list/python-ideas@python.org/message/HTO7BQTMDWMTVHMMIAIEHZ4PSJWTEL3N/ | CC-MAIN-2022-33 | en | refinedweb |
SETUP(2) Linux Programmer's Manual SETUP(2)
NAME
setup - setup devices and filesystems, mount root filesystem
SYNOPSIS
#include <unistd.h>
int setup(void);
DESCRIPTION
setup() is called once from within linux/init/main.c. It calls ini-
tialization functions for devices and filesystems configured into the
kernel and then mounts the root filesystem. 4.10 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.
Linux 2008-12-03 SETUP(2) | http://man.yolinux.com/cgi-bin/man2html?cgi_command=setup(2) | CC-MAIN-2022-33 | en | refinedweb |
A table that depicts the frequency of occurrences of several categories is called a frequency table. This particular kind of table is especially helpful for gaining an idea of the distribution of the values contained in a dataset. This tutorial will walk you through the process of creating frequency tables in Python. We will be covering implement of the same in a number of different ways which are covered in the next few sections.
Also Read: 6 Ways to Count Pandas Dataframe Rows
Method 1 – With the help of value_counts() function
The very first method is to make use of the
value_counts() function which will return a series containing the count of unique values in all the list of values. The result will be in
descending order which implies that the first element is the most frequently-occurring element.
import pandas as pd data = pd.Series([1, 2, 5, 2, 3, 3, 3, 3, 4, 4, 5]) print("The Dataset is : ") print(data) print("\nFrequency Table for the data : ") print(data.value_counts())
The Dataset is : 0 1 1 2 2 5 3 2 4 3 5 3 6 3 7 3 8 4 9 4 10 5 dtype: int64 Frequency Table for the data : 3 4 2 2 5 2 4 2 1 1
Method 2 – With the help of crosstab() function
Another function that we can use to display frequencies of a pandas DataFrame is the
crosstab() function as shown in the code below. We will create a dataframe and then create the frequency table for two columns of the data frame.
df = pd.DataFrame({'Student_Grade': ['A','B','A','B','B', 'B', 'B', 'C', 'C', 'D'], 'Student_Age': [18, 25, 28, 19, 30, 20, 15, 18, 29, 17], 'Student_Gender': ['M','F', 'M', 'F', 'F', 'M', 'M', 'F', 'F', 'F']}) print("The Dataset is : ") print(df) print("\nFrequency Table for the Grade in the dataset : ") pd.crosstab(index=df['Student_Grade'], columns='count')
print("\nFrequency Table for the Gender in the dataset : ") pd.crosstab(index=df['Student_Gender'], columns='count')
Advance Frequency Tables ( 2 – way Tables )
We can also create a two-way frequency table to display the frequencies for two different columns in the dataset we used in the last section. The following code displays a two-way frequency table for the two columns Age and Grade.
pd.crosstab(index=df['Student_Grade'], columns=df['Student_Age'])
We will also be developing a two-way frequency table between the two columns Gender and Grade. Look at the code below.
pd.crosstab(index=df['Student_Grade'], columns=df['Student_Gender'])
Thank you for reading! I hope you understood the tutorial 😃
I would recommend you to give the following tutorials a read as well:
- Calculating Precision in Python — Classification Error Metric
- Chi-square test in Python — All you need to know!!
- Universal NumPy Trigonometric functions to know | https://www.askpython.com/python/examples/frequency-tables | CC-MAIN-2022-33 | en | refinedweb |
Pythonista xCode template adventure
Hi Pythonistaers!
I have a problem with a discrepancy between the xCode template and Pythonista 1.6 betaversions of an app, resulting in different code paths depending on if it's run from within the Pythonista app or it's own app /in an xCode simulator. (xCode simulator and self-contained app have the same results. Pythonista scripts don’t, but they behave as expected.)
the specific piece of code where the divergence takes place is in the try-except fork below. Pythonista-launched app succeeds the try clause. xCode/self-contained-app fails and excepts.
Based on the piece of code where this divergence happens, and error logs, I believe this has to do with the way location services work.
ourActualLocation = [] print "..." location.start_updates() print "...." thisLoc = location.get_location() print thisLoc print "....." try: #works w/pythonista launched app thisLon = thisLoc["longitude"] thisLat = thisLoc["latitude"] except: #excepts with simulator and app bundle print "gps module offline...using napa coordinates fallback..." thisLon = -125.3353 thisLat = 39.3101 print "......" ourActualLocation = [thisLat,thisLon] print "......." location.stop_updates() #addressStart = #[39.2960,-125.2830] addressEnd = [39.3101,-125.3353]#getCoor
Here is part of an error log:
Oct 29 21:26:24 syht8387235u locationd[3928]: ERROR: com.mycompany.PythonistaFiveStars is depending on legacy on-demand authorization, which is not supported for new apps Oct 29 21:26:54 --- last message repeated 1 time --- Oct 29 21:26:54 syht8387235u assertiond[3929]: assertion failed: 15B42 13B134: assertiond + 13207 [F9316174-60A2-3CA9-A8AD-49680DCA196D]: 0x1 Oct 29 21:27:26 syht8387235u assertiond[3929]: assertion failed: 15B42 13B134: assertiond + 13207 [F9316174-60A2-3CA9-A8AD-49680DCA196D]: 0x1 Oct 29 21:27:52 --- last message repeated 7 times --- Oct 29 21:27:52 syht8387235u PythonistaFiveStars[3976]: -canOpenURL: failed for URL: "launch://" - error: "This app is not allowed to query for scheme launch" Oct 29 21:30:58 syht8387235u routined[3913]: CoreLocation: Error occurred while trying to retrieve motion state update: CMErrorDomain Code:104
Also, another error: The template/app bundle can’t load piano sounds included in the sound module.[SOLVED - see below]
Error Log:
2015-10-30 02:16:00.923 PythonistaFiveStars[2373:100188] OAL Error: -[OALSimpleAudio internalPreloadEffect:reduceToMono:]: Could not load effect Piano_C.caf 2015-10-30 02:16:01.227 PythonistaFiveStars[2373:100188] OAL Error: -[OALSimpleAudio internalPreloadEffect:reduceToMono:]: Could not load effect Piano_3.caf Message from debugger: Terminated due to signal 15
So, in summary, the issues with the Template seem to be:
1.) location updates are different, something about "legacy" permissions?[SOLVED]
A: Create NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription
item in your info.plist, and choose the text description to show people in settings location pane.
surprisingly, correct me if I'm wrong, a dialogue only seems to pop up with NSLocationAlwaysUsageDescription
2.) access to sounds in the sound module[SOLVED]
A: never mind - personal code bug.
3.) While the script is running from within pythonista, it's able to remain in the background at least for a while. The self-contained app version does not stay open in the background AT ALL.[SOLVED]
A: change "application does not run in the background" to NO in plist file.
4.) Out bound Webbrowser:// links to other apps don't seem to work.
I should probably include:
iPhone 6S plus / xCode-Beta.app v7.1 / iOS 9.1 / Pythonista 1.6 latest Beta (160035) / latest Pythonista template that I'm aware of.
I'm going to use this thread as an ongoing exploration of issues with using the whole of the Pythonista development environment.
Hi everyone, just following up here.
webbrowser.open() doesn't appear to work as a standalone app through the Xcode template.
Previously I had mentioned that launching an outbound link to an app made my app freeze when used as a standalone app. I have a function tied to a button that would close the view and then open a link. I removed everything except an outbound link to, and still this doesn't work in the standalone version, just making the app freeze, and I don't see anything relevant in the system log output.
So, button tied to the following function:
def uberButtonPress(sender): webbrowser.open("") or def uberButtonPress(sender): webbrowser.open("launch://")
both versions of that function work properly when in pythonista itself, but not for the template.
Any ideas guys?
The only console output i could get from Xcode was this, but I don't think it's relevant. (I do use the speech module, so if anybody has any insight about these errors I'm very interested)
2015-11-17 11:41:22.103 PythonistaFiveStars[896:309538] ] Building MacinTalk voice for asset: (null)
Any ideas anyone about webbrowser.open() in the Xcode template?
I am concerned when you say you close the view, then open a webbrowser. Without a ui.delay, this can result in some race conditions that freeze the app. The timing in xcode is going to be a little different than in app, i think others have had similar issues.
Try: 1). launching webbrowser without ui, to see if webbrowser works at all.
- if that works, try
def uberButtonPress(sender): def launchWebBrowser(): webbrowser.open('') ui.delay(launchWebBrowser, 1.0)
Does the webbrowser need to stay in app? if not, you could use safari-http:// to swicth to safari. Do you need the full webbrowser with addressbar,etc? mif not ui.WebView might work for you.
safari-http://
Thanks for your reply, JonB. So, as you suggest, I removed everything from the function except the webbrowser.open() function, using both the safari-http:// and other app's url-schemes. None of them seem to work when running from an app built using the Pythonista template for xCode. Pressing the button associated with them doesn't make the app crash and close or anything like that, it simply makes the app's execution hang, freeze, and be unresponsive.
Once I figure out how to make webbrowser.open() work at all, I'll have to use ui.delay per your advice.
Is there anything else I can do to troubleshoot? It's my understanding that I can't simply use Objc_util because that's not integrated into the xCode template yet (please correct me if I'm wrong).
Have you created an app which does not us
uiat all? i.e no button at all?
also... i am pretty sure webview does work in the template. is there a reason you cannot use ui.WebView?
@JonB So I've experimented with this quite a bit and there are a couple things involved. (BTW i'm not actually trying to have a web view, but use the url schemes of other apps via these modules, but am using safari- for testing purposes.)
First off, for iOS 9 to be able to query url schemes you need to add an array into your plist called LSApplicationQueriesSchemes, filled with strings of all the app urls you want to use. for launch center pro, url "launch://", you use string "launch" in the plist array.
Turns out both ui.WebView and webbrowser.open() DO work in the template when tested on their own. In the context of my app, they have maybe a 5% success rate, the other 95% of the time the app freezes.
I have a main run loop that's constantly going, and making changes to labels etc if time passed since last change has been 1 second or more. So I guess the interrupt from using a button to launch a url is somehow interfering with this.
But again, the same exact files launched from within Pythonista, these buttons launching URLS work 100% of the time, where from an app using the Xcode template, almost none of the time.
ui.delay(webbrowser.open("safari-),1) results in the same freezing.
ui.delay takes a callable as the first argument. You provided a bool, after calling webbrowser.open! You will want to use a lambda or wrap in a def:
def launch(): webbrowser.open(url) ui.delay(launch,1.)
Is your main loop running as a thread? or just a main loop with sleeps?
I just read a little about LSApplicationQueriesSchemes... seems like this will kill the whole x-callback-url movement. if that was the problem here, it seems like it should just fail silently.
btw, use webbrowser.can_open to check if it is LSApplicationQueriesSchemes causing you problems.
sorry,. | https://forum.omz-software.com/topic/2328/pythonista-xcode-template-adventure/18 | CC-MAIN-2022-33 | en | refinedweb |
Here's a fun program in C programming language to find the number of 500, 100, 50, 20, 10, 5, 2, 1 rupee notes in a given amount. It'll surely help cashiers to mange things properly.
# include <stdio.h> # include <conio.h> void main() { int rs, a, b, c, d, e, f, g, h ; clrscr() ; printf("Enter the amount in Rupees : ") ; scanf("%d", &rs) ; while(rs >= 500) { a = rs / 500 ; rs = rs % 500; printf("\nThe no. of five hundreds are : %d", a) ; break ; } while(rs >= 100) { b = rs / 100 ; rs = rs % 100; printf("\n\nThe no. of hundreds are : %d", b) ; break ; } while(rs >= 50) { c = rs / 50 ; rs = rs % 50; printf("\n\nThe no. of fifties are : %d", c) ; break ; } while(rs >= 20) { d = rs / 20 ; rs = rs % 20; printf("\n\nThe no. of twenties are : %d", d) ; break ; } while(rs >= 10) { e = rs / 10 ; rs = rs % 10; printf("\n\nThe no. of tens are : %d", e) ; break ; } while(rs >= 5) { f = rs / 5 ; rs = rs % 5; printf("\n\nThe no. of fives are : %d", f) ; break ; } while(rs >= 2) { g = rs / 2 ; rs = rs % 2; printf("\n\nThe no. of Twos are : %d", g) ; break ; } while(rs >= 1) { h = rs / 1 ; rs = rs % 1; printf("\n\nThe no. of ones are : %d", h) ; break ; } getch() ; }
Output of above program is
Enter the amount in Rupees : 698
The no. of five hundreds are : 1
The no. of hundreds are : 1
The no. of fifties are : 1
The no. of twenties are : 2
The no. of fives are : 1
The no. of Twos are : 1
The no. of ones are : 1
Explanation of above program
Above program is pretty straightforward. All it does is that it takes an amount as input and shows how many 500, 100, 50, 10, 5, 2, 1 notes are needed. As this program contains all basics of C programming, lets understand this program by an example.
Remember: When you divide two integer and stores the value in an integer only integer part of the result is stored e.g. 10 / 3 = 3.333 but when you store this result in another integer, it will only hold 3 as its value (to store the exact result use float as data type).
Also in C, % is modulus and is used to calculate remainder so e.g. 5 % 3 will be 2.
Suppose, rs = 698. Now we go step by step .
- First while loop executes as 698 >= 500, so a = 698 / 500 = 1 and rs = rs % 500 = 698 % 500 = 198. The printf() is executed.
- Next while loop executes as 198 >= 100, so a = 198 / 100 = 1 and rs = rs % 100 = 198 % 100 = 98. The printf() is executed.
- Next while loop executes as 98 >= 50, so a = 98 / 50= 1 and rs = rs % 50 = 98 % 50 = 48. The printf() is executed.
- Next while loop executes as 48 >= 20, so a = 48 / 20= 2 and rs = rs % 20 = 48 % 20 = 8. The printf() is executed.
- The next while loop is not executed because 8 < 10.
- Next while loop executes as 8 >= 5, so a = 8 / 5= 1 and rs = rs % 5 = 8 % 5 = 3. The printf() is executed.
- Next while loop executes as 3 >= 2, so a = 3 / 2= 1 and rs = rs % 2 = 3 % 2 = 1. The printf() is executed.
- Next while loop executes as 1 >= 1, so a = 1 / 1= 1 and rs = rs % 1 = 1 % 1 = 0. The printf() is executed.
plz applications of thisprogram
This program could be used to determine how a sum of money could be formed using notes of different denominations by keeping higher denominations notes as many as possible. E.g. in case the amount is 1500 then three notes of 500
Hi, Tanmay. I made a more efficient code in C++, I hope you enjoy it:
#include
using namespace std;
int main () {
float remaining_value(0),result(0),rest(1);
int aux(0),other(0);
float notes[7] = {100,50,20,10,5,2,1};
cout << "Provide us the value: ";
cin >> remaining_value;
while (rest!=0) {
result = remaining_value/notes[other]; // result in float
aux = result; // number of notes that will be use
rest = remaining_value - (notes[other]*aux); // provides the rest
if (aux!=0) {
cout << aux << " note(s) of " << notes[other] << endl; }
remaining_value = rest;
other++;
}
return 0; }
If you enter an amount that have decimal is it going to work?
I found an alternate approach .. for solving this C program without using multiple while statements. Finding number of notes
i was looking for this type of answer in many sites. but the only satified answer is this. keep it up. well done!
Thank you very much!!.Helped me alot
Hi There,
Thanks for highlighting this and indicating about C Programming Tutorial where more study and thought is necessary.
I work at the biggest internet non-profit company in the world:]. I love flying remote control cars with my boys. Howdy, my first post here. I was told to announce myself. I`m 43 yrs. old, hitched, and have 2 kids under 5. Anyways, that’s about all.
I look forward to see your next updates.
Regards,
Veena
I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
Php course in chennai
You have explained the topic very well. Thanks for sharing a nice article -visit Java Tutorials
You have explained this topic very well and step by step. Thanks for sharing a nice Post -visit Java Tutorials | http://cprogramming.language-tutorial.com/2012/01/finding-number-of-500-100-50-20-10-5-2.html?showComment=1462211580566 | CC-MAIN-2022-33 | en | refinedweb |
KEYCTL_READ(3) Linux Key Management Calls KEYCTL_READ(3)
NAME
keyctl_read - Read a key
SYNOPSIS
#include <keyutils.h>
long keyctl_read(key_serial_t key, char *buffer,
size_tbuflen);
long keyctl_read_alloc(key_serial_t key, void **_buffer);
DESCRIPTION allo-
cates a buffer big enough to hold the payload data and places the data
in it. If successful, A pointer to the buffer is placed in *_buffer.
The caller must free the buffer.
READING KEYRINGS.
RETURN VALUE
On success keyctl_read()_read_alloc() returns the amount of data in the buf-
fer._READ(3) | http://man.yolinux.com/cgi-bin/man2html?cgi_command=keyctl_read(3) | CC-MAIN-2022-33 | en | refinedweb |
>>
Bessel’s Interpolation in C++
Interpolation is a type of estimation technique of unknown value which lies between know values. Interpolation is the process of constructing new data points between the range of a discrete set of know data points.
An application or reason to use interpolation is that it might reduce computation costs. When the formula (function) to calculate certain values is too complicated or costly to compute, we prefer using interpolation. A few data points are calculated using the original function, the rest of them can be estimated using interpolation. These may not be completely accurate but fairly close!
So basically here the reduced computation cost and simplicity is outweighing the loss from interpolation error.
Bessel’s Interpolation Formula
f(u) = {(f(0)+f(1))/2} + {u - ½}𝛥f(0) + {u(u-1)/2!}{(𝛥2 f(-1) + 𝛥2 f(0))/2} + {u(u-1)(u - ½)/3!}𝛥3f(-1) + {u(u+1)(u-1)(u-2)/4!}{(𝛥4f(-2) + 𝛥4f(-1))/2}+..
here,
f(0) is origin point which is usually the mid point.
u = x - f(0) / h, gh is interval of difference
Example
Program to illustrate Bassel’s interpolation −
#include <iostream> using namespace std; float calU(float u, int n){ if (n == 0) return 1; float result = u; for (int i = 1; i <= n / 2; i++) result = result*(u - i); for (int i = 1; i < n / 2; i++) result = result*(u + i); return result; } int factorial(int n){ if(n == 1) return 1; return n * factorial(n-1); } int main(){ int n = 6; float x[] = { 50, 51, 52, 53, 54, 55 }; float y[n][n]; y[0][0] = 8.000; y[1][0] = 7.746; y[2][0] = 7.674; y[3][0] = 7.571; y[4][0] = 7.469; y[5][0] = 7.231; for (int i = 1; i < n; i++) for (int j = 0; j < n - i; j++) y[j][i] = y[j + 1][i - 1] - y[j][i - 1]; float value = 53.2; float sum = (y[2][0] + y[3][0]) / 2; int index; if (n % 2) index = n/2; else index = n/2 - 1; float u = (value - x[index]) / (x[1] - x[0]); for (int i = 1; i < n; i++) { if (i % 2) sum+= (((u-(0.5))*calU(u, i - 1)*y[index][i])/factorial(i)); else sum+= ((calU(u, i)*(y[index][i]+y[-- index][i])/(factorial(i)*2))); } cout<<"Value at "<<value<<" found using Bessels's interpolation is "<<sum; return 0; }
Output
Value at 53.2 found using Bessels's interpolation is 7.54985
- Related Questions & Answers
- Lagrange’s Interpolation in C++
- Interpolation Search
- Lagrange Interpolation
- Interpolation Search in JavaScript
- String Interpolation in Dart Programming
- How to do string interpolation in JavaScript?
- C++ Program to Implement Interpolation Search Algorithm
- Python Pandas - Fill NaN with Linear Interpolation
- Python Pandas - Fill NaN with Polynomial Interpolation
- Return the modified Bessel function evaluated at each of the elements of x in Python
- C++ program to implement Inverse Interpolation using Lagrange Formula
- How to get smooth interpolation when using pcolormesh (Matplotlib)?
- Python Pandas - Fill NaN values using an interpolation method
- How to draw a precision-recall curve with interpolation in Python Matplotlib?
- How to replace missing values with linear interpolation method in an R vector? | https://www.tutorialspoint.com/bessel-s-interpolation-in-cplusplus | CC-MAIN-2022-33 | en | refinedweb |
I want to enforce constraints the parameter values for Scala methods at compile-time.
For example:
case class Foo(numberOfFoo: Int, ...)
numberOfFoo
Int
val n: Int = ...
val f: Foo = Foo(n)
n > 0
n <= 0
Option[Foo]
Foo
Foo.numberOfFoo != n
case class Foo(bar: Bar) {val n = bar size}
Another way of doing this is by using the
shapeless library, and using
Nat. The limitation is that you will need to instantiate those
Foo entities at compile time basically, with known constants.
import shapeless.ops.nat_ import shapeless.nat._ case class Foo[T <: Nat](numberOfFoo: Int)(implicit ev: GT[T, _0] object Foo { // The problem is this won't work. def apply[T <: Nat](n: Int): Foo[T] = Foo(Nat(n)) }
This will work only if used like this:
Foo(_1)
Where
_1 comes from
shapeless.nat._. If you drill down into the implementation, the
0 part happens to be enforced even without you meaning to by shapeless:
if (n < 0) c.abort(c.enclosingPosition, s"A Nat cannot represent $n")
Stick to simpler things
This is however quite cumbersome, because whichever approach you take, it will rely on a macro, and macros cannot really work unless the value is known at compile time. This can become very limiting, if the simplest delegation method no longer works.
In practice, it may be more efficient to go around this kind of approach and use the normal ways. Whether you use shapeless or the refined library mentioned above, the story doesn't change, so for a normal use case it's probably cleaner to do runtime validation. | https://codedump.io/share/9TLIUcfOTiUk/1/how-can-i-enforce-compile-time-constraints-on-values-for-scala-methods | CC-MAIN-2017-13 | en | refinedweb |
#include <dh2.h>
Inheritance diagram for DH2:
Definition at line 12 of file dh2.h.
[inline, virtual]
generate static private key
Implements AuthenticatedKeyAgreementDomain.
Definition at line 27 of file dh2.h.
generate static public key
Definition at line 29 of file dh2.h.
generate private/public key pair
Reimplemented from AuthenticatedKeyAgreementDomain.
Definition at line 31 of file dh2.h.
generate ephemeral private key
Definition at line 38 of file dh2.h.
generate ephemeral public key
Definition at line 40 of file dh2.h.
Definition at line 42 of file dh2.h.
true
[virtual]
derive agreed value from your private keys and couterparty's public keys, return false in case of failure
length of staticPrivateKey == StaticPrivateKeyLength()
length of ephemeralPrivateKey == EphemeralPrivateKeyLength()
length of staticOtherPublicKey == StaticPublicKeyLength()
length of ephemeralOtherPublicKey == EphemeralPublicKeyLength()
Definition at line 8 of file dh2.cpp. | http://cryptopp.sourceforge.net/docs/ref521/class_d_h2.html | CC-MAIN-2017-13 | en | refinedweb |
/*
* Element;
import org.simpleframework.xml.strategy.Type;
import org.simpleframework.xml.stream.Format;
import org.simpleframework.xml.stream.Style;
/**
* The <code>ElementLabel</code> represents a label that is used to
* represent an XML element in a class schema. This element can be
* used to convert an XML node into either a primitive value such as
* a string or composite object value, which is itself a schema for
* a section of XML within the XML document.
*
* @author Niall Gallagher
* @see org.simpleframework.xml.Element
class ElementLabel extends TemplateLabel {
/**
* This is the decorator that is associated with the element.
*/
private Decorator decorator;
* The contact that this element label represents.
private Introspector detail;
* This is a cache of the expression for this element.
private Expression cache;
* References the annotation that was used by the field.
private Element label;
* This is the format used to style this element label.
private Format format;
* This is the name of the element for this label instance.
private String override;
* This is the path of the XML element from the annotation.
private String path;
* This is the name of the XML element from the annotation.
private String name;
* This is the expected type that has been declared for this.
private Class expect;
* This is the type of the class that the field references.
private Class type;
* This is used to determine if the element is required.
private boolean required;
* This is used to determine if the element is data.
private boolean data;
* Constructor for the <code>ElementLabel</code> object. This is
* used to create a label that can convert a XML node into a
* composite object or a primitive type from an XML element.
*
* @param contact this is the field that this label represents
* @param label this is the annotation for the contact
* @param format this is the format used to style this element
public ElementLabel(Contact contact, Element label, Format format) {
this.detail = new Introspector(contact, this, format);
this.decorator = new Qualifier(contact);
this.required = label.required();
this.type = contact.getType();
this.override = label.name();
this.expect = label.type();){
Type contact = getContact();
if(expect == void.class) {
return contact;
}
return new OverrideType(contact, expect);
* Creates a converter that can be used to transform an XML node to
* an object and vice versa. The converter created will handles
* only XML elements and requires the context object to be provided.
* @param context this is the context object used for serialization
* @return this returns a converter for serializing XML elements
public Converter getConverter(Context context) throws Exception {
Type type = getContact();
if(context.isPrimitive(type)) {
return new Primitive(context, type);
}
return new Composite(context, type);
return new Composite(context, type, expect);
*) {
return null;
*;
return expect;
*();
} | http://simple.sourceforge.net/download/stream/report/cobertura/org.simpleframework.xml.core.ElementLabel.html | CC-MAIN-2017-13 | en | refinedweb |
Vert.x HTTP Client
Vert.x contains a HTTP client that makes it easy to make HTTP requests asynchronously. Remember, every IO action
in Vert.x must be performed asynchronously to avoid blocking the event loop. The event loop is the thread(s) that
manages your verticles and their handlers. Java's built-in
URL and
URLConnection are
not asynchronous, so you should not use these classes in your Vert.x apps.
Creating an HTTP Client
You create a Vert.x HTTP client like this:
HttpClient httpClient = vertx.createHttpClient();
When you create a Vert.x HTTP client from inside a verticle, it looks like this:
public class VertxHttpClientVerticle extends AbstractVerticle { @Override public void start() throws Exception { HttpClient httpClient = vertx.createHttpClient(); } }
Sending a GET Request
Once you have created the Vert.x HTTP client you can send a GET request using its
getNow() method.
Here is a Vert.x
HttpClient
getNow() example:
httpClient.getNow(80, "tutorials.jenkov.com", "/", new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse httpClientResponse) { System.out.println("Response received"); } });
The first parameter to the
getNow() method is the TCP port to connect to the remote HTTP server on.
The
getNow() method exists in a version where you can leave the port out. The port will then default
to port 80 which is the HTTP protocol's default TCP port.
The second parameter to the
getNow() method is the domain name of the remote HTTP server to connect to. Notice that there is not
"http://" in front of the domain name. The Vert.x HTTP client knows that this is an HTTP request, so you don't need
to include the protocol in the domain name.
The third parameter to the
getNow() method is the URI to the resource to retrieve. The example
above retrieves the frontpage of the website ("/"). Another URI could have been
"/vert.x/index.html".
The fourth parameter is a
Handler implementation which is called when the response for the HTTP request
is received. How to handle the HTTP response is explained below.
Handling the HTTP Response
The
Handler implementation passed to the
getNow() method is called when the headers
of the HTTP response are received. If you do not need to access the response body, you can process the response
already in this handler.
However, if you do need to access the body of the HTTP response, you need to register another handler on the
HttpClientResponse that is passed as parameter to the first
Handler's
handle()
method. Here is how that looks:
httpClient.getNow(80, "tutorials.jenkov.com", "/", new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse httpClientResponse) { httpClientResponse.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer buffer) { System.out.println("Response (" + buffer.length() + "): "); System.out.println(buffer.getString(0, buffer.length())); } }); } });
The
Handler implementation passed to the
bodyHandler() method of the
HttpClientResponse
is called when the full HTTP response body is received.
The
Buffer passed as parameter to the body
Handler contains the full HTTP response.
More Methods
The
HttpClient contains a lot more methods for sending GET, POST, PUT, DELETE and HEAD requests.
It also contains more options for configuring the
HttpClient with defaults, and for handling
the HTTP response asynchronously, incrementally, as the response body is received
(instead of when the full body is received). See the Vert.x JavaDoc for more info about these options. | http://tutorials.jenkov.com/vert.x/http-client.html | CC-MAIN-2017-13 | en | refinedweb |
If you have been following me for the last few weeks then you know I’ve been playing with ECMAScript 6, Web Components and Polymer quite extensively. This is all leading towards a major single page application that I want to be driven by the latest standards. My last step is in integrating a web framework. There are lots to choose from, but not many that take web components and ECMAScript 6 seriously. The one I’ve decided to play with is Aurelia as it meets all these requirements plus it has support in Web Essentials 2015.
Before I get into Aurelia for my own project, I want to go through the tutorial. However, I want to go through it with Visual Studio as my IDE (since I’ve already explored the non-IDE route and it is painful). The problem is that Aurelia sort of assumes a Node stack and I want this to run with a Visual Studio ASP.NET stack.
Integrating JSPM
My first problem is that Aurelia likes jspm. This makes sense – it’s built on top of the system.js loader and es6-module-loader, so it makes for a cleaner ES6 integration. But Visual Studio doesn’t natively support JSPM or ECMAScript 6. However, we can integrate it with some up-front work. First, create the Visual Studio project (or download mine at my GitHub repository).
Then open up a PowerShell prompt (you don’t have to be Administrator) and type in the following:
npm install -g jspm
This will install jspm and all its dependencies in your account. The jspm binary is placed in ~\AppData\Roaming\npm. I highly recommend you add this to your PATH permanently since all the global npm-installed tools get a link there. I can now create a jspm configuration for this project. To do this, change directory to the project and run the following (screen shot with prompts filled in):
As you can see, I’ve selected the wwwroot directory and the babel transpiler. I did have to change around the back-slashes for forward slashes afterwards. Here is a look at the resulting package.json:
{ "version": "1.0.0", "name": "AureliaTutorial", "private": true, "devDependencies": { "gulp": "^3.8" }, "jspm": { "directories": { "baseURL": "wwwroot", "lib": "wwwroot", "packages": "wwwroot/jspm_packages" } } }
In addition, a wwwroot/config.js was created – here are the contents of that:
System.config({ "baseURL": "/", "transpiler": "babel", "paths": { "*": "*.js" } });
Notice all the files under jspm_packages as well? We don’t need those to be checked in, so make sure you add jspm_packages to the list of ignores in .gitignore. I’ve done this and checked it in to my repository.
Starting the Tutorial
The first step in the tutorial was to create a HTML page called index.html. In the tutorial, this is created in the root directory. In my version, this is created in the wwwroot directory. It’s contents are also slightly different because I want to see what I can alter. Here is my version:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="jspm_packages/github/twbs/bootstrap@3.3.2/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="jspm_packages/npm/font-awesome@4.3.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="styles/styles.css"> </head> <body aurelia-app> <script src="jspm_packages/system.js"></script> <script src="config.js"></script> <script> System.import('aurelia-bootstrapper'); </script> </body> </html>
I don’t actually have bootstrap, font-awesome or aurelia-bootstrapper yet. I do have system.js – this was included as part of the jspm init. In addition I have a starting point for config.js. My next step was to expand on the config.js based on what was in the skeleton config.js:
System.config({ "paths": { "*": "*.js", "github:*": "/jspm_packages/github/*.js", "npm:*": "/jspm_packages/npm/*.js" } }); System.config({ "map": { .2", "font-awesome": "npm:font-awesome@4.3.0", "github:aurelia/binding@0.3.7": { "aurelia-dependency-injection": "github:aurelia/dependency-injection@0.4.5", "aurelia-metadata": "github:aurelia/metadata@0.3.3", "aurelia-task-queue": "github:aurelia/task-queue@0.2.5" }, "github:aurelia/bootstrapper@0.9.5": { "aurelia-event-aggregator": "github:aurelia/event-aggregator@0.2.4", "aurelia-framework": "github:aurelia/framework@0.8.8", "aurelia-history": "github:aurelia/history@0.2.4", "aurelia-history-browser": "github:aurelia/history-browser@0.2.5", "aurelia-loader-default": "github:aurelia/loader-default@0.4.3", "aurelia-logging-console": "github:aurelia/logging-console@0.2.4", "aurelia-router": "github:aurelia/router@0.5.8", "aurelia-templating": "github:aurelia/templating@0.8.14", "aurelia-templating-binding": "github:aurelia/templating-binding@0.8.7", "aurelia-templating-resources": "github:aurelia/templating-resources@0.8.10", "aurelia-templating-router": "github:aurelia/templating-router@0.9.4" }, "github:aurelia/dependency-injection@0.4.5": { "aurelia-metadata": "github:aurelia/metadata@0.3.3", "core-js": "npm:core-js@0.4.10" }, "github:aurelia/framework@0.8.8": { "aurelia-binding": "github:aurelia/binding@0.3.7", "aurelia-dependency-injection": "github:aurelia/dependency-injection@0.4.5", "aurelia-loader": "github:aurelia/loader@0.3.5", "aurelia-logging": "github:aurelia/logging@0.2.5", "aurelia-metadata": "github:aurelia/metadata@0.3.3", "aurelia-task-queue": "github:aurelia/task-queue@0.2.5", "aurelia-templating": "github:aurelia/templating@0.8.14" }, "github:aurelia/history-browser@0.2.5": { "aurelia-history": "github:aurelia/history@0.2.4", "core-js": "npm:core-js@0.4.10" }, "github:aurelia/http-client@0.5.5": { "aurelia-path": "github:aurelia/path@0.4.5", "core-js": "npm:core-js@0.4.10" }, "github:aurelia/loader-default@0.4.3": { "aurelia-loader": "github:aurelia/loader@0.3.5", "aurelia-metadata": "github:aurelia/metadata@0.3.3", "aurelia-path": "github:aurelia/path@0.4.5" }, "github:aurelia/loader@0.3.5": { "aurelia-html-template-element": "github:aurelia/html-template-element@0.1.3", "core-js": "npm:core-js@0.4.10", "webcomponentsjs": "github:webcomponents/webcomponentsjs@0.5.5" }, "github:aurelia/router@0.5.8": { "aurelia-dependency-injection": "github:aurelia/dependency-injection@0.4.5", "aurelia-event-aggregator": "github:aurelia/event-aggregator@0.2.4", "aurelia-history": "github:aurelia/history@0.2.4", "aurelia-path": "github:aurelia/path@0.4.5", "aurelia-route-recognizer": "github:aurelia/route-recognizer@0.2.4", "core-js": "npm:core-js@0.4.10" }, "github:aurelia/templating-binding@0.8.7": { "aurelia-binding": "github:aurelia/binding@0.3.7", "aurelia-templating": "github:aurelia/templating@0.8.14" }, "github:aurelia/templating-resources@0.8.10": { "aurelia-binding": "github:aurelia/binding@0.3.7", "aurelia-dependency-injection": "github:aurelia/dependency-injection@0.4.5", "aurelia-logging": "github:aurelia/logging@0.2.5", "aurelia-templating": "github:aurelia/templating@0.8.14", "core-js": "npm:core-js@0.4.10" }, "github:aurelia/templating-router@0.9.4": { "aurelia-dependency-injection": "github:aurelia/dependency-injection@0.4.5", "aurelia-metadata": "github:aurelia/metadata@0.3.3", "aurelia-path": "github:aurelia/path@0.4.5", "aurelia-router": "github:aurelia/router@0.5.8", "aurelia-templating": "github:aurelia/templating@0.8.14" }, "github:aurelia/templating@0.8.14": { "aurelia-binding": "github:aurelia/binding@0.3.7", "aurelia-dependency-injection": "github:aurelia/dependency-injection@0.4.5", "aurelia-html-template-element": "github:aurelia/html-template-element@0.1.3", "aurelia-loader": "github:aurelia/loader@0.3.5", "aurelia-logging": "github:aurelia/logging@0.2.5", "aurelia-metadata": "github:aurelia/metadata@0.3.3", "aurelia-path": "github:aurelia/path@0.4.5", "aurelia-task-queue": "github:aurelia/task-queue@0.2.5", "core-js": "npm:core-js@0.4.10" } } });
That’s a lot of mapping, but it’s boiler-plate going forward, which is why I’v collapsed it in the code-block above. Note that I have changed the paths section in the top config section from the skeleton-config to match my environment. I’ve also only included the libraries that I need in the map section. A lot of the jspm_modules were for gulp and the build system which I don’t need because I’m going to handle those separately. In addition I need to define some dependencies in my package.json file:
{ "version": "1.0.0", "name": "AureliaTutorial", "private": true, "devDependencies": { "gulp": "^3.8" }, "jspm": { "directories": { "baseURL": "wwwroot", "lib": "wwwroot", "packages": "wwwroot/jspm_packages" }, "dependencies": { .1", "font-awesome": "npm:font-awesome@^4.3.0" } } }
As with the config.js, this is boilerplate that comes from the skeleton-navigation project. Go back to your PowerShell prompt, change directory to your project directory and run jspm install. jspm will install all the dependencies for you.
Some dependencies were not installed on the first time I ran jspm install because GitHub rate limits unauthenticated connections. The fix is to use an authenticated GitHub connection. Go back to your PowerShell prompt and run:
jspm endpoint config github
The command will prompt you for your GitHub credentials. Register an account if you don’t have one already. You can re-run the jspm install to install the rest of the dependencies. Note that running jspm install seems to sometimes affect the config.js file, specifically changing the paths element to be jspm_packages/ instead of /jspm_packages/ – this is a major pain for me, so I just look at it after I run jspm install to ensure it is doing the right thing.
Note how you can pick between github/bower and npm packages? That’s called the best of both worlds.
A final item before I make my first test run – copy the styles/styles.css from the skeleton-navigation project to wwwroot/styles/styles.css.
At this point you will be able to run the project and see the effects. You will get something like the following in the console window:
I’m on track with the tutorial because that notes that you don’t have an app.js either!
Integrating Gulp Building
Continuing the tutorial, you are asked to create an app.js and an app.html. I’ve created a project directory (not in wwwroot – at the top level) called src In it I placed copies of the app.js and app.html files. I’m not going to bore you with the contents here. The point of this article is to provide the additional bits to enable you to run through the tutorial.
Keeping the files in src isn’t going to help much. I want to transpile them using the babel compiler into system.js compatible modules and place them in the wwwroot/app directory. I’m going to have to do some work on the gulp front for this. I already have a template Gulpfile.js so I just have to add some dependencies into my package.json file and then wire up a task to do this. Let’s take a look at the tasks first. I’ve added the following into my Gulpfile.js:
var gulp = require("gulp"), babel = require("gulp-babel"), sourcemaps = require("gulp-sourcemaps"); gulp.task('build:js', function () { return gulp.src("src/**/*.js") .pipe(sourcemaps.init()) .pipe(babel({ modules: "system" })) .pipe(sourcemaps.write({ includeContent: false, sourceRoot: "/src/" })) .pipe(gulp.dest("wwwroot/")); }); gulp.task('build:html', function () { return gulp.src("src/**/*.html") .pipe(gulp.dest("wwwroot/")); }); gulp.task("_build", ["build:js", "build:html"]);
My package.json dependencies looks like this:
"devDependencies": { "gulp": "^3.8", "gulp-babel": "^4.0", "gulp-sourcemaps": "^1.5" },
Note that I’m building directly into wwwroot. When the Aurelia system asks for app.html, it expects it to be in the same path as app.js. I am asking system.js to modify the relative URL of the file by specifying a baseUrl. So, for instance, system.js will load ./app.js (which is actually, say, wwwroot/dist/app.js) and then the ./app.html (which is wwwroot/app.html) because I didn’t modify those paths without a custom router in the ASP.NET side of things.
Running this version (which is tagged t-3 in my repository) finally gives us some output and it works per the tutorial.
Adding Navigation
At this point I wanted to start putting my views in a sub-directory. The key to this is the moduleId in the router. But I am getting ahead of myself. I copied the app.html and app.js to a sub-directory or src called views and renamed them to welcome.html and welcome.js. I then put the following in the app.js file:
import {Router} from 'aurelia-router'; export class App { static inject() { return [ Router ]; } constructor(router) { this.router = router; this.router.configure(config => { config.title = 'Aurelia'; config.map([ { route: ['', 'welcome'], moduleId: 'views/welcome', nav: true, title: 'Welcome' } ]); }); } }
Note the change to the moduleId – I’ve now got my views in a sub-directory, just the way I like it. The app.html file was a direct copy of the one from the tutorial.
The tutorial then goes on to add a second page. I again put the files in the views directory before adding the second page to the config.map and altering it’s moduleId. A quick build and it was working again.
Note that I am not using browser-sync as yet. My preference is to do the build, then refresh after I see things are in the right place. I’ve found that the gulp watch process is fairly fragile under Visual Studio 2015 CTP 6 – hopefully, they will get this working better under the RTM.
I’ve checked in this checkpoint as AureliaTutorial-t-4 on my GitHub Repository.
Custom Elements
To keep my custom elements separate from my views, I placed the nav-bar into a new directory called elements (in the src tree). The app.html file became:
<template> <import from='./elements/nav-bar'></import> <nav-bar router.</nav-bar> <div class="page-host"> <router-view></router-view> </div> </template>
The only real difference here is one of choice. I want my views and elements separated. Continue on to the child router (don’t forget to prefix your moduleId with views/).
Tutorial Complete. You can find the code to my version of the tutorial (including the steps along the way) on my GitHub Repository. | https://shellmonger.com/2015/03/31/aurelia-and-visual-studio-2015/ | CC-MAIN-2017-13 | en | refinedweb |
I have a requirement that some registered users with specific role should be able to create articles, but they should not have access to CMS administration UI. Is there any built-in feature to support such case? As I remember EPiServer CMS 6 had on-page editing without CMS menus etc.
Currently I see only option to create custom page from where user posts all fields required to create article pages, but it duplicates CMS editing features for article page type.
Had a simular request ones. Belive I used quick publish to solve it that time.
The article about quick publish is for EPiServer 6, but I am using EPiServer 7.5/8.
Another option I am looking at is to allow those users to access CMS, but hide as much as possible of admin features.
I already got to showing only pages with Edit access in the page tree as described in this article:
Hi Maris!
Since the EPiServer 7 editing interface is much more advanced and the parts fit together, for instance giving the ability to drag and drop pages and media into the editors, we decided to abandon the somewhat two more simplified editing "modes" that existed in EPiServer CMS 6, on page edit and simple editing. You can modify the views to suite certain roles as described here:
Also, I can mention that I'm somewhat helping out on a prototype project to add templates to EPiServer. The idea is to have an gadget with templates and to be able to create new items from the templates, for instance "New article", "New news page" etc. This is still in early prototyping but is might be something that could solve this need, combined with a modified view.
Thanks Linus!
It seems that allowing those users to access admin mode is fine and could be adjusted as needed with these solutions:
Also I am building the page to help users to start page creation by filling required values and after page creation redirect to edit mode. Now I need to get the page Edit URL.
Is there any builtin method to get page Edit URL?
The class EPiServer.Cms.Shell.IContentExtensions has a number of extension methods you can use. GetUri is the simplest and will create a URI for the current mode (site, preview or edit). There is also more specific methods that will give you more control, such as getting the URL for a pre-defined mode.
Just tested - GetUri works great!
Here is the sample:
using EPiServer.Cms.Shell;
...
var newPage = _contentRepository.GetDefault<PageData>(parentLink, contentType.ID, LanguageSelector.AutoDetect());
newPage.Name = "Page name";
_contentRepository.Save(newPage, SaveAction.Save);
var editUri = newPage.GetUri();
...
Actually GetUri did not work as I wanted. It returns only part of edit URL. For example, "epi.cms.contentdata:///1995_5754".
I did some research and found solution in ContentSearchProviderBase constructor. Using this solution created extension method which returns full edit URL:
public static string GetEditUrl(this IContent content, string languageName = null, bool relativeUrl = true)
{
var cmsEditUrl = GetSiteEditUrl(relativeUrl);
var contentEditUri = content.GetUri(true);
return !string.IsNullOrWhiteSpace(languageName)
? string.Format("{0}?language={1}#context={2}", cmsEditUrl, languageName, contentEditUri)
: string.Format("{0}?#context={1}", cmsEditUrl, contentEditUri);
}
private static string GetSiteEditUrl(bool relativeUrl)
{
var cmsEditUrl = SiteDefinition.Current.GetFullUrlToEditView(null);
return relativeUrl
? new Uri(cmsEditUrl).PathAndQuery
: cmsEditUrl;
}
© Episerver 2017 |
About Episerver World | http://world.episerver.com/forum/developer-forum/-Episerver-75-CMS/Thread-Container/2015/3/on-page-editing-outside-cms-admin/ | CC-MAIN-2017-13 | en | refinedweb |
#include <Pt/System/Timer.h>
Notifies clients in constant intervals. More...
Timers can be used to be notified if a time interval expires. It usually works with an event loop, where the Timer needs to be registered. Timers send the timeout signal in given intervals, to which the interested clients connect. The interval can be changed at any time and timers can switch between an active and inactive state.
The following code calls the function onTimer every second:
Constructs an inactive timer.
The destructor sends the destroyed signal.
Start a timer from the moment this method is called. The Timer needs to be registered with an event loop, otherwise the timeout signal will not be sent.
If the Timer is registered with an event loop, the timout signal will not be sent anymore.
This signal is sent if the interval time has expired. | http://pt-framework.org/htdocs/classPt_1_1System_1_1Timer.html | CC-MAIN-2017-13 | en | refinedweb |
Created on 2015-04-07 16:23 by serhiy.storchaka, last changed 2016-06-06 02:30 by python-dev.
Here is a (perhaps incomplete) list of documented names absent in __all__ lists of respective modules. Perhaps some of them (but not all) are worth to be added to __all__ lists.
calendar.Calendar
calendar.HTMLCalendar
calendar.TextCalendar
cgi.test
configparser.Error
csv.unix_dialect
doctest.DocFileCase
doctest.DocTestCase
enum.EnumMeta
fileinput.fileno
ftplib.Error
ftplib.error_perm
ftplib.error_reply
gettext.bind_textdomain_codeset
gettext.lgettext
gettext.lngettext
http.client.HTTPMessage
http.cookies.Morsel
http.server.test
logging.shutdown
mailbox.Error
mailbox.ExternalClashError
mailbox.NoSuchMailboxError
mailbox.NotEmptyError
mimetypes.MimeTypes
optparse.check_choice
pickletools.OpcodeInfo
plistlib.InvalidFileException
pydoc.doc
smtpd.SMTPChannel
subprocess.SubprocessError
subprocess.TimeoutExpired
tarfile.CompressionError
tarfile.HeaderError
tarfile.ReadError
tarfile.open
threading.BrokenBarrierError
tkinter.ttk.Widget
tokenize.open
traceback.FrameSummary
traceback.StackSummary
traceback.TracebackException
traceback.walk_stack
traceback.walk_tb
wave.Wave_read
wave.Wave_write
xml.etree.ElementTree.XMLPullParser
http.client.HTTPMessage: See Issue 23439. There was resistance to adding this (and the status code constants), though IMO they should be added, since they are documented public APIs.
http.server.test(): In Issue 23418, I consciously left this function out. It is only mentioned as a place to look for sample code, as far as I can tell.
New changeset ebf3e6332a44 by Berker Peksag in branch 'default':
Issue #23883: Add missing entries to traceback.__all__.
May be makes sense to add a helper in test.support that implements a test similar to the one in issue23411, and add tests for __all__ in multiple modules.
I working on these three.
calendar.Calendar
calendar.HTMLCalendar
calendar.TextCalendar
Changes would be the same as for every module?
Serhiy: Yes I was also thinking it might be time for a common helper function.
Milap: I think changes like you mentioned (originally by me) would be fine. Another variation was done for Issue 10838: revision 10b0a8076be8, which expects each object that is not a module object (e.g. not from “import sys”), rather than expecting each object that is a function or class defined in the module. It might depend on the particular circumstance which technique is superior.
New changeset 86fbe140e395 by Andrew Kuchling in branch '2.7':
#23883: add names missing from __all__ (l*gettext, bind_textdomain_codeset)
New changeset 717d87c13f0d by Andrew Kuchling in branch '3.4':
#23883: add names missing from __all__ (l*gettext, bind_textdomain_codeset)
I took care of the tarfile module.
Added the following according to the first message:
tarfile.CompressionError
tarfile.HeaderError
tarfile.ReadError
tarfile.open
The following were included in __all__ that were not explicitly mentioned in the first message but were denoted as an exported function, exported class, or an exported error.
tarfile.main
tarfile.TarIter
tarfile.StreamError
tarfile.ExtractError
tarfile.SubsequentHeaderError
tarfile.InvalidHeaderError
tarfile.EmptyHeaderError
tarfile.EOFHeaderError
tarfile.TruncatedHeaderError
This is my first patch so feedback is highly appreciated.
Regarding tarfile: Two of the extra errors are documented, so I agree they should be added:
* tarfile.StreamError
* tarfile.ExtractError
However I’m not so sure about main(), TarIter, and the HeaderError subclasses. They aren’t mentioned in the documentation. At least main() and TarIter are just implementation details I think.
There are other documented items that should be added in my opinion. These would not be picked up by the proposed test, although they would be picked up by making the test like in revision 10b0a8076be8.
* ENCODING
* USTAR/GNU/PAX/DEFAULT_FORMAT
Thanks for the feedback. I was unsure how to proceed with the undocumented items that seemed to be categorized as exported. Thanks for catching ENCODING & *_FORMAT.
Oh I see, TarIter is listed underneath a comment saying “Exported Classes”, and main() is listed underneath “exported functions”. If they are indeed meant to be exported, they should probably also be documented. Otherwise, maybe we can just add another comment clarifying that they are internal.
In the latest patch, I think HeaderError should be added back to __all__; it is just its subclasses that are not documented. Also XHDTYPE is listed twice in the test case.
If it were up to me, I would add the TarInfo.type constants (REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE). But I’m not sure if others would agree.
Put HeaderError back in and removed the extra XHDTYPE.
We can get more input on the type constants as well as the undocumented but exported items. Could just be cleared up with some edits to documentation.
I?
Woops just noticed above in the issue someone else picked up the Calendar __all__. I am genuinely sorry I didn't intend to duplicate the effort.
Hi guys!
Here is a patch for the fileinput module, with some names beyond fileinput.fileno: fileinput.hook_compressed, fileinput.hook_encoded as mentioned in the docs
This is my first patch as well, so feedback's appreciated!
Hi! This is my first attempt at contributing so as always, feedback will be well appreciated. :)
I meant to start small so I took a shot with csv module. In test, initial expected set contains QUOTE_* because they don't provide __module__ attribute, and __doc/version__ because they are already in csv.__all__ (should they?).
I've made a few PEP8-related fixes just around code I've touched (so they aren't completely unrelated). Is that ok?
Reviews.
Thank.
> ftplib and threading have more functions
I've meant function and exceptions, of course. Sorry for the noise.
I've added previously missing test and docs for test.support.check__all__ in Issue23883_support_check__all__.v2.patch . Awaiting review. :)
To..
===
Serhiy: ftplib.Error does not actually appear to be documented. Perhaps it should not be added to __all__ after all? (excuse the pun)
> Nice work with the check__all__() function.
Thank you! :)
>.
Could you please elaborate on "making the test stricter"?
I'd go with the first check + optional name_of_module. With second one alone, all freshly added test__all__ tests would need additional names in blacklists - not huge ones, but they would otherwise be unnecessary.
I've amended the patches and I'm waiting for review.
I've also thought of not only making name_of_module param optional, but to make it extra_names_of_module (so such param would be added to module.__name__ used in "getattr(module_object, '__module__', None) in name of module" check. It would account for less typing in general (module.__name__ occurs in almost all cases), but also less explicity. What do you think?
> Serhiy: ftplib.Error does not actually appear to be documented. Perhaps it should not be added to __all__ after all? (excuse the pun)
Agree. The list is only cursorily filtered result of some one-liners and can contain false names.
Adding new names to __all__ can have undesired effect and break user code (by hiding builtins as for tarfile.open). Perhaps not all documented names should be imported with "import *". In any case it is too late for 3.5.
I think names should be in __all__ even if they shadow builtins, at least in a new feature release. There is plenty of precedent, e.g. asyncio.TimeoutError; reprlib.repr(); threading.enumerate(). Modules with open() in __all__ include aifc, bz2, codecs, dbm, dbm.dumb, gzip, lzma, os, shelve, wave and webbrowser. Plus, pydoc ignores things excluded from __all__.
J.
The.
> In any case it is too late for 3.5.
Ok, next round of patches is based on default branch.
> Jacek: If we used the ModuleType check, and somebody adds a module-level constant (like logging.CRITICAL = 50), the test will automatically detect if they forget to update __all__. That is what I meant by the test being stricter.
Right and I think such case should be covered as well. I think it may be worth the hassle of adding new condition in detecting names expected to be documented, so the whole if clause would look like:
if (getattr(module_object, '__module__', None) in name_of_module
or (not isinstance(module_object, types.ModuleType)
and not hasattr(module_object, '__module__'))):
expected.add(name)
Obviously tradeoff lies in required blacklisting:
* with previous __module__ check - all undocumented, non "_*" names defined in checked module, but constants need to be in *extra* and new ones won't be detected
* with ModuleType check only - all undocumented, non "_*" names defined in checked module + all functions and classes imported from other modules needs blacklisting
* with extended __module__ check (proposed above) - all undocumented, non "_*" names defined in checked module + all constants imported from other modules; this choice also requires less 'extra' params (in fact, in these patches only csv.__doc/version__ case left)
In this round of patches I went the new, third way.
One odd thing: in test.test_logging, are these:
3783: self.addCleanup(setattr, logging, 'raiseExecptions', old_raise)
3790: self.addCleanup(setattr, logging, 'raiseExecptions', old_raise)
("Ex*ec*ptions") really typos or is it intentional? test.test_logging has raiseExceptions name as well.
Also, pickletools.OpcodeInfo and threading.ThreadError are not really documented, are they?
That raiseExecptions thing looks like a typo to me. The code should probably be monkey patching the module variable, and restoring it after the test. Then you wouldn’t need to add your extra typoed version to the blacklist.
In the logging module, I reckon raiseExceptions (non-typoed) should actually be added to __all__. It is documented under Handler.handleError().
pickletools.OpcodeInfo: It is briefly mentioned as the type of the first item of genops(). I don’t have a strong opinion, but I tended to agree with your previous patch which added it to __all__.
threading.ThreadError: It is not documented, but it was already in __all__. I think it should be restored, in case someone’s code is relying on it.
I'm getting patches ready with amendments you've proposed. Two things, though (and two on Rietveld):
> That raiseExecptions thing looks like a typo to me. The code should probably be monkey patching the module variable, and restoring it after the test. Then you wouldn’t need to add your extra typoed version to the blacklist.
Wouldn't it be better to just blacklist the typoed version in this patch, with proper comment, and then fix the typo along with test? Working it around like you proposed looks like unnecessary overkill. I'm also not yet sure where is the "don't change too much in one patch" border.
> pickletools.OpcodeInfo: It is briefly mentioned as the type of the first item of genops(). I don’t have a strong opinion, but I tended to agree with your previous patch which added it to __all__.
That addition was a little absentminded of me, sorry for that. Is such brief mention considered a documentation for a part of API in this case?
raiseExecptions typo: Might be best to get the typo fixed first (maybe open a separate issue, since it should probably be fixed starting from the 3.4 branch).
Regarding OpcodeInfo, it is probably up to your judgement.
> raiseExecptions typo: Might be best to get the typo fixed first (maybe open a separate issue, since it should probably be fixed starting from the 3.4 branch).
Done in #24678 and commited in 83b45ea19d00 .
> Regarding OpcodeInfo, it is probably up to your judgement.
Then I'll leave it as it was - without OpcodeInfo in pickletools.__all__ . The test for it remains in the patch, though.
Thank you all for your work and apologies for my lack of response.
I'm +1 on adding a check__all__ helper to test.support. But passing "self" to it feels a bit weird. Perhaps the assertCountEqual part could be moved outside of the helper. If Serhiy(and/or other people) are happy with the current API, I am happy too :)
Here is a brainstorm of alternatives that don’t require passing “self” into a helper function. But IMO the current proposal that does pass “self” is better.
* Passive expected_module_api() function, and manually check the return value. Precedent: support.detect_api_mismatch().
def test_all(self): # In class test.test_tarfile.MiscTest
blacklist = {"bltn_open", ...}
possible_exports = support.expected_module_api(tarfile, ignore=blacklist)
self.assertCountEqual(ftplib.__all__, possible_exports)
* ModuleApiTestBase class. Subclass it to use it:
class ExportsTest(support.ModuleApiTestBase): # In module test.test_tarfile
module = tarfile
ignore = {"bltn_open", ...}
* Raise AssertionError directly in case of failure. No automatic error message showing the different names though. Precedents: support.run_doctest(), .check_warnings(), script_helper.assert_python_ok(), _failure().
* Make a temporary internal TestCase instance:
def check__all__(module, etc):
expected = ...
...
TestCase().assertCountEqual(module.__all__, expected)
Does anyone have strong preference towards one of the propositions above?
TestCase subclass looks reasonable IMHO, but I'd not add that to the scope of this issue (I'd be happy to implement it later, though).
Any suggestions?
many things are not present in os.__all__ that should be, including
os.getcwd
Michael: According to Issue 18554, os.__all__ was fixed in 3.5. Can you confirm? It is working for me:
Python 3.5.0 (default, Sep 20 2015, 11:28:25)
[GCC 5.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> "getcwd" in os.__all__
True
@Martin, my mistake. You're correct. I forgot I was using Python v3.4.
Berker (or anyone else), do you have a preference on how we move forward? I am inclined to use Jacek’s function as it is. I think it is certainly an improvement over the current state. People can propose an alternative version of the function later if they want, though in my opinion the underlying problem is in the architecture of unittest’s assertion methods; see Issue 19645.
I have added comments on Rietveld. Besides few stylistic nitpicks Issue23883_support_check__all__.v5.patch LGTM.
> But passing "self" to it feels a bit weird.
This is not new. There are other testing helpers in test.support that needs passing "self". If the helper is used many times in one test class, I prefer to make a method:
class SomeTest(TestCase):
check_something = test.support.check_something
def test_foo():
self.check_something('foo')
def test_bar():
self.check_something('bar')
But in this case I'm happy with the current API.
Serhiy, thank you for the review. I've made proposed changes (along with rebasing Issue23883_all patch; Issue23883_test_gettext.v3.patch still applies cleanly).
I like Martin's support.expected_module_api() suggestion in msg247167. I still find passing self to a function just to use assertCountEqual a bit weird, but I can live with that.
The reason why I prefer the current API over my support.expected_module_api() idea is it requires the extra assertCountEqual() boilerplate at each call site.
Jacek’s three patches look ready to me. I propose:
1. Commit Issue23883_support_check__all__.v6.patch to 3.6, which everything else depends on.
2. Commit Issue23883_test_gettext.v3.patch to 3.6. (Andrew Kuchling’s original gettext.__all__ fix was made in 3.4 and 2.7 as well, but we would have to backport the support function, or rewrite the test, to apply this to earlier branches.)
3. Commit Issue23883_all.v6.patch to 3.6 only to limit the chance of breaking existing code.
4. Rewrite Mauro SM Rodrigues’s issue23883_fileinput.patch to use support.check__all__().
5. Update Joel Taddei’s Issue23883_tarfile_all.patch and Issue23883_calendar_all.patch for support.check__all__() and addressing review comments.
6. Work on the remaining modules, probably in a separate issue to keep things under control. According to my calculations these modules are: cgi, configparser, doctest, http.cookies, mailbox, mimetypes, plistlib, pydoc, smtpd, tkinter.ttk, tokenize, xml.etree.ElementTree.
Another question that comes to mind: Should we add anything into What’s New, maybe warning of new symbols from “import *”?
> The reason why I prefer the current API over my support.expected_module_api() idea is it requires the extra assertCountEqual() boilerplate at each call site.
I personally find explicit assert* calls in a test case more readable(e.g. I don't need to check what the helper does every N month), but I guess that's another version of tabs vs. space debate :)
> Jacek’s three patches look ready to me. I propose:
Your plan sounds good to me. Thanks!
> Should we add anything into What’s New, maybe warning of new symbols from “import *”?
I guess it wouldn't hurt to add a sentence :)
New changeset f8fa7bc837a3 by Martin Panter in branch 'default':
Issue #23883: Add test.support.check__all__() and test gettext.__all__
New changeset 78d67bdc1142 by Martin Panter in branch 'default':
Issue #23883: Add missing APIs to __all__; patch by Jacek Kołodziej
New changeset 25a7ceed79d1 by Martin Panter in branch 'default':
Issue #23883: Add news listing modules with new exported APIs
Thankyou.
Martin, yay! :) And thank you for the documentation correction.
Milap, Joel, Mauro, are you still interested in working on patches for calendar/tarfile/fileinput patches? I intend to finish them up if that's not the case.
Yes, I'm, I have a commitment now but I'll submit a new version later today
New version.
issue23883_fileinput.v2.patch looks good to me.
Week and no response, I'm posting updated patches for calendar and tarfile.
I committed the last three patches to 3.6:
571632315c36: fileinput
a2ffa9eedb1b: calendar
48090e08e367: tarfile
a5d3ebb6ad2a: Update news
Please let me know if there are some outstanding patches here that I missed. Otherwise, I think we are up to step 6 in <>.
New changeset 571632315c36 by Martin Panter in branch 'default':
Issue #23883: Missing fileinput.__all__ APIs; patch by Mauro SM Rodrigues
New changeset a2ffa9eedb1b by Martin Panter in branch 'default':
Issue #23883: Add missing APIs to calendar.__all__
New changeset 48090e08e367 by Martin Panter in branch 'default':
Issue #23883: Add missing APIs to tarfile.__all__
New changeset a5d3ebb6ad2a by Martin Panter in branch 'default':
Issue #23883: Update news
New changeset 62e925be0aff by Serhiy Storchaka in branch 'default':
Issue #23883: Removed redundant names from blacklists.
Thanks for caring for this Martin.
> Should we add anything into What's New, maybe warning of new symbols from "import *"?
I think yes.
New changeset bd6127a6354f by Martin Panter in branch 'default':
Issue #23883: grp and pwd are None on Windows
Serhiy: I already added a bullet point at <>.
Per Martin's request, I've created a few new issues for next batch of module's __all__ list updates:
* cgi: #27105
* configparser: #27106
* mailbox: #27107
* mimetypes: #27108
* plistlib: #27109
* smtpd: #27110
* tokenize: #27112
I've also looked at pydoc module, but I'm not sure what to do with it: `doc` function has only a brief docstring, it's not mentioned in docs at all. Should it really be in pydoc.__all__?
I think pydoc could be left alone. The RST documentation doesn’t say anything about importing any functions from the module that I can see. I was surprised that it even defines __all__ = ["help"]. Perhaps pydoc.doc() was another false indication in Serhiy’s list.
In this case I'm proposing a small patch just for testing pydoc module's __all__ list and left the decision to you, whether to apply it or not. :)
Test doesn't use test.support.check__all__ (see msg266312) - blacklist would be huge and expected list, as you already pointed out, has only one value.
New changeset a36c7f87eba9 by Martin Panter in branch 'default':
Issue #23883: News updates for __all__ attributes | https://bugs.python.org/issue23883 | CC-MAIN-2017-13 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.