text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
There are several owner draw buttons on this site, but I couldn’t find one that easily supports PNG files with transparency, so I created this class. Since this class uses GDI+, it actually supports many image formats, but the better quality buttons available are now PNG instead of ICO, so that is the one highlighted here. Update: I have an extended version of this class in my Style Toolkit. If all you want is to use an image on a button, this class is probably simpler to use. GDI+ is part of the Microsoft Windows SDK, and it needs to be initialized when the application starts up. If you haven’t used GDI+ before, look at the source code of the demo project and read this article: The image at the top of the page shows the play button in three different states. From left to right, they are: normal, highlighted, and disabled. The other two buttons are just more examples that look cool. It may not be too obvious from the picture that the second button is in the highlighted state. This is by design, I don’t want to significantly change the image. The highlight state just increases the brightness and the contrast a bit. It is obvious enough when you move the mouse over it. This class prioritizes image quality, so it will never stretch or shrink the image which usually degrades the quality, it will just paint the part that fits. If you need to resize your image, use an image editor like Photoshop. The picture below shows the play button in the toggled state, and it should be obvious why you would want such a feature. The exit button is in the highlighted state, and the tool tip is shown in this image. There is no performance penalty for using GDI+ (assuming such a penalty exists) since it is only used during initialization. On creation, the images are converted to bitmaps, and the bitmaps are used when the control needs to be repainted. Add a button to your dialog box with the resource editor, set the resource ID, and erase the text in the Caption box. You could set the style to Owner Draw, but you don’t need to because the code will automatically set this style. Using the Class Wizard, add a variable to the ID you just created. In this example, I set the ID to IDC_PLAY, and the variable name to m_cPlay. Edit the dialog’s .h file, and change the control from CButton to CGdiButton. Don’t forget to include the file “GdipButton.h”. IDC_PLAY m_cPlay CButton CGdiButton In the resource editor, import the .png file from the res folder and set the resource type to PNG. Using PNG is just convention, it can be anything as long as the code matches what you name it. Right click on IDR_PNG1, select Properties, and rename it to something useful, IDR_PLAY in this example. IDR_PNG1 IDR_PLAY Now, we just need to load the image to the button on initialization. In the OnInitDialg() function, add the following code near the bottom: OnInitDialg() BOOL CTestGdipButtonDlg::OnInitDialog() { CDialog::OnInitDialog(); /// a bunch of stuff here m_cPlay.LoadStdImage(IDR_PLAY, _T("PNG")); return TRUE; } You should be able to run it now and see your new PNG button! If it crashes here, it is probably because you didn’t initialize GDI+. Review the Background section of this article. This is all the code that is needed to create the buttons in the test program: // load the standard image and alternate image m_cPlay.LoadStdImage(IDR_PLAY, _T("PNG")); m_cPlay.LoadAltImage(IDR_PAUSE, _T("PNG")); m_cPlay.EnableToggle(TRUE); // just to show highlight state for article m_cPlayHi.LoadStdImage(IDR_PLAY, _T("PNG")); // set as disabled m_cPlayDis.LoadStdImage(IDR_PLAY, _T("PNG")); m_cPlayDis.EnableButton(FALSE); // show a larger button type m_cGear.LoadStdImage(IDR_GEAR, _T("PNG")); // replace the OK button with something m_cShutDn.LoadStdImage(IDR_EXIT, _T("PNG")); m_cShutDn.SetToolTipText(_T("Close Program")); Both the VC6 and VS2005 versions are included in the demo project. The button control has no idea what the background beneath it should be; it gets this information from the bitmap associated with the current DC. In most cases, this works fine, the background is what is on the screen just before the control is painted. However, the application may not be the top most when it is launched. An always on top application like Task Manager may be in the way, so when it gets the background image, it is the wrong data. This is overcome by calling the SetBkGnd() function by the code that actually creates the background. SetBkGnd() Set all the button backgrounds in the parent’s OnEraseBkgnd() function. The demo program does this with the following code: OnEraseBkgnd() BOOL CTestGdipButtonDlg::OnEraseBkgnd(CDC* pDC) { CDialog::OnEraseBkgnd(pDC); CRect rect; GetClientRect(rect); CMemDC pDevC(pDC, rect); // fill in the back ground with something SetButtonBackGrounds(pDevC); return TRUE; } void CTestGdipButtonDlg::SetButtonBackGrounds(CDC *pDC) { m_cPlay.SetBkGnd(pDC); m_cPlayHi.SetBkGnd(pDC); m_cPlayDis.SetBkGnd(pDC); m_cShutDn.SetBkGnd(pDC); } Since the DC that is passed is a memory DC, it doesn’t matter what other applications might be doing. The code above assumes you want to use something other than the crummy default background; otherwise, you would probably just use the default crummy button. VC6 needs a few extra things to compile correctly, add the following to your stdafx.h file. Also add the SDK include and lib paths to your environment. // VC6 #if defined(_MSC_VER) && _MSC_VER == 1200 #ifndef ULONG_PTR #define ULONG_PTR unsigned long* #endif #include <span class="code-keyword"><Specstrings.h></span> #include <span class="code-keyword"><gdiplus.h></span> #pragma comment(lib, "gdiplus.lib") using namespace Gdiplus; // VS2005 #else #include <span class="code-keyword"><gdiplus.h></span> #pragma comment(lib, "gdiplus.lib") using namespace Gdiplus; #endif This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) if (bSwitch) // bSwitch is a static variable pDevC->FillSolidRect(&rect, RGB(255,255,0)); else pDevC->SelectObject(m_hBitmap); void CGdipButton::SetBkGnd(CDC* pDC) { m_bHaveBitmaps = FALSE; m_dcBk.DeleteDC(); m_dcStd.DeleteDC(); m_dcStdP.DeleteDC(); m_dcStdH.DeleteDC(); m_dcAlt.DeleteDC(); m_dcAltP.DeleteDC(); m_dcAltH.DeleteDC(); m_dcGS.DeleteDC(); } General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/26887/A-user-draw-button-that-supports-PNG-files-with-tr?fid=1402009&df=90&mpp=25&noise=3&prof=True&sort=Position&view=None&spc=Relaxed&fr=26
CC-MAIN-2015-35
refinedweb
1,051
55.95
SMS Gateway with Orange SMS API, Python, Nginx, mod_wsgi and Postfix Orange are beginning to open up some of their APIs. One API I'm particularly interested in is the Orange SMS API because during the Alpha Orange are making both sending and receiving SMS messages free of charge. When you sign up at you are given 1000 credits with each text sent costing 10 credits. Each SMS received gains you 2 credits. You can request more messages for testing. Update: You can only send/receive 10 SMS messages per day though. This is completely impractical for any sort of serious debugging so I'm mentioned this to Orange. Here's how the SMS API works. When you send an SMS fro your phone to 967482 Orange looks at the first word to find out which partner account the SMS is for. I've chosen the word FOR so SMS messages starting FOR are sent to me. In the control panel I can choose to have such messages sent on to an email address, passed as query parameters to a URL or both. These can then be processed. In this article we are going to do three things: - Create a Phone to server gateway so that SMS messages sent to 967482 and starting FOR can be handled by our server - Create a server to SMS gateway so that we can send SMS messages from the server - Create an email to SMS gateway so that people can send SMS messages by writing emails to a particular address - Create an SMS to email gateway so that people can send emails from their phones via SMS Register with Orange First register as an Orange partner and choose a keyword in the Administrator Web Interface. I've chosen FOR. You'll be given an access key which you'll need to make a note of and keep secret. Choose for received messages to be sent to a URL. I'm going to choose Setting up The Server I created a new Xen virtual machine and pointed sms.3aims.com to that machine. Next I create a new user called sms and install some software on the virtual machine: adduser sms apt-get install python2.5 python2.5-dev build-essential mysql-server-5.0 screen mercurial subversion python2.4 python2.4-dev libpcre3-dev libssl-dev Then as sms let's set up a virtual Python install: cd /home/sms mkdir download mkdir lib cd download wget tar zxfv virtualenv-1.0.tar.gz cp virtualenv-1.0/virtualenv.py ./ python2.5 virtualenv.py --no-site-packages ~/env We are going to serve the project using Nginx and the mod_wsgi plugin for no other reason than I haven't tried it before: cd ~/download wget cd ../lib tar zxfv ../download/nginx-0.5.34.tar.gz hg clone You'll need to patch mod_wsgi/config to set PYTHON to python2.5. Now compile and install nginx: cd nginx-0.5.34 ./configure --add-module=/home/sms/lib/mod_wsgi --with-debug --with-http_ssl_module --sbin-path=/usr/local/sbin make We’ll use the script from Slicehost which is itself based on the Debian package: cd ~/download wget chmod +x nginx then as root: cd /home/sms/lib/nginx-0.5.34 make install cd /home/sms/download mv nginx /etc/init.d /usr/sbin/update-rc.d -f nginx defaults ln -s /usr/local/nginx/conf/nginx.conf /etc/nginx.conf Edit /etc/nginx.conf to replace the http section with this: worker_processes 5; http { include conf/mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 60; wsgi_enable_subinterpreters on; env PYTHON_EGG_CACHE=/home/sms/cache; server { listen 80; server_name sms.3aims.com; location / { wsgi_pass /home/sms/sms/handle.py; wsgi_var PATH_INFO $fastcgi_script_name; wsgi_var REQUEST_METHOD $request_method; wsgi_var QUERY_STRING $query_string; wsgi_var SERVER_NAME $server_name; wsgi_var SERVER_PORT $server_port; wsgi_var SERVER_PROTOCOL $server_protocol; wsgi_var CONTENT_TYPE $content_type; wsgi_var CONTENT_LENGTH $content_length; wsgi_pass_authorization off; wsgi_script_reloading on; wsgi_use_main_interpreter on; # If you were using Pylons you'd add this, but we don't need to # wsgi_python_optimize 0; # pylons uses doc strings... } } } Nginx has an asynchronous architecture and by default only has one worker process. This means that if your Python WSGI application served from Nginx blocks for any reason (perhaps database access for example) then the whole server will block. Two solutions are: - Increase the number of worker threads - Make sue you use the asynchronous WSGI extensions provided by mod_wsgi We've already increased the number of worker threads to 5 but in order to program asynchronously we have to use a slightly different architecture to something like Pylons. By the way, notice the line to set the value of PYTHON_EGG_CACHE. This is essential so that setuptools doesn't complain. We'll create this directory and set the permissions in a bit. Test Application Now that the server is set up, let's write a test application. We want this application to be able to use the virtual environment we set up for Python so there are a few lines at the front to set up the correct paths: import site site.addsitedir('/home/sms/env/lib/python2.5') site.addsitedir('/home/sms/env/lib/python2.5/site-packages') def application(environ, start_response): start_response('200 OK', [('Content-type','text/html')]) return ['Hello World!'] Save this as /home/sms/sms/handle.py then restart the Nginx server. You'll also need to create /home/sms/cache then change its permissions with chmod 777 /home/sms/cache. Visit and you'll see the Hello World! message. Setting up Email on the Server We're going to use Postfix 2.5 (just because I like the milter support of Postfix 2.4 which Postfix 2.3 which comes with etch doesn't support) but otherwise the installation will be compatible with the excellent tutorial by Chris Haas at Setting up the hostname Become root on your server and make sure that /etc/hostname contains the host name without the domain part. The file /etc/mailname should contain the fully-qualified host name with the domain part. You'll probably need to fix /etc/hosts too. Run hostname --fqdn and see if you get the fully-qualified hostname. If you just get the hostname without the domain please check that your /etc/hosts file has the fully-qualified hostname first in the list. Wrong: 78.47.146.250 sms sms.3aims.com Right: 78.47.146.250 sms.3aims.com sms Setting the Locale As root: apt-get install locales Then if needed: apt-get install debconf dpkg-reconfigure locales Here's what you get: Package configuration ┌──────────────────────────┤ Configuring locales ├──────────────────────────┐ │ │ │ Locale is a framework to switch between multiple languages for users who │ │ can select to use their language, country, characters, collation order, │ │ etc. │ │ │ │ Choose which locales to generate. The selection will be saved to │ │ `/etc/locale.gen', which you can also edit manually (you need to run │ │ `locale-gen' afterwards). │ │ │ │ When `All locales' is selected, /etc/locale.gen will be set as a symlink │ │ to /usr/share/i18n/SUPPORTED. │ │ │ │ <Ok> │ │ │ └───────────────────────────────────────────────────────────────────────────┘ Select the locale(s) you want: Package configuration ┌──────┤ Configuring locales ├───────┐ │ Locales to be generated: │ │ [ ] en_BW ISO-8859-1 │ [ ] en_BW.UTF-8 UTF-8 │ [ ] en_CA ISO-8859-1 │ [ ] en_CA.UTF-8 UTF-8 │ [ ] en_DK ISO-8859-1 │ [ ] en_DK.ISO-8859-15 ISO-8859-15 │ [ ] en_DK.UTF-8 UTF-8 │ [ ] en_GB ISO-8859-1 │ [ ] en_GB.ISO-8859-15 ISO-8859-15 │ [*] en_GB.UTF-8 UTF-8 │ [ ] en_HK ISO-8859-1 │ [ ] en_HK.UTF-8 UTF-8 │ │ │ <Ok> <Cancel> │ │ └────────────────────────────────────┘ I choose to make the new locale the default: Package configuration ┌─────────────────────────┤ Configuring locales ├─────────────────────────┐ │ Many packages in Debian use locales to display text in the correct │ │ language for users. You can change the default locale if you're not a │ │ native English speaker. These choices are based on which locales you │ │ have chosen to generate. │ │ │ │ Note: This will select the language for your whole system. If you're │ │ running a multi-user system where not all of your users speak the │ │ language of your choice, then they will run into difficulties and you │ │ might want not to set a default locale. │ │ │ │ Default locale for the system environment: │ │ │ │ None │ │ en_GB.UTF-8 │ │ │ │ │ │ <Ok> <Cancel> │ │ │ └─────────────────────────────────────────────────────────────────────────┘ Setting Up Backports Read this for background information: The only change is we add the etch backports to the /etc/apt/sources.list: deb etch-backports main Then run: wget -O - | apt-key add - apt-get update Installing Postfix Install it with this command to explicitly use the backports version: apt-get -t etch-backports install postfix-mysql Now you will see a lot of screens: │ <Ok> │ │ └─────────────────────────────────────────────────────────────────────────┘ Click OK then choose Internet Site. You'll see this, enter the domain which will appear after the @ in email addresses: Package configuration ┌─────────────────────────┤ Postfix Configuration ├─────────────────────────┐ │ The "mail name" is the domain name used to "qualify" mail addresses │ │ without a domain name. sms.3aims.com____________________________________________________________ │ │ │ │ <Ok> <Cancel> │ │ │ └───────────────────────────────────────────────────────────────────────────┘ Implementing the Code The code is going to be implemented in three parts: - A simple library to send an SMS using the Orange SMS API. - A mod_wsgi handler to receive SMS messages from orange, process them and send them out either by SMS or by email depending on whether the word after FOR in the SMS is an email address or a phone number - A postfix pipe command to receive any incoming email messages and send an SMS message based on the phone number in the subject of the email Setting up Logging Since the scripts we are going to use are executed by either postfix or as a result of an HTTP request from Orange, we won't have any particularly easy way to see what's going on so we'll set up a logging configuration to log data to /var/log/syslog. To do this create a logging configuration which looks like this in /home/sms/sms/logging_basic.ini: [formatters] keys: detailed [handlers] keys: syslog [loggers] keys: root,sms [logger_root] level: INFO handlers: syslog [logger_sms] level: DEBUG handlers: syslog qualname: sms [handler_syslog] class: handlers.SysLogHandler args: ['/dev/log'] propagate: 0 formatter: detailed [formatter_detailed] %(name)s:%(levelname)s %(message)s This will log all child loggers of sms which have levels of DEBUG or above to the syslog. To use it in a Python application use this code: import logging import logging.config logging.config.fileConfig('/home/sms/sms/logging_basic.ini') log = logging.getLogger('sms.some_child') You can then log results like this: log.debug(result) Implementing the Send SMS API Let's start with the send SMS library. Create an sms.py file within the /home/sms/sms directory: """\ Simple module for sending SMS messages """ import logging import logging.config logging.config.fileConfig('/home/sms/sms/logging_basic.ini') log = logging.getLogger('sms.sms') import urllib API_KEY = 'XXXXXXXXXXX' def send_sms(to, message): log.debug("Sending SMS to %r with message %r", to, message) url = '' data = {'id': API_KEY, 'to':to, 'content':message} fp = urllib.urlopen(url, urllib.urlencode(data)) result = fp.read() fp.close() log.debug("Sending SMS result was %r", result) return result You'll need to replace all the XXX characters with the correct API key you get from the Orange control panel. Implement the Web Server Part Now we are ready to implement the webserver part. This is going to When a txt is sent to 967482 and starts with the keyword you've specified, Orange will call the URL you entered. For example. This text: For 447980233595 Test would result in this URL being called: Our code needs to handle this and then make a call to the API to send the txt on: #! -*- coding: utf-8 -*- import site site.addsitedir('/home/sms/env/lib/python2.5') site.addsitedir('/home/sms/sms') site.addsitedir('/home/sms/env/lib/python2.5/site-packages') from webob import Request, Response # Set up logging import logging import logging.config logging.config.fileConfig('/home/sms/sms/logging_basic.ini') log = logging.getLogger('sms.handle') from sms import send_sms import webhelpers.mail as mail def application(environ, start_response): log.debug('Message receive begun') request = Request(environ) response = Response() response.content_type = 'text/html' if request.path_info == '/retrieve': if request.params.get('api') != 'receivesms': log.error('Invalid API') response.body = 'Invalid API' elif not request.params.get('content'): log.error('No content') response.body = 'No content' elif not request.params.get('from'): log.error('No from') response.body = 'No from' else: content = request.params['content'].strip(' ') parts = content.split(' ') if len(parts) < 3: log.error('Unknown SMS structure') response.body = 'Unknown SMS structure' else: code = parts[0].lower() to = parts[1].lower() content = ' '.join(parts[2:]) log.debug('Code: %r, To: %r, Content: %r', code, to, content) if code not in ['for']: log.error('Received SMS with an unknown keyword %r', code) response.body = 'Unknown SMS keyword' else: if '@' in to: # Treat as an email address log.debug('Sending email to %r', to) mail.send( mail._prepare( mail.plain(content), from_name = '3aims SMS Gateway', from_email = 'noreply@sms.3aims.com', to=[to], subject = 'SMS from %s'%request.params['from'] ), sendmail = '/usr/sbin/sendmail' ) log.debug('Sent email') response.body = 'Sent email' else: if to.startswith('0'): # Assume a UK number to = '44'+to[1:] log.debug('No country code, using %r', to) from_ = 'From '+request.params['from']+'. '+content log.debug('Sending SMS to %r from %r', to, from_) response.body = send_sms(to, from_) log.debug('Result: %r', response.body) else: response.status = '200 Not Found' response.body = 'Not Found' return response(environ, start_response) Set up the Forwarding When messages are sent to sms att sms.3aims.com we want them to piped to a program which sends them as an SMS message. This requires us to create a .forward file for the sms user to forward the email to the program. As the sms user: touch ~/.forward chmod 0640 ~/.forward Add the following content to the .forward file: "|/home/sms/sms/receive.py" We'll need the latest WebHelpers package: cd ~/lib hg clone cd webhelpers ~/env/bin/python2.5 setup.py develop Then create /home/sms/sms/receive.py with this content: #!/home/sms/env/bin/python2.5 import logging import logging.config import sys import webhelpers.mail as mail from email.feedparser import FeedParser from sms import send_sms # Set up logging logging.config.fileConfig('/home/sms/sms/logging_basic.ini') log = logging.getLogger('sms.receive') # Parse the message f = FeedParser() f.feed(sys.stdin.read()) message = f.close() # Process the message to = message['subject'] if not message.is_multipart(): msg = message.get_payload() else: raise Exception('Multipart messages not supported') result = send_sms(to, msg) log.debug(result) log.debug(to) log.debug(msg) That's it. You can now send SMS's to email addresses, have emails forwarded to SMS and also have SMS's send to other mobile numbers all via your server. With these basics in place the possibilities are fairly limitless.
https://www.jimmyg.org/blog/2008/orange-sms-api-and-python-with-nginx-mod_wsgi.html
CC-MAIN-2020-24
refinedweb
2,456
58.58
On Mon, Feb 14, 2005 at 01:05:40PM -0500, Greg Hudson wrote: > On Mon, 2005-02-14 at 11:51, Ben Collins-Sussman wrote: > > 2. mod_dav_svn notices whether the incoming lock was created by > > an svn client or a generic DAV client. > > I'd rather see us test whether the author field is minimal or not. If > it looks like <D:author>blah</D:author>, it would be nice to unpackage > it regardless of whether the client is a generic DAV client. My theory > is that most DAV clients will send a minimal author spec, and it would > be nice not to display their lock fields as junk to non-dav clients. Agreed. This is/was the original solution that Ben and I worked thru via AIM. We came up with an idea to detect "minimal" and do the stripping. I think the current problem is that if you're looking at a lock->comment, then how does mod_dav_svn determine whether it was stripped (and needs wrapping), or should be passed along unchanged? A simple detection rule might be, "is the first character '<' ?" But what if a comment can legitimately contain that? Then you could end up a DAV:owner tag wrapped around some content that it shouldn't have wrapped. > On another note, if the author field is using namespace tags which were > defined elsewhere, how can we be sure those namespace tags are defined > the same way in the response? How does the DAV spec address this > problem? mod_dav passes a serialized XML fragment which is internally consistent with the namespaces/prefixes. It was designed this way so that the result could simply be dropped into the output XML stream without worrying about a bunch of namespace crap (as you rightly were concerned about). In any case, I think the question comes down to: is there a detection rule that is workable for "should this be wrapped?" A heuristic is available; is that good enough? If not, then a boolean as Ben suggests is a good way out of the problem. Cheers, -g -- Greg Stein, --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org For additional commands, e-mail: dev-help@subversion.tigris.org This is an archived mail posted to the Subversion Dev mailing list.
http://svn.haxx.se/dev/archive-2005-02/0462.shtml
CC-MAIN-2016-26
refinedweb
379
71.44
Tech Helproom It's free to register, to post a question or to start / join a discussion import contacts to incredimail from Windows live mail ? Likes # 0 Posted June 16, 2012 at 4:42PM I am attempting to update my address book in Incredimail, when I attempt to import and point it to Windows live mail, I get a message stating that it cannot find any contacts. Although the contacts are obviously there, I cannot find the appropriate folder. I also have a back up file (csv) file from my outlook on another computer, but I cannot see how to update using this either ? - contacts - incredimail Likes # 0 Posted June 16, 2012 at 9:53PM Take a look here
http://www.pcadvisor.co.uk/forums/1/tech-helproom/4149891/import-contacts-to-incredimail-from-windows-live-mail-/?ob=datea
CC-MAIN-2014-15
refinedweb
119
56.39
Configure Force Tunneling for DirectAccess Clients Published: October 7, 2009 Updated: May 24, 2010 Applies To: Windows Server 2008 R2 Before configuring force tunneling settings for DirectAccess clients, you should have deployed and determined the Internet Protocol version 6 (IPv6) addresses of either your dual protocol (Internet Protocol version 4 [IPv4] and IPv6) proxy servers or your IPv6/IPv4 translator (NAT64) and IPv6/IPv4 DNS gateway (DNS64) devices that are in front of your IPv4-based proxy servers. For more information about these devices, see Choose Solutions for IPv4-only Intranet Resources. snap-in, open the appropriate forest and domain object, right-click the Group Policy object for DirectAccess clients, and then click Edit. In the console tree of the Group Policy Management Editor snap-in, open Computer Configuration\Policies\Administrative Templates\Network\Network Connections. In the details pane, double-click Route all traffic through the internal network. In the Route all traffic through the internal network dialog box, click Enabled, and then click OK. In the console tree of the Group Policy Management Editor snap-in, open Computer Configuration\Policies\Windows Settings\Name Resolution Policy. In the details pane, in To which part of the namespace does this rule apply?, click Any. Click the DNS Settings for Direct Access tab, and then click Enable DNS settings for Direct Access in this rule. In DNS servers (optional), click Add. In DNS server, type the IPv6 address of your dual protocol (IPv4 and IPv6) proxy server or your NAT64/DNS64 devices that are in front of your IPv4-based proxy server. Repeat this step if you have multiple IPv6 addresses. Click Create, and then click Apply. In the console tree of the Group Policy Management Editor snap-in, open Computer Configuration\Policies\Administrative Templates\Network\TCPIP Settings\IPv6 Transition Technologies. In the details pane, double-click 6to4 State. In the 6to4 State dialog box, click Enabled, click Disabled State in Select from the following states, click Apply, and then click OK. In the details pane, double-click Teredo State. In the Teredo State dialog box, click Enabled, click Disabled State in Select from the following states, click Apply, and then click OK. In the details pane, double-click IP-HTTPS State. In the IP-HTTPS State dialog box, click Enabled State in Select Interface state from the following options, click Apply, and then click OK. DirectAccess clients will apply these settings the next time they update their Computer Configuration Group Policy. If you arrived at this page by clicking a link in a checklist, use your browser’s Back button to return to the checklist.
https://technet.microsoft.com/en-us/library/ee649127(WS.10).aspx
CC-MAIN-2017-22
refinedweb
434
52.8
Did you download the new examples? they are not included anymore. Here you can find them: Did you download the new examples? they are not included anymore. Here you can find them: I use V_LEVEL and S_MOISTURE for a moisture sensor. The percentage part is something i am going to try for sure. In the 2.0 sketch this is mentioned: #define COMPARE_TEMP 1 // Send temperature only if changed? 1 = Yes 0 = No So 0 should keep everything working and sens info even when not changed. I don't know either and i remember that there should be a zip file which you can download. I only cannot remember where. For now you can copy the code and save it. That is because UDP is enabled, if you uncomment the gateway stuff for the ENC28J60 then it compiles because UDP can be enabled now. So remove the comment lines and add #define MY_USE_UDP at the end like suggested. Thanks, i would not have found that by myself I have an issue where a node stops sending sensor info after a while. I do not have a log (yet) but i am wondering if a range issue would cause this. Which reasons could cause a node stop sending info to the gateway? If needed i can made a log later as i need my laptop connected to it and i cannot reach it at the moment. yes add the line but only on non battery powered nodes. If battery powered this will kill battery life. I have a couple repeater nodes at home to extend the range. That is quick I will check ik out later. Thanks I think i will invest in suck a buck converter. There is still plenty coming over from China so many projects to build and i rather do it right the first time. yes add the line but only on non battery powered nodes. If battery powered this will kill battery life. I have a couple repeater nodes at home to extend the range. In the 2.0 sketch this is mentioned: #define COMPARE_TEMP 1 // Send temperature only if changed? 1 = Yes 0 = No So 0 should keep everything working and sens info even when not changed. I think you just have to comment out that part of the code (the 5 lines of code) Thanks, i would not have found that by myself I will buy one later This is just to play with as i wanted to know how the battery measurement works. And how do i downgrade AVR board devs? I have voltage now and a percentage at the devices. Hum and temp do work fine. I only sucked all the juice out of the battery so it is charging now by the little solar panel. I found out that 2,4V was really the lowest voltage that worked I have the voltage part working and i think also the battery percentage with it. I build the sketch like this. Can you have a little * * This is an example that demonstrates how to report the battery level for a sensor * Instructions for measuring battery capacity on A0 are available here: * * */ // Enable debug prints to serial monitor #define MY_DEBUG // Enable and select radio type attached #define MY_RADIO_NRF24 //#define MY_RADIO_RFM69 #include <SPI.h> #include <MySensors.h> #include <DHT.h> #define CHILD_ID_BATT 0 #define CHILD_ID_HUM 1 #define CHILD_ID_TEMP 2 #define DHT_DATA_PIN 3 // Set this to the pin you connected the DHT's data pin to int BATTERY_SENSE_PIN = A0; // select the input pin for the battery sense point // Set this offset if the sensor has a permanent small offset to the real temperatures #define SENSOR_TEMP_OFFSET 0 static const uint64_t UPDATE_INTERVAL =; //unsigned long SLEEP_TIME = 9000; // sleep time between reads (seconds * 1000 milliseconds) int oldBatteryPcnt = 0; float lastTemp; float lastHum; uint8_t nNoUpdatesTemp; uint8_t nNoUpdatesHum; boolean metric = true; MyMessage msgBatt(CHILD_ID_BATT, V_VOLTAGE); MyMessage msgHum(CHILD_ID_HUM, V_HUM); MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); DHT dht; void setup() { // use the 1.1 V internal reference #if defined(__AVR_ATmega2560__) analogReference(INTERNAL1V1); #else analogReference(INTERNAL); #endif //} { to the gateway and Controller sendSketchInfo("Battery Meter", "1.0"); present(CHILD_ID_BATT, S_MULTIMETER); wait(20); present(CHILD_ID_HUM, S_HUM); wait(20); present(CHILD_ID_TEMP, S_TEMP); wait(20); metric = getConfig().isMetric; }(msgBatt.set(batteryV, 1)); //sendBatteryLevel(batteryPcnt); oldBatteryPcnt = batteryPc(SLEEP_TIME); sleep(UPDATE_INTERVAL); }}``` I have voltage now (utility) and a percentage under devices. I have read somewhere that the percentage is depending on the last sensors poll so i will now try to add the DHT part in to the sketch. sendBatteryLevel doesn't do anything. I have modified it a bit and now i have some readings. I will do a bit more playing to see where i will end.
https://forum.mysensors.org/user/tlpeter
CC-MAIN-2020-50
refinedweb
778
72.56
#include <stdio.h> #include <Stdlib.h> int ff(); int main() { clrscr(); ff(); ff(2); ff(2,3,4); return 3; } int ff(int i,int j,int k) { printf(" \n Hello world %d %d %d\n",i,j,k); return 3; } We can see that the first two calls to the function result in garbage values being printed for the unspecified parameters (i , j, and k in the first call and j and k in the second call). The last call prints the correct values as all the parameters have been specified. For the functions developed in the last section, the following are valid prototype declarations. void sayhello(void); int n_abs(int n); or int n_abs(int); float reciproc(float x); or float reciproc(float); char get_yesno(void); Notice that every prototype declaration ends with a semi-colon. The easiest way to put a declaration is to simply copy the header from the function definition, paste it, and add a terminating semi-colon. Prototype declarations are optional in C but they are compulsory in C++. Since, it is a reasonable assumption that every C programmer is a future C++ programmer , you should develop the habit of declaring prototypes for every function! The C program, demonstrates the three aspects of a user defined function – the function prototype declaration, the function definition, and function calls. /*creating and using a user-defined function*/ #include <Stdio.h> /* function prototype declaration*/ float reciproc(float x); int main() { float x=5.67, y; clrscr(); y = reciproc(x); /*a call to the function recipro*/ printf("%g %g",y, reciproc(y)); return 0; /* another function call*/ } float reciproc(float x) { float y; y = 1.0/x; return y; } Another advantage of using function prototype declarations is that the functions can be defined in any order in the source file. Otherwise, some compilers place a restriction that a function should be used (i.e., a function call statement is placed) only after it has been defined. Once you have declared the prototypes of all functions, this restriction does not apply and you are free to reorder your functions in any order. As a matter of style, main is usually the last or the first function in a program depending on personal stylistic preferences. Many programming books show main as the last function in a source file but I prefer to place main as the first function in a program as I feel that it improves the readability
http://ecomputernotes.com/what-is-c/function-a-pointer/undefined-parameter-list
CC-MAIN-2019-39
refinedweb
408
58.82
For just starting to explore with VPython window, getting one's feet wet, I'm looking at such as stickworks.py as a simple place to begin (excerpts below). The stickworks namespace wants us to think of Vector objects as radiating from (0,0,0), i.e. they're always tail anchored to the origin. cross(self, other): temp = cross(self.v, other.v) return Vector((temp.x, temp.y, temp.z)) etc. Edges, on the other hand, otherwise known as line segments, may connect any two points in space, and as such are defined by the arrow *tips* of two Vectors of the type defined above. class Edge (object): """ Edges are defined by two Vectors (above) and express as cylinder via draw(). """ radius = 0.03 def __init__(self, v0, v1, color=(1,0,0)): self.v0 = v0 self.v1 = v1 self.color = color) You'll find this dichotomy in some published linear algebra books e.g. this one by Wayne Bishop and Stewart Venit ISBN: 087150300X (Wayne being a Cal State prof and one of my sparring partners on math-teach). I'm not using VPython's cylinder and vector objects directly because I'm wanting an even simpler namespace. Vectors are my primary constituent, followed by edges as pairs of vectors, and faces as tuples of vectors defining three or more edges. Of course in the Fuller School we quickly move to a small subset of polyhedra organized in a particular way (or core mandala, source of many dharmas). We harp on Euler's V + F = E + 2. We talk in an alien manner about our 4D Simplex with energy added (4D++). But that doesn't mean every gnu math teachers needs to follow our lead and/or sequence. The curriculum is a network, and the many trailheads go to many places (partially overlapping) in different orders. Plus Arthur of Pygeo has a whole other toolset you could explore. Save the Bucky stuff for later, if ever. Tell 'em I said it was OK. The sequence I'm developing here is: intro to namespaces --> import stickworks as a namespace --> explore in VPython Given stickworks is provided, student creativity will be more in what they can *do* with it. I'll be thinking of some projects. Dissecting and tweaking source code will also be a focus, as fluency gradually develops, plus writing new modules that assume the above as all given. Kirby
http://mail.python.org/pipermail/edu-sig/2006-September/007145.html
crawl-002
refinedweb
403
73.98
Discussions EJB programming & troubleshooting: explain java:comp/env/jdbc/JNDINAME explain java:comp/env/jdbc/JNDINAME (3 messages) can u any body explain me about tis statement java:comp/env/jdbc/Simple (jndi name) .. i am weblogic9.0 server for deploying servlet..jsp..ejb.. how to configure jndi name.. is it with name Simple or jdbc.simple if i configure with simple or with jdbc/simple it is showing error.. plz explain tis - Posted by: prasanna vasan - Posted on: September 12 2006 08:03 EDT Threaded Messages (3) - reference by Tim LeMaster on September 12 2006 10:55 EDT - Re: reference by Jyothish John on September 13 2006 06:57 EDT - explain java:comp/env/jdbc/JNDINAME by AshaLatha Sadhu on March 24 2010 14:51 EDT reference[ Go to top ] java:comp/env is the namespace used for references. This is a decoupling point so your code doesn't have to worry about the actual JNDI name of the resource. Lets say you installed an Datasource and gave it a JNDINAME jdbc/datasource You could look that up directly but if the name changed you would have to recompile your code. Now change the code to lookup java:comp/env/jdbc/datasource. With adding something to your web.xml this will always fail with a naming exception. If you want to use references look at adding a to your web.xml and to weblogic.xml - Posted by: Tim LeMaster - Posted on: September 12 2006 10:55 EDT - in response to prasanna vasan Re: reference[ Go to top ] java:comp/env/jdbc/myDatasource name.. means that you have to create a jndiDatasource with the name "myDatasource" on the weblogic server or you must create a new datasource with the name "myDatasource" . And when the application server /container starts, the JNDI service will store a reference to the datasource under the java:comp/env/jdbc namespace, so your applications can simply look up the data source for obtaining a connection to the database, to which the data source is pointing to. The name of the datasource can be anything as far as you try to lookup the datasource using the same name as of the datasource inside your code,or simply create a datasource of the samename which you use inside your code.. - Posted by: Jyothish John - Posted on: September 13 2006 06:57 EDT - in response to Tim LeMaster explain java:comp/env/jdbc/JNDINAME[ Go to top ] have you got answer for your Question: - Posted by: AshaLatha Sadhu - Posted on: March 24 2010 14:51 EDT - in response to prasanna vasan explain java:comp/env/jdbc/JNDINAME if so, could U pls explain to me
http://www.theserverside.com/discussions/thread.tss?thread_id=42158
CC-MAIN-2014-42
refinedweb
446
50.57
Created on 2008-10-27 23:57 by amy20_z, last changed 2011-03-09 04:09 by terry.reedy. This issue is now closed. I have a simple program to call a shell command "service cpboot start" to start Check Point firewall on RHEL5.1. ================= #!/usr/bin/env python # vim: softtabstop=4 shiftwidth=4 expandtab import os from subprocess import * p = Popen('service cpboot stop',shell=True, stdout=PIPE) output = p.communicate() print 'STDERR: %s' % output[0] print 'STDOUT: %s' % output[1] =============== Python process pid 13343 spawned child 13375 to run "service cpboot start". However, after child process 13375 finished and sent SIGCHLD to the python script, the parent hangs in Popen function communicate() at line 1041 and child process 13375 became a defunct process. Traceback (most recent call last): File "./subprocess_test03.py", line 7, in ? output = p.communicate() File "/usr/lib/python2.4/subprocess.py", line 1041, in communicate rlist, wlist, xlist = select.select(read_set, write_set, []) KeyboardInterrupt Here is part of the strace: Process 13375 detached [pid 19195] close(878) = -1 EBADF (Bad file descriptor) [pid 19195] close(879) = -1 EBADF (Bad file descriptor) [pid 19195] close(880) = -1 EBADF (Bad file descriptor) [pid 13343] <... select resumed> ) = ? ERESTARTNOHAND (To be restarted) [pid 19195] close(881 <unfinished ...> [pid 13343] --- SIGCHLD (Child exited) @ 0 (0) --- [pid 19195] <... close resumed> ) = -1 EBADF (Bad file descriptor) [pid 13343] select(7, [4 6], [], [], NULL <unfinished ...> It seems like the select system call got interrupted and error code was "ERESTARTNOHAND" was returned. The PIPEs won't be able to terminate since child process has finished and exited and EOF won't be read from the PIPEs. If executing the shell command directly from shell command line, there's no problem at all.It seems like there might be some race condition somewhere in the python library. Any idea what may cause the problem? Many thanks in advance. I'm unable to reproduce your problem with Python 2.4.4 nor Python 2.5.1. I'm using Ubuntu and the program "service" doesn't exist. So I used the commands "pwd", "sh -c pwd", "sh -c 'echo $$'". All commands terminate correctly. Your problem is specific to the command "service cpboot start"? You can reproduce the problem with another command? Can you attach the full trace? I mean something like "strace -f -o trace python test.py". Yes, I can only replicate this issue with command to start firewall. Stopping firewall or other service commands don't have the problem. Check Point firewall is a kernel application. Somehow select system call is interrupted and can't terminate the PIPE. I don't know what interrupt it is, though. I'll collect the full log and attach it here. The bug should be fixed in Python 2.5 since it uses: while read_set or write_set: try: rlist, wlist, xlist = select.select(read_set, write_set, []) except select.error, e: if e[0] == errno.EINTR: continue else: raise EINTR is supported in subprocess for select(), read(), write() and waitpid() Can't you migrate to Python 2.5 or 2.6? You can try to copy subprocess.py from Python 2.5 to Python 2.4. I'm running python 2.5.2 on Ubuntu 8.10. I believe I've also encountered the problem reported here. The scenario in my case was the following: 1. Python process A uses subprocess.Popen to create another python process (B). Process B is created with stdout=PIPE and stderr=PIPE. Process A communicates with process B using communicate(). 2. Python process B, starts a ssh process (process C) which is invoked to open a new control socket in master mode. Process C is started without pipes so it gets its std{in,out,err} from process B. Process C is going to run for a long time. That is, it will run until a command is sent to the control socket to close the ssh connexion. 3. Process B does not wait for process C to end, so it ends right away. 4. Python process A remains stuck in communicate() until process C (ssh) dies even though process B has ended already. Analysis: The reason for this is that process C (ssh) gets its stdout and stderr from process B. But process C keeps both stdout and stderr opened until it is terminated. So process A does not get an EOF on the pipes it opened for communicating with process B until process C ends. The set of conditions which will trigger the effect is not outlandish. However, it is specific enough that testing by executing "pwd" or "ls -l", or "echo blah" or any other simple command won't trigger it. In my case, I fixed the problem by changing the code of process B to invoke process C with stdout and stderr set to PIPE and close those pipes as soon as process B is satisfied that process C is started properly. In this way, process A does not block. (FYI, process A in my case is the python testing tool nosetests. I use nosetests to test a backup script written in python and that script invokes ssh.) It seems that in general subprocess creators might have two needs: 1. Create a subprocess and communicate with it until there is no more data to be passed to its stdin or data to be read from its std{out,err}. 2. Create a subprocess and communicate with it *only* until *this* process dies. After it is dead, neither stdout nor stderr are of any interest. Currently, need 1 is addressed by communicate() but not need 2. In my scenario above, I was able to work around the problem by modifying process B but there are going to be cases where process B is not modifiable (or at least not easily modifiable). In those cases, process A has to be able to handle it. I think communicate() works as documented now: reads stdout/stderr until EOF, *and* waits for subprocess to terminate. You're asking for a different method, or perhaps an optional parameter "return_when_died" to communicate, so it returns as soon as the child process terminates (I don't like the parameter name...) I think this is more a feature request than a crash, targeted to 2.7/3.1 - 2.4 only gets security fixes anyway. Yes I think subprocess is working correctly. Since this feature request is 2 years old now without any interest, I think it should be closed. If the functionality is needed, it can always be programmed by the user when needed. You can try subprocess.call() with close_fds=True. It helped me, at least. Closing as suggested by Ross
https://bugs.python.org/issue4216
CC-MAIN-2018-05
refinedweb
1,113
76.11
A Simple Example Let) The rendering process involves the following: - We start with the svgroot element: - a doctype declaration as known from (X)HTML should be left off because DTD based SVG validation leads to more problems than it solves - to identify the version of the SVG for other types of validation the versionand baseProfileattributes should always be used instead - as an XML dialect, SVG must always bind the namespaces correctly (in the xmlns attribute). See the Namespaces Crash Course page for more info. - The background is set to red by drawing a rectangle <rect/>that covers the complete image area - A green circle <circle/>with a radius of 80px is drawn atop the center of the red rectangle (offset 30+120px inward, and 50+50px upward). - The text "SVG" is drawn. The interior of each letter is filled in with white. The text is positioned by setting an anchor at where we want the midpoint to be: in this case, the midpoint should correspond to the center of the green circle. Fine adjustments can be made to the font size and vertical position to ensure the final result is aesthetically pleasing. Basic properties of SVG files - The first important thing to notice is the order of rendering of elements. The globally valid rule for SVG files is, that later elements are rendered atop previous elements. The further down an element is the more will be visible. - SVG files on the web can be displayed directly in the browser or embedded in HTML files via several methods: - If the HTML is XHTML and is delivered as type application/xhtml+xml, the SVG can be directly embedded in the XML source. - If the HTML is HTML5, and the browser is a conforming HTML5 browser, the SVG can be directly embedded, too. However, there may be syntax changes necessary to conform to the HTML5 specification - The SVG file can be referenced with an objectelement: <object data="image.svg" type="image/svg+xml" /> - Likewise an iframeelement can be used: <iframe src="image.svg"></iframe> - An imgelement can be used theoretically, too. However this technique doesn't work in Firefox before 4.0. - Finally SVG can be created dynamically with JavaScript and injected into the HTML DOM. This has the advantage, that replacement technologies for browsers, that can't process SVG, can be implemented. - How SVG handles sizes and units will be explained on the next page. SVG File Types). A Word on Webservers Now that you have an idea of how to create basic SVG files, the next stage is to upload them to a Webserver. There are some gotchas at this stage though. For normal SVG files, servers should send the HTTP header: Content-Type: image/svg+xml For gzip-compressed SVG files, servers should send the HTTP headers: Content-Type: image/svg+xml Content-Encoding: gzip You can check that your server is sending the correct HTTP headers with your SVG files by using SVG wiki.
https://developer.mozilla.org/en-US/docs/SVG/Tutorial/Getting_Started?redirect=no
CC-MAIN-2016-40
refinedweb
495
59.23
It is used to get characters. Following is the declaration for std::basic_istream::get. er (1) int_type get(); basic_istream& get (char_type& c); c-string (2) basic_istream& get (char_type* s, streamsize n); basic_istream& get (char_type* s, streamsize n, char_type delim); stream buffer (3) basic_istream& get (basic_streambuf<char_type,traits_type>& sb); basic_istream& get (basic_streambuf<char_type,traits_type>& sb, char_type delim); c − The reference to a character where the extracted value is stored.). sb − A basic_streambuf object on whose controlled output sequence the characters are copied. Returns the character read, or the end-of-file value (traits_type::eof()) if no characters are available in the stream (note that in this case, the failbit flag is also set). Basic guarantee − if an exception is thrown, the object is in a valid state. Modifies c, sb or the elements in the array pointed by s and modifies the stream object. In below example for std::basic_istream::get. #include <iostream> #include <fstream> int main () { char str[256]; std::cout << "Enter the name of an existing text file: "; std::cin.get (str,256); std::ifstream is(str); char c; while (is.get(c)) std::cout << c; is.close(); return 0; }
https://www.tutorialspoint.com/cpp_standard_library/cpp_basic_ios_get.htm
CC-MAIN-2020-16
refinedweb
191
57.27
This is the result of people jumping into graphics programming without even understanding what a buffer is. A buffer is the 'virtual screen' in memory. I hope you know that all pixels are represented by DWORDs or unsigned integers (in 32-bit color and in 32-bit code). Since the actual video memory is simply an area of memory mapped I/O in the computer, you can mimick this 'screen' by creating your own buffer of DWORDs the same exact size as the video buffer. The only thing that makes the 'screen' what you see is the fact that the card scans the area of memory deemed to be the 'screen' DWORD by DWORD hundreds of times per second - actually much faster than that. The card translates the RGB values into the correct analog voltages and sends them to the monitor. Some monitor's and some cards are pure digital depending on whether you have a flat screen array of transistors or an analog CRT. The screen may look two dimensional on the monitor, but in memory it's just one long huge line of numbers. To plot a pixel at the correct location you must use these: DWORD offset=y*(width*(sizeofdatatype))+x; Note in DirectX and OpenGL (width*sizeofdatatype) has been replaced by something called buffer pitch. This basically says how many bytes of data exist in one scan line. The reason for pitch is because video manufacturers figured out that aligning the data on certain boundaries is much faster and more in tune with the architecture of the system as well as their GPU. So in the old DOS days here are the size of some of the screens: 256 colors 640x480x256 colors - (640*480) 800x600x256 colors - (800*600) To make a buffer for 640x480x256 colors you need to first figure out the data type being used. Since 256 color is simply paint by the palette number, all colors can be represented by 1 byte. Each RGB can be from 0 to 32 but only 256 distinct RGB triplets are allowed at any one time. That code will fail in real DOS mode however because there is not enough memory to hold the data. I will not explain here the differences between 16-bit programming and 32-bit. Do some research.That code will fail in real DOS mode however because there is not enough memory to hold the data. I will not explain here the differences between 16-bit programming and 32-bit. Do some research.Code:typedef unsigned char BYTE; BYTE far *Buffer=new unsigned char[(unsigned long)(640*480)]; To plot a pixel in that 'virtual screen' you would do this: Surface is simply a BYTE far pointer that points to either buffer or screen.Surface is simply a BYTE far pointer that points to either buffer or screen.Code:#define XYTOMEM (x,y,pitch) (unsigned long)((y)*(pitch)+(x)) void Pixel(int x,int y,BYTE color) { Surface[XYTOMEM(x,y)=color]; } This is a simpe mode 13h unit. Try it in Turbo C++ and see what you get. It's old, but it might help you understand what the heck a backbuffer is. The keyword FAR is not used anymore - but you still must use it when coding for 16-bit pure or emulated DOS. It informs the compiler that the pointer to the memory does not exist in our segment - in exists outside of our current segment. To explain that I would have to explain assembly language programming and I'm also not going to do that. This will stick the computer in old school DOS 320x200x256 color mode and will setup the screen, back buffer, and current buffer pointer.This will stick the computer in old school DOS 320x200x256 color mode and will setup the screen, back buffer, and current buffer pointer.Code:#ifndef CVIDEO #define CVIDEO #define TRUE 1 #define FALSE 0 class CVideo { protected: //Pointer to actual screen - video memory BYTE far *Screen; //Pointer to back buffer - virtual screen BYTE far *Buffer; //Pointer to current pointer being used BYTE far *Surface; unsigned int Width; unsigned int Height; unsigned int Pitch; //Current drawing mode BYTE BufferMode; public: CVideo(void):Screen(0),Buffer(0),Surface(0),Width(0),Height(0),Pitch(0) {} virtual ~CVideo(void) { if (Buffer) { delete [] Buffer; Buffer=0; } } BYTE SetMode13h(void) { REGS regs; regs.x.ax=0x10; int86(0x10,& regs, & regs); Width=320; Height=200; Pitch=Width; //pitch and width synonymous in this mode Screen=(BYTE far *)MK_FP(0xA000,0); Surface=Screen; Buffer=new BYTE[64000L]; if (Buffer) { return true; } else return false; } void Pixel(int x,int y,BYTE color { Surface[XYTOMEM(x,y)=color]; } BYTE far *GetBuffer(void) {return Buffer;} BYTE far *GetScreen(void) {return Screen;} BYTE far *GetSurface(void) {return Surface;} void Flip(void) { //No vsync here //Copy back buffer to screen memcpy((BYTE far *)Screen,(BYTE far *)Buffer,64000L); } void Flip16(void) { asm { push ds les di,[Screen] lds si,[Buffer] mov cx,32000d rep movsw pop ds } } void Flip32(void) { asm { db 66h push ds db 66h les di,[Screen] db 66h lds si,[Buffer] db 66h mov cx,32000d db 67h rep movsw db 66h pop ds } } void SetBufferMode(BYTE mode=TRUE) { if (mode) { Surface=Buffer; BufferMode=TRUE; } else { Surface=Screen; BufferMode=FALSE; } } BYTE GetBufferMode(void) {return BufferMode;} void CLS(BYTE color) { BYTE far *ptrSurface=0; if (BufferMode) { ptrSurface=Buffer; } else ptrSurface=Screen; asm { les di,[ptrSurface] mov cx,32000d mov ah,[color] mov al,[color] rep stosw } } //inlined unsigned int XYTOMEM(int x,int y) { return (y<<8)+(y<<6)+x; } }; #endif You can add functions to the class to draw lines, circles, bitmaps, etc. The only function I'm leery of is Flip32 which is an attempt to use 32-bit code in a 16-bit environment. If it works, it should copy 4 pixels at a time to the screen instead of 2 like Flip16. Flip simply copies 1 byte at a time. Theoretically Flip16 is twice as fast as Flip and Flip32 is twice as fast as Flip16 or four times as fast as Flip. But I'm not positive the code will work. It's been a LONG time since the DOS days. Play with this code. Set the screen up by calling SetMode13h. Then clear the screen by calling CLS(BYTE color). This will clear the screen if BufferMode is FALSE and will clear the buffer if it is TRUR. The parameter is the color the screen will be cleared to. Set the buffer mode to TRUE by calling SetBufferMode(TRUE). Draw some pixels. Run it. Nothing shows up. This is because you are drawing to a back buffer - a portion of memory that looks just like the screen, but isn't. Now call Flip() after you draw and everything should show up. This is what OpenGL and Direct3D are doing for you. Drawing to the front buffer, in most cases, is not needed. This code should work with that class: This should display a white dot in the center of the screen.This should display a white dot in the center of the screen.Code:#include "CVideo.h" #include <conio.h> #include <stdio.h> CVideo Display; int main(void) { Display->SetMode13h(); Display->SetBufferMode(TRUE); Display->CLS(0); Display->Pixel(160,100,15); Display->Flip(); getch(); return (0); } Sorry for such a long post, but to show you buffers in DirectX code is even uglier than what I just posted...and none of it would show you how it works - just how to do it in DirectX. This code will show you EXACTLY what is going on. Download Turbo C++ 1.0 from and mess with it. Then go back to OpenGL and please - rethink what you are doing. If the code doesn't work, let me know what's wrong with it. I wrote it sitting here so I'm sure there are some errors.
http://cboard.cprogramming.com/game-programming/65850-how-can-i-opengl-3.html
CC-MAIN-2015-32
refinedweb
1,321
69.11
New Language Features on the JVM Why, after Java has dominated the enterprise landscape for so many years, is there an explosion of new languages and features targeting the JVM? Read on and listen to David Buschman's opinion on the matter. Join the DZone community and get the full member experience.Join For Free Recently, I have noticed a trend where former Java developers are currently writing code for the JVM but not in Java. Full disclosure, I am one of them. We are using other languages like Scala or Clojure in place of Java. Even newcomers like Kotlin and Xtend are getting support. So why, after Java has dominated the enterprise landscape for so many years, is there an explosion of new languages and features targeting the JVM. Furthermore, why are Java developers now using these new languages to write their software. Taking some time to look at what these new languages have in common can shed some light on why developers are moving to these new languages to program in. Functions as Parameters This has been one of the biggest features missing from Java so a very long time. All of the new languages make it very clear that this feature is one of the main reason to use their language to write your software with. The consistency of these new languages all keying in on this feature signifies that it is a very important feature for the future. Even with Java 8, functions as parameters support is a bolt on to the language and is currently limited in 3rd party library usage to date. def sayHello(name: String) = s"Hello ${name}" def sayGoodbye(name: String) = s"Goodbye ${name}" val functions = Seq[String => String](sayHello, sayGoodbye) functions .map { func => func("DaVe.") } .map(println) // Produces: // // Hello DaVe. // Goodbye DaVe. High Order Functions (or Lambdas) Now that we can pass functions as parameters, we can also return them from functions as return types as well. This enables developers to compose functions into more complicated functions and return that function as the returned value. This is a powerful tool that can be used to construct complicated algorithms in very simple ways. Composition can also be used to dynamically build up business logic and delay execution until all the necessary logic is completely assembled. This can now be done in Java 8 but it is an order of magnitude easier in these new languages. The fact that this feature is a major “bullet point” feature of these almost all of these new languages indicates its importance for developers. def plus1(i: Int): Int = i + 1 def times2(i: Int): Int = i * 2 def minus1(i: Int): Int = i - 1 def composed: Int => Int = { i => minus1(times2(plus1(i))) } // ((i + 1) * 2) - 1 println(composed(5)) // Produces: (( 5 + 1) * 2) - 1 = 11 println(composed(10)) // Produces: ((10 + 1) * 2) - 1 = 21 Pattern Matching (or Case Matching) This is a feature that is worth its weight in gold and a huge code implication. This ability to write compact code to match in type or a value within an object in a very simple easy to understand way is a huge time saver. I will just let a few examples speak for themselves. def pattern(obj: Any): String = obj match { case i: Int => s"Integer = ${i}" case s: String if s.length > 0 => s"String = ${s}" case s: String => s"String is empty" case l: Long => s"Long = ${l}" case unknown => s"Unknown value ${unknown}" } Seq[Any](123, "DaVe.", 456L, "", 0.123).map(pattern).map(println) // Produces: // Integer = 123 // String = DaVe. // Long = 456 // String is empty // Unknown value 0.123 And: case class Contact(first: String, last: String, email: String) def identify(in: Contact): String = in match { case Contact("Dave", _, _) => "Me" case Contact(_, "Buschman", _) => "Family Member" case Contact(_, _, _) => "Kids, do not talk to strangers" } Compiler, Write This Code For Me. Developers now want the compiler to write more code for them so they do not have to. They do not get bogged down in the details of boilerplate code but stay focused on the business logic. Programs, after all, are better at repetitive mundane tasks than humans. Leaving more of the implementation details for the compiler to get right every time simplifies our job. In Scala, For comprehensions and Macros are good examples onf places where we ask the compiler to generate lots of boilerplate code that we don’t want to be bothered with having to do. NOTE: The case matching examples above also make use of compiler-generated code to implement the requested functionality. import play.api.libs.json._ case class Contact(first: String, last: String, email: String) object Contact { // Macro = code generated for Contact JSON de/serialization at compile time implicit val _json = Json.format[Contact] // Awesome implicit magic here } val entity = Contact("Dave", "Buschman", "not@gonna.happen") // Serialization val json = Json.toJson[Contact](entity) println(json.toString()) // Produces: {"first":"Dave","last":"Buschman","email":"not@gonna.happen"} // Deserialization Json.fromJson[Contact](json) match { case JsSuccess(e: Contact, _) => println(s"Full Name is ${e.first} ${e.last}") case JsError(errors) => errors.map(println) } // Produces: Full Name is Dave Buschman Language X is Not the Only Language in This Application Going forward, developers will not be tied to a specific language but will use different languages for different projects based the project’s needs. Polyglot programming is already here with most developers having and primary language like Java or Scala and secondary languages like Maven XML, SBT, Bash, Go, YAML, and even Dockerfile. We already code in multiple secondary languages, it will not be long before most developers will need to be fluent in multiple primary languages as well. The days of entire systems built in a single “one-size-fits-all” language is coming to a close. As an industry, we have matured to the point where interoperability between languages has become common place and easy to accomplish in our build systems. def callJava(in: Option[String]) = System.out.println(in.getOrElse(null)) callJava(Some("foo")) // Produces: foo callJava(None) // Produces: null Conclusion Whether you believe these new languages are all hype or the "best thing since sliced bread" these new languages and the features they provide give developers some powerful tools to make their coding tasks faster and easier to accomplish. It is a great time to be a developer with all of the choices we have at our fingertips. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/new-language-features-on-the-jvm
CC-MAIN-2020-45
refinedweb
1,086
52.39
The official package for the easy-VQA dataset. Project description easy-vqa The official repository for the easy-VQA dataset. Contains: - the official Python package for the dataset - the source code for generating the dataset About the Dataset easy-VQA contains - 4000 train images and 38575 train questions. - 1000 test images and 9673 test questions. - 13 total possible answers. - 28407 training questions that are yes/no. - 7136 testing questions that are yes/no. All images are 64x64 color images. See a live demo of a model trained on the dataset. Example Images Example Questions - What color is the rectangle? - Does the image contain a triangle? - Is no blue shape present? - What shape does the image contain? Installing the Package pip install easy-vqa Using the Package Questions Each question has 3 parts: - the question text - the answer - the image ID The question getters return corresponding arrays for each of the 3 parts: from easy_vqa import get_train_questions, get_test_questions train_questions, train_answers, train_image_ids = get_train_questions() test_questions, test_answers, test_image_ids = get_test_questions() # Question 0 is at index 0 for all 3 arrays: print(train_questions[0]) # what shape does the image contain? print(train_answers[0]) # circle print(train_image_ids[0]) # 0 Images The image path getters return dicts that map image ID to absolute paths that can be used to load the image. from easy_vqa import get_train_image_paths, get_test_image_paths train_image_paths = get_train_image_paths() test_image_paths = get_test_image_paths() print(train_image_paths[0]) # ends in easy_vqa/data/train/images/0.png Answers The answers getter returns an array of all possible answers. from easy_vqa import get_answers answers = get_answers() print(answers) # ['teal', 'brown', 'black', 'gray', 'yes', 'blue', 'rectangle', 'yellow', 'triangle', 'red', 'circle', 'no', 'green'] Generating the Dataset The easy-VQA dataset was generated by running python gen_data/generate_data.py which writes to the easy_vqa/data/ directory. Be sure to install the dependencies for dataset generation running generate_data.py: pip install -r gen_data/requirements.txt If you want to generate a larger easy-VQA dataset, simply modify the NUM_TRAIN and NUM_TEST constants in generate_data.py. Otherwise, if you want to modify the dataset itself, the files and code in the gen_data/ directory should be pretty self-explanatory. 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/easy-vqa/1.0b1/
CC-MAIN-2020-10
refinedweb
375
57.57
UML::Class::Simple - Render simple UML class diagrams, by loading the code This document describes UML::Class::Simple 0.19 released by 26 January 2013. use UML::Class::Simple; # produce a class diagram for Alias's PPI # which has already installed to your perl: @classes = classes_from_runtime("PPI", qr/^PPI::/); $painter = UML::Class::Simple->new(\@classes); $painter->as_png('ppi.png'); # produce a class diagram for your CPAN module on the disk @classes = classes_from_files(['lib/Foo.pm', 'lib/Foo/Bar.pm']); $painter = UML::Class::Simple->new(\@classes); # we can explicitly specify the image size $painter->size(5, 3.6); # in inches # ...and change the default title background color: $painter->node_color('#ffffff'); # defaults to '#f1e1f4' # only show public methods and properties $painter->public_only(1); # hide all methods from parent classes $painter->inherited_methods(0); $painter->as_png('my_module.png'); UML::Class::Simple is a Perl CPAN module that generates UML class diagrams (PNG format, GIF format, XMI format, or dot source) automatically from Perl 5 source or Perl 5 runtime. Perl developers can use this module to obtain pretty class diagrams for arbitrary existing Perl class libraries (including modern perl OO modules based on Moose.pm), by only a single command. Companies can also use the resulting pictures to visualize the project hierarchy and embed them into their documentation. The users no longer need to drag a mouse on the screen so as to draw figures themselves or provide any specs other than the source code of their own libraries that they want to depict. This module does all the jobs for them! :) Methods created on-the-fly (in BEGIN or some such) can be inspected. Accessors created by modules Class::Accessor, Class::Accessor::Fast, and Class::Accessor::Grouped are recognized as "properties" rather than "methods". Intelligent distingishing between Perl methods and properties other than that is not provided. You know, I was really impressed by the outputs of UML::Sequence, so I decided to find something to (automatically) get pretty class diagrams too. The images from Autodia's Graphviz backend didn't quite fit my needs when I was making some slides for my presentations. I think most of the time you just want to use the command-line utility umlclass.pl offered by this module (just like me). See the documentation of umlclass.pl for details. (See also samples/ppi_small.png in the distribution.) (See also samples/moose_small.png in the distribution.) (See also samples/fast.png in the distribution.) Returns a list of class (or package) names by inspecting the perl runtime environment. $module_to_load is the main module name to load while $regex is a perl regex used to filter out interesting package names. The second argument can be omitted. Returns a list of class (or package) names by scanning through the perl source files given in the first argument. $regex is used to filter out interesting package names. The second argument can be omitted. Excludes package names via specifying one or more paths where the corresponding modules were installed into. For example: @classes = exclude_by_paths(\@classes, 'C:/perl/lib'); @classes = exclude_by_paths(\@classes, '/home/foo', '/System/Library'); Filters out package names via specifying one or more paths where the corresponding modules were installed into. For instance: @classes = grep_by_paths(\@classes, '/home/malon', './blib/lib'); All these subroutines are exported by default. $obj->new( [@class_names] ) Create a new UML::Class::Simple instance with the specified class name list. This list can either be constructed manually or by the utility functions classes_from_runtime and classes_from_files. $obj->as_png($filename?) Generate PNG image file when $filename is given. It returns binary data when $filename is not given. $obj->as_gif($filename?) Similar to as_png, bug generate a GIF-format image. Note that, for many graphviz installations, gif support is disabled by default. So you'll probably see the following error message: Format: "gif" not recognized. Use one of: bmp canon cmap cmapx cmapx_np dia dot fig gtk hpgl ico imap imap_np ismap jpe jpeg jpg mif mp pcl pdf pic plain plain-ext png ps ps2 svg svgz tif tiff vml vmlz vtx xdot xlib $obj->as_dom() Return the internal DOM tree used to generate dot and png. The tree's structure looks like this: { 'classes' => [ { 'subclasses' => [], 'methods' => [], 'name' => 'PPI::Structure::List', 'properties' => [] }, { 'subclasses' => [ 'PPI::Structure::Block', 'PPI::Structure::Condition', 'PPI::Structure::Constructor', 'PPI::Structure::ForLoop', 'PPI::Structure::Unknown' ], 'methods' => [ '_INSTANCE', '_set_finish', 'braces', 'content', 'new', 'refaddr', 'start', 'tokens' ], 'name' => 'PPI::Structure', 'properties' => [] }, ... ] } You can adjust the data structure and feed it back to $obj via the set_dom method. $obj->set_dom($dom) Set the internal DOM structure to $obj. This will be used to generate the dot source and thus the PNG/GIF images. $obj->as_dot() Return the Graphviz dot source code generated by $obj. $obj->set_dot($dot) Set the dot source code used by $obj. $obj->as_xmi($filename) Generate XMI model file when $filename is given. It returns XML::LibXML::Document object when $filename is not given. can_run($path) Copied from IPC::Cmd to test if $path is a runnable program. This code is copyright by IPC::Cmd's author. $prog = $obj->dot_prog() $obj->dot_prog($prog) Get or set the dot program path. $obj->size($width, $height) ($width, $height) = $obj->size Set/get the size of the output images, in inches. $obj->public_only($bool) $bool = $obj->public_only When the public_only property is set to true, only public methods or properties are shown. It defaults to false. $obj->inherited_methods($bool) $bool = $obj->inherited_methods When the inherited_methods property is set to false, then all methods, inherited from parent classes, are not shown. It defaults to true. $obj->node_color($color) $color = $obj->node_color Set/get the background color for the class nodes. It defaults to '#f1e1f4'. $obj->moose_roles($bool) When this property is set to true values, then relationships between Moose::Role packages and their consumers will be drawn in the output. Default to false. $obj->display_methods($bool) When this property is set to false, then class methods will not be shown in the output. Default to true. $obj->display_inheritance($bool) When this property is set to false, then the class inheritance relationship will not be drawn in the output. Default to false. Please download and intall a recent Graphviz release from its home: UML::Class::Simple requires the HTML label feature which is only available on versions of Graphviz that are newer than mid-November 2003. In particular, it is not part of release 1.10. Add Graphviz's bin/ path to your PATH environment. This module needs its dot utility. Grab this module from the CPAN mirror near you and run the following commands: perl Makefile.PL make make test make install For windows users, use nmake instead of make. Note that it's recommended to use the cpan utility to install CPAN modules. ::namespace separator in the class diagrams instead of dot ( .) chosen by the UML standard. One can argue that following UML standards is more important since people in the same team may use different programming languages, but I think it's not the case for the majority (including myself) ;-) as_ps, as_jpg, and etc. Please send me your wish list by emails or preferably via the CPAN RT site. I'll add them here or even implement them promptly if I'm also interested in your (crazy) ideas. ;-) There must be some serious bugs lurking somewhere; if you found one, please report it to or contact the author directly. I must thank Adam Kennedy (Alias) for writing the excellent PPI and Class::Inspector modules. umlclass.pl uses the former to extract package names from user's .pm files or the latter to retrieve the function list of a specific package. I'm also grateful to Christopher Malon since he has (unintentionally) motivated me to turn the original hack into this CPAN module. ;-) You can always grab the latest version from the following GitHub repository: It has anonymous access to all. If you have the tuits to help out with this module, please let me know. I have a dream to keep sending out commit bits like Audrey Tang. ;-) Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>, CloudFlare Inc. Maxim Zenin <max@foggy.ru>. Copyright (c) 2006-2013 by Yichun Zhang (章亦春), CloudFlare Inc. Copyright (c) 2007-2013 by Maxim Zenin. This library is free software; you can redistribute it and/or modify it under the same terms as perl itself, either Artistic and GPL. umlclass.pl, Autodia, UML::Sequence, PPI, Class::Inspector, XML::LibXML.
http://search.cpan.org/~agent/UML-Class-Simple-0.19/lib/UML/Class/Simple.pm
CC-MAIN-2016-40
refinedweb
1,404
58.48
The following form allows you to view linux man pages. ); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): getaddrinfo(), freeaddrinfo(), gai_strerror(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE Given dependen- cies. The addrinfo structure used by getaddrinfo() contains the following fields: struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; socklen_t ai_addrlen; struct sockaddr *ai_addr; char *ai_canonname; struct addrinfo *ai_next; }; The hints argument points to an addrinfo structure that specifies ai_flags This field specifies additional options, described below. Multiple flags are specified by bitwise OR-ing them together. All the other fields in the structure pointed to by hints must contain either 0 or a null pointer, as appropriate. Specifying hints as NULL is equivalent to setting ai_socktype and ai_protocol to 0; ai_family to AF_UNSPEC; and ai_flags to (AI_V4MAPPED | AI_ADDRCONFIG). (POSIX specifies different defaults for ai_flags; see NOTES.) node specifies either a numerical network address (for IPv4, numbers-and-dots notation as supported by inet_aton(3); for IPv6, hexadecimal string format as supported by inet_pton(3)), or a network hostname, whose network addresses are looked up and resolved. If hints.ai_flags contains the AI_NUMERICHOST flag then node must be a numerical network address. The AI_NUMERICHOST flag suppresses any potentially lengthy network host address lookups. If the AI_PASSIVE flag is specified in hints.ai_flags, and node is NULL, then the returned socket addresses will be suitable for bind(2)ing a socket that will accept(2) connections. The returned socket address will contain the "wildcard address" (INADDR_ANY for IPv4 addresses, IN6ADDR_ANY_INIT for IPv6 address). The wildcard address is used by applications (typically servers) that intend to accept connec- tions on any of the hosts's network addresses. If node is not NULL, then the AI_PASSIVE flag is ignored. If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned socket addresses will be suitable for use with connect(2), sendto(2), or sendmsg(2). If node is NULL, then the network address will be set to the loopback interface address (INADDR_LOOPBACK for IPv4 addresses, IN6ADDR_LOOPBACK_INIT for IPv6 address); this is used by applications that intend to communicate with peers running on the same host.. Either node or service, but not both, may be NULL. The getaddrinfo() function allocates and initializes a linked list of addrinfo structures, one for each network address that matches node and service, subject to any restrictions imposed by hints, and returns a pointer to the start of the list in res. The items in the linked list set to point to the official name of the host. The remaining fields of each returned addrinfo structure are. config- ured address. This flag is useful on, for example, IPv4-only systems, to ensure that getaddrinfo() does not return IPv6 socket addresses that would always fail in connect(2) or bind(2). If hints res. If both AI_V4MAPPED and AI_ALL are specified in hints.ai_flags, then return both IPv6 and IPv4-mapped IPv6 addresses in the list pointed to by res. AI_ALL is ignored if AI_V4MAPPED is not also speci- fied. functions. hints.ai_flags contains invalid flags; or, hints.ai_flags included AI_CANONNAME and name was NULL. EAI_FAIL The name server returned a permanent failure indication. EAI_FAMILY The requested address family is not supported. ser- vice was not a numeric port-number string. EAI_SERVICE The requested service is not available for the requested socket type. It may be available through another socket type. For example, this error could occur if service was "shell" (a ser- vice available only on stream sockets), and either hints.ai_pro- tocol was IPPROTO_UDP, or hints.ai_socktype was SOCK_DGRAM; or the error could occur if service was not NULL, and hints.ai_socktype was SOCK_RAW (a socket type that does not sup- port the concept of services). EAI_SOCKTYPE The requested socket type is not supported. This could occur, for example, if hints.ai_socktype and hints.ai_protocol are-2001, specifying hints as NULL should cause ai_flags to be assumed as 0. The GNU C library instead assumes a value of (AI_V4MAPPED | AI_ADDRCONFIG) for this case, since this value is considered an improvement on the specification. The following programs demonstrate the use of getaddrinfo(), gai_str- error(), freeaddrinfo(), and getnameinfo(3). The programs are an echo server and client for UDP datagrams. Server program #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h>) { } printf("Received %zd bytes: %s\n", nread, buf); } exit(EXIT_SUCCESS); } getaddrinfo_a(3), gethostbyname(3), getnameinfo(3), inet(3), gai.conf(5), hostname(7), ip(7) webmaster@linuxguruz.com
http://www.linuxguruz.com/man-pages/freeaddrinfo/
CC-MAIN-2017-13
refinedweb
749
58.08
CS 150B - Culture and Coding: Python (AUCC 3B/GT-AH3) def welcome(): # Prints Welcome to CS 150B print("Welcome to CS 150B") Lecture Sections Attendance will be taken in lecture as there are discussion assignments. Instructor Albert Lionelle Instructor and Curriculum Specialist, Computer Science College of Natural Sciences e: Albert.Lionelle@colostate.edu w: 274 Computer Science Building | 1100 Center Avenue Mall | Fort Collins, CO 80523 Office Hours: Wednesday, 1:30-3:00. CSB 274 or via MS Teams (student option) Preferred Contact Private Message on Microsoft Teams Lab Times Attendance is highly encouraged, and directly related to performance. Helpdesk Times - Times are all based on mountain daylight time. Times with a gold background, are times when it is open. - Times that list both a campus room, and MS Teams means there is availability both online and on campus for help-sessions. - Additional in person help -Students are allowed to sit in other labs to get in person help, but priority goes to students who signed up for that lab slot!
https://www.cs.colostate.edu/~cs150b/.Fall21/
CC-MAIN-2022-40
refinedweb
171
59.53
This site uses strictly necessary cookies. More Information I need help adding game resources from outside the game after it's built. After I build a game and after it's built I get the game.exe file and a data folder. I also want to include a folder called Models from which the game will import custom models created by players in the game. How should I approach this problem? Answer by FWCorey · May 09, 2015 at 06:08 PM Your best bet across platforms is to use a configured path and have your game create a folder there the first time it runs. The Application.PersistentDataPath is the best location for this. You can find info on getting the path and caveats on mobile platforms HERE. Though it is not wrong, I would say it is easier just to consider a folder next to the exe file since the data path is somewhere deep down into windows/mac system. It is said in the question that user is asked to add his own models so he may want to keep it simple. Thanks for the answer I'll look into it. @fafalse it's specifically because of $$anonymous$$ac compatibility that I suggested this route. The user may not be able to write to the program's install folder without administrator access on Windows and on $$anonymous$$ac the entire application is encapsulated in a container the user should never modify. Although this can also be an issue on Windows $$anonymous$$etro IIRC since apps there can't even use System.IO and have to use Windows.Storage namespace alternatives to even read them. Yes actually I was only having Windows in mind since it comes in a basic folder where you can add your own manually...my bad No worries, and it may have been okay for this particular instance. Just a bad habit since it might mean code refactoring later. With all the platforms Unity allows a developer to target, it would be a crying shame not to take cross-platform compatibility into account whenever practical. :) Answer by petersvp · Oct 21, 2017 at 09:43 PM This can be done by any way you like. I have single bat file that gets the exe, the data folder and a template folder with my custom data and merges them into directory for publishing, then, actually, publishes the game to the target Distribute terrain in zones 3 Answers How to access unity from within a c# file? 0 Answers Flip over an object (smooth transition) 3 Answers [C#] How would I create skeleton bone transforms from a TRS matrix? 0 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/962738/help-adding-external-files-in-compiled-gamesc.html
CC-MAIN-2021-25
refinedweb
446
62.58
#include <ompl/geometric/planners/sst/SST.h> Detailed Description - Short description - SST (Stable Sparse RRT) is an asymptotically near-optimal incremental sampling-based motion planning algorithm. It is recommended for geometric problems to use an alternative method that makes use of a steering function. Using SST for geometric problems does not take advantage of this function. - External documentation - Yanbo Li, Zakary Littlefield, Kostas E. Bekris, Sampling-based Asymptotically Optimal Sampling-based Kinodynamic Planning. [PDF] Definition at line 59 of file SST 86 of file SST.h. ◆ setPruningRadius() Set the radius for pruning nodes. This is the radius used to surround nodes in the witness set. Within this radius around a state in the witness set, only one active tree node can exist. This limits the size of the tree and forces computation to focus on low path costs nodes. If this value is too large, narrow passages will be impossible to traverse. In addition, children nodes may be removed if they are not at least this distance away from their parent nodes. Definition at line 142 of file SST.h. ◆ setRange() ◆ setSelectionRadius() Set the radius for selecting nodes relative to random sample. This radius is used to mimic behavior of RRT* in that it promotes extending from nodes with good path cost from the root of the tree. Making this radius larger will provide higher quality paths, but has two major drawbacks; exploration will occur much more slowly and exploration around the boundary of the state space may become impossible. Definition at line 121 of file SST.h. The documentation for this class was generated from the following files:
http://ompl.kavrakilab.org/classompl_1_1geometric_1_1SST.html
CC-MAIN-2017-22
refinedweb
269
56.96
Introduction Artificial Intelligence and Machine Learning is going to be our biggest helper in coming decade! Today morning, I was reading an article which reported that an AI system won against 20 lawyers and the lawyers were actually happy that AI can take care of repetitive part of their roles and help them work on complex topics. These lawyers were happy that AI will enable them to have more fulfilling roles. Today, I will be sharing a similar example – How to count number of people in crowd using Deep Learning and Computer Vision? But, before we do that – let us develop a sense of how easy the life is for a Crowd Counting Scientist. Act like a Crowd Counting Scientist Let’s start! Can you help me count / estimate number of people in this picture attending this event? Ok – how about this one? Source: ShanghaiTech Dataset You get the hang of it. By end of this tutorial, we will create an algorithm for Crowd Counting with an amazing accuracy (compared to humans like you and me). Will you use such an assistant? P.S. This article assumes that you have a basic knowledge of how convolutional neural networks (CNNs) work. You can refer to the below post to learn about this topic before you proceed further: Table of Contents - What is Crowd Counting? - Why is Crowd Counting required? - Understanding the Different Computer Vision Techniques for Crowd Counting - The Architecture and Training Methods of CSRNet - Building your own Crowd Counting model in Python This article is highly inspired by the paper – CSRNet : Dilated Convolutional Neural Networks for Understanding the Highly Congested Scenes. What is Crowd Counting? Crowd Counting is a technique to count or estimate the number of people in an image. Take a moment to analyze the below image: Source: ShanghaiTech Dataset Can you give me an approximate number of how many people are in the frame? Yes, including the ones present way in the background. The most direct method is to manually count each person but does that make practical sense? It’s nearly impossible when the crowd is this big! Crowd scientists (yes, that’s a real job title!) count the number of people in certain parts of an image and then extrapolate to come up with an estimate. More commonly, we have had to rely on crude metrics to estimate this number for decades. Surely there must be a better, more exact approach? Yes, there is! While we don’t yet have algorithms that can give us the EXACT number, most computer vision techniques can produce impressively precise estimates. Let’s first understand why crowd counting is important before diving into the algorithm behind it. Why is Crowd Counting useful? Let’s understand the usefulness of crowd counting using an example. Picture this – your company just finished hosting a huge data science conference. Plenty of different sessions took place during the event. You are asked to analyze and estimate the number of people who attended each session. This will help your team understand what kind of sessions attracted the biggest crowds (and which ones failed in that regard). This will shape next year’s conference, so it’s an important task! There were hundreds of people at the event – counting them manually will take days! That’s where your data scientist skills kick in. You managed to get photos of the crowd from each session and build a computer vision model to do the rest! There are plenty of other scenarios where crowd counting algorithms are changing the way industries work: - Counting the number of people attending a sporting event - Estimating how many people attended an inauguration or a march (political rallies, perhaps) - Monitoring of high-traffic areas - Helping with staffing allocation and resource allotment Can you come up with some other use cases? Let me know in the comments section below! We can connect and try to figure out how we can use crowd counting techniques in your scenario. Understanding the Different Computer Vision Techniques for Crowd Counting Broadly speaking, there are currently four methods we can use for counting the number of people in a crowd: 1. Detection-based methods Here, we use a moving window-like detector to identify people in an image and count how many there are. The methods used for detection require well trained classifiers that can extract low-level features. Although these methods work well for detecting faces, they do not perform well on crowded images as most of the target objects are not clearly visible. 2. Regression-based methods We were unable to extract low level features using the above approach. Regression-based methods come up trumps here. We first crop patches from the image and then, for each patch, extract the low level features. 3. Density estimation-based methods We first create a density map for the objects. Then, the algorithm learn a linear mapping between the extracted features and their object density maps. We can also use random forest regression to learn non-linear mapping. 4. CNN-based methods Ah, good old reliable convolutional neural networks (CNNs). Instead of looking at the patches of an image, we build an end-to-end regression method using CNNs. This takes the entire image as input and directly generates the crowd count. CNNs work really well with regression or classification tasks, and they have also proved their worth in generating density maps. CSRNet, a technique we will implement in this article, deploys a deeper CNN for capturing high-level features and generating high-quality density maps without expanding the network complexity. Let’s understand what CSRNet is before jumping to the coding section. Understanding the Architecture and Training Method of CSRNet CSRNet uses VGG-16 as the front end because of its strong transfer learning ability. The output size from VGG is ⅛th of the original input size. CSRNet also uses dilated convolutional layers in the back end. But what in the world are dilated convolutions? It’s a fair question to ask. Consider the below image: The basic concept of using dilated convolutions is to enlarge the kernel without increasing the parameters. So, if the dilation rate is 1, we take the kernel and convolve it on the entire image. Whereas, if we increase the dilation rate to 2, the kernel extends as shown in the above image (follow the labels below each image). It can be an alternative to pooling layers. Underlying Mathematics (Recommended, but optional) I’m going to take a moment to explain how the mathematics work. Note that this isn’t mandatory to implement the algorithm in Python, but I highly recommend learning the underlying idea. This will come in handy when you need to tweak or modify your model. Suppose we have an input x(m,n), a filter w(i,j), and the dilation rate r. The output y(m,n) will be: We can generalize this equation using a (k*k) kernel with a dilation rate r. The kernel enlarges to: ([k + (k-1)*(r-1)] * [k + (k-1)*(r-1)]) So the ground truth has been generated for each image. Each person’s head in a given image is blurred using a Gaussian kernel. All the images are cropped into 9 patches, and the size of each patch is ¼th of the original size of the image. With me so far? The first 4 patches are divided into 4 quarters and the other 5 patches are randomly cropped. Finally, the mirror of each patch is taken to double the training set. That, in a nutshell, are the architecture details behind CSRNet. Next, we’ll look at its training details, including the evaluation metric used. Stochastic Gradient Descent is used to train the CSRNet as an end-to-end structure. During training, the fixed learning rate is set to 1e-6. The loss function is taken to be the Euclidean distance in order to measure the difference between the ground truth and estimated density map. This is represented as: where N is the size of the training batch. The evaluation metric used in CSRNet is MAE and MSE, i.e., Mean Absolute Error and Mean Square Error. These are given by: Here, Ci is the estimated count: L and W are the width of the predicted density map. Our model will first predict the density map for a given image. The pixel value will be 0 if no person is present. A certain pre-defined value will be assigned if that pixel corresponds to a person. So, calculating the total pixel values corresponding to a person will give us the count of people in that image. Awesome, right? And now, ladies and gentlemen, it’s time to finally build our own crowd counting model! Building your own Crowd Counting model Ready with your notebook powered up? We will implement CSRNet on the ShanghaiTech dataset. This contains 1198 annotated images of a combined total of 330,165 people. You can download the dataset from here. Use the below code block to clone the CSRNet-pytorch repository. This holds the entire code for creating the dataset, training the model and validating the results: git clone Please install CUDA and PyTorch before you proceed further. These are the backbone behind the code we’ll be using below. Now, move the dataset into the repository you cloned above and unzip it. We’ll then need to create the ground truth values. The make_dataset.ipynb file is our savior. We just need to make minor changes in that notebook: #setting the root to the Shanghai dataset you have downloaded # change the root path as per your location of dataset root = '/home/pulkit/CSRNet-pytorch/' Now, let’s generate the ground truth values for images in part_A and part_B: Generating the density map for each image is a time taking step. So go brew a cup of coffee while the code runs. So far, we have generated the ground truth values for images in part_A. We will do the same for the part_B images. But before that, let’s see a sample image and plot its ground truth heatmap: plt.imshow(Image.open(img_paths[0])) Things are getting interesting! gt_file = h5py.File(img_paths[0].replace('.jpg','.h5').replace('images','ground-truth'),'r') groundtruth = np.asarray(gt_file['density']) plt.imshow(groundtruth,cmap=CM.jet) Let’s count how many people are present in this image: np.sum(groundtruth) 270.32568 Similarly, we will generate values for part_B: Now, we have the images as well as their corresponding ground truth values. Time to train our model! We will use the .json files available in the cloned directory. We just have to change the location of the images in the json files. To do this, open the .json file and replace the current location with the location where your images are located. Note that all this code is written in Python 2. Make the following changes if you’re using any other Python version: - In model.py, change xrange in line 18 to range - Change line 19 in model.py with: list(self.frontend.state_dict().items())[i][1].data[:] = list(mod.state_dict().items())[i][1].data[:] - In image.py, replace ground_truth with ground-truth Made the changes? Now, open a new terminal window and type the following commands: cd CSRNet-pytorch python train.py part_A_train.json part_A_val.json 0 0 Again, sit back because this will take some time. You can reduce the number of epochs in the train.py file to accelerate the process. A cool alternate option is to download the pre-trained weights from here if you don’t feel like waiting. Finally, let’s check our model’s performance on unseen data. We will use the val.ipynb file to validate the results. Remember to change the path to the pretrained weights and images. #defining the image path img_paths = [] for path in path_sets: for img_path in glob.glob(os.path.join(path, '*.jpg')): img_paths.append(img_path) model = CSRNet() #defining the model model = model.cuda() Check the MAE (Mean Absolute Error) on test images to evaluate our model: We got an MAE value of 75.69 which is pretty good. Now let’s check the predictions on a single image: Wow, the original count was 382 and our model estimated there were 384 people in the image. That is a very impressive performance! Congratulations on building your own crowd counting model! End Notes I encourage you to try out this approach on different images and share your results in the comments section below. Crowd counting has so many diverse applications and is already seeing adoption by organizations and government bodies. It is a useful skill to add to your portfolio. Quite a number of industries will be looking for data scientists who can work with crowd counting algorithms. Learn it, experiment with it, and give yourself the gift of deep learning! Did you find this article useful? Feel free to leave your suggestions and feedback for me below, and I’ll be happy to connect with you. You should also check out the below resources to learn and explore the wonderful world of computer vision: - Certified Course: Computer Vision using Deep Learning - A Step-by-Step Introduction to the Basic Computer Vision Algorithms - Understanding and Building your First Object Detection Model from Scratch - Learn Object Detection using the Popular YOLO Framework 75 Comments Nicely explained the complex concept of Crowd counting . And its very helpful. Thank you Saurabh! Very nicely explained. Good one Pulkit Great learning through your article . The zip file with pre-trained weights is corrupt , Could you provide the correct file please? “A cool alternate option is to download the pre-trained weights from here if you don’t feel like waiting.” Hi vivek, The link is working fine at my end. What is the error that you are getting while downloading the weights? The file downloaded from the link is not correct. I cant un-tar it, also facing issue while loading it at Kaggle kernel. Hello Pultik, I am able to use pre-trained weights now. I am using google colab kernel (with GPU) to process data. Kaggle on other hand tries to process your uploaded .tar file and failed to do so, which results in; coucln’t upload file at all! Here I have slightly modified code to work with Python 3, Thanks a lot for sharing wonderful information! *Pulkit Apology for typo. Hi, how could you untar the 0model….tar file? Thanks Hi, I’m getting an issue, when trying to replicate the concept. I kept the screenshots here about the issue as well as the part of the code where it is occurring. Hi Mohan, Make sure that you are providing the correct location for the images. You have to give the entire location of the directory where your images are. The path and everything is correct only. check this pic out, i added some logs Hi I was facing the similar issue and the solution that worked for me was that i was using python3 for the code but when i switched to python2 everything was working fine, So you could give it a try? I thought I won’t be able to deal with computer vision. But after reading this article i am amazed. Thank you Yogesh! Hi Sir! I tried this method using CPU version of torch, and I modified the code accordingly to make it work. But after one picture has een evaluated, the RAM usage suddenly booms and freezes my system entirely. Is this a memory leak on my part, or does the model require a lot of RAM? (I have 8GB RAM) Hi Nimish, This might be an issue related to RAM. As it is a heavy dataset, you will require more RAM. Instead of training your own model, you can download the trained weights given in the article to make predictions for new images. How do we give the path in Windows? UNABLE TO GENERATE GROUND TRUTHS! Does this code run only on Linux? What changes must be made to replicate this code on Windows considering that the system has Cuda, Anaconda with Python3.7 and PyTorch ? Hi Aditya, These codes will work on windows too. You just have to give the entire path of the images and their corresponding density maps. Any option to bypass this cuda since my machine has nvidea GPU 410M only which is not supporting the cuda9.X Hi Anjalina, You can use cloud services to run these codes. Some of the options could be: Google Colab Paperspace Hi Pulkit, Sorry for disturbing you . I am very new to this field and it would be great if you could give some pointer to find out solutions to the issue that I am facing. I was trying to predict the crowed count of a local image(xyz.jpg). I don’t have .mat files of my local image. I could see the dataset that you have shared contains images and the corresponding .mat files. I just created a predict.py as you mentioned in your code. Without training (python train.py part_A_train.json part_A_val.json 0 0) and all, I just added the following code to predict.py(hope this is sufficient for all other steps that you mentioned) checkpoint = torch.load(‘part_A/0model_best.pth.tar’) model.load_state_dict(checkpoint[‘state_dict’]) while running the predict.py it was complaining about the “xyv.h5”. Says this file not found in: temp = h5py.File(‘part_A/test_data/ground-truth/xyv.h5’, ‘r’) Could you please assist me to get an understanding about the .mat, .h5 and its dependency in original count prediction. This is the same problem that I am having.() The later part of the code was to compare the result when you know the actual count of the person in the image which in your case seems is not known. So, use the above code and just change the path of the image. This will give you the count for new image. Hey, thanks for the article I’m running CUDA on my laptop with 16gb ram and 2gb video memory but alway caught the “CUDA out of memory. Tried to allocate 86.00 MiB (GPU 0; 2.00 GiB total capacity; 927.71 MiB already allocated; 51.00 MiB free; 355.54 MiB cached)” what is the requirements for training? or how can I fix this? Hi Yuriy, I trained the model using very high compute. I had a ram of 128 GB. Generally, it is not easily available. So, you can just download the trained weights which I have shared in the article and use them to get predictions for new images. link to trained weights is not working Hi Ruchika, The link is working at my end. Can you share what is the error that you are getting? Hello Pulkit the error when trying on windows 10 is the archive is either in unknown format of is damaged similar error in linux also an error occured while loading the archive Hi Pulkit, I love the tutorial, but the theory about making ground truth and density map were a bit hard for me. Could you give some sources to find an explanation of how to generate ground truth without counting the number of people in images manually? Rgs, Mr. T Hi, You can look at the following resource : please correct me if I am wrong. I am very new to this field.This might be a simple question for you. From this article what I could understand is evenif I supply any image from my local collection, the prediction.py will provide the crowed count. With this assumption when I tried, for example I have added IMG5000.jpg in the images and tried to run prediction.py, its complaining about the h5 and mat files since its not there in the dataset. mat = io.loadmat(img_path.replace(‘.jpg’,’.mat’).replace(‘images’,’ground-truth’).replace(‘IMG_’,’GT_IMG_’)) is complaning about this.. How do you get the .mat files for each image? Thanks. Hi esther, I took the ShanghaiTech dataset. They have provided the .mat files for those images. Thank you for this. How can I use it to count the number of people in unlabeled images? Hi Esther,. Pulkit, thank you so much for this. I’ve gotten everything to work using google colab with GPU acceleration. Now, how can I use this to test new images? Thanks! Hi Esther, As mentioned in the post as well, you can use the following code to get predictions for the new images:() Here, you just have to give the path to your image. I got it to work now. I had to change the filenames of my new images to begin with “IMG_” Thanks so much!!! Your article is very helpful. Thanks a lot for explaining this in a better way. But when I tested the “part_B_final/test_data_backup/images/IMG_1.jpg” with the above code(reply to Esther), I could see the count that we are getting is 54 , actual the count is only less than 30. Similarly getting some weird counts if I try images with very less count , say 1, 2 or three. May I know whether this issue is with the the way that I am executing this code or this code is not considering all those cases Hi Arun,. Hi Pulkit, Awesome doc. Thanks you for posting this. This doc definitely would be helpful to all those who are interested to explore in this area. I am facing an issue while running this code. It would be great if you could suggest a solution for the same. I have 14GB RAM and the following is the nvidia-smi console output. +—————————————————————————–+ | NVIDIA-SMI 418.56 Driver Version: 418.56 CUDA Version: 10.1 | |——————————-+———————-+———————-+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce MX110 Off | 00000000:01:00.0 Off | N/A | | N/A 49C P0 N/A / N/A | 443MiB / 2004MiB | 3% Default | +——————————-+———————-+———————-+ +—————————————————————————–+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 1480 G /usr/lib/xorg/Xorg 172MiB | | 0 1651 G /usr/bin/gnome-shell 118MiB | | 0 5000 G …quest-channel-token=8194962126415318391 146MiB | | 0 6268 G /snap/pycharm-community/123/jre64/bin/java 2MiB | I am getting frequent Runtimeerror, even-if I try to predict the crowed count of 150 kb file. The error I am getting is as follows: RuntimeError: CUDA out of memory. Tried to allocate 174.38 MiB (GPU 0; 1.96 GiB total capacity; 1.31 GiB already allocated; 65.50 MiB free; 1.12 MiB cached). The following the code base that I am running: import PIL.Image as Image import numpy as np from matplotlib import pyplot as plt from image import * from model import CSRNet import torch import gc; gc.collect() torch.cuda.empty_cache() from torchvision import datasets, transforms transform=transforms.Compose([ transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) model = CSRNet() model = model.cuda() checkpoint = torch.load(‘/home/abc/Downloads/Shanghai/part_A_final/0model_best.pth.tar’) model.load_state_dict(checkpoint[‘state_dict’]) from matplotlib import cm as c img = transform(Image.open(“/home/abc/Downloads/Shanghai/xyz() Hi Aiswarya, Try to use a GPU to run these codes. As the codes are heavy, they might not run on a cpu. You can try to run these codes on google colab as well which provides free GPU access. Hi Pulkit, The ‘0model_best.pth.tar’ contain the pretrained weight of the 1198 images(ie the train and test images of part_A and part_B) right? Hi Bharth, These pretrained weights only contains the learning from the train images and not the test images. Hi Pulkit, Excellent explanation, keep on the good work! I am running the code on Anaconda python 3 on windows and it did not like the following line if gt_count > 1: in the “# function to create density maps for images” Line 20 it complained about the semicolon. is there a problem in the syntax ? Also I had to install openCV which was not mentioned in the explanation but needed by the code. Hi Mishal, If you are using if statement, you have to give : after the condition. And thank you for pointing out about openCV. I will add that in the article. Thanks a lot for this doc. For the crowed prediction, DO you think it has some dependency with the image size and pixels. I could see the trian images are with a dimensions of 1024*768 . Do you think if the image size and dimension is bigger then the accuracy will also be more fine tuned. Hi Beenu, It depends. I can not confirm that increasing the shape of image will always give better performance. The performance might improve and you might get a better model. But, as you increase the size of the image, computation cost also increases. You will need more memory to store those images and stronger computation to build your model on larger images. So, you must also try to reduce the computation cost instead of just focusing on improving the model performance. Hi! great article! I have stumped into a little problem and I do not know how to fix it. This is the error I am receiving: IndexError Traceback (most recent call last) in () 1 #now see a sample from ShanghaiA —-> 2 plt.imshow(Image.open(img_paths[0])) IndexError: list index out of range The location of my root is this: #set the root to the Shanghai dataset you download root = ‘/Desktop/CSRNet-pytorch-master/ShanghaiTech’ #now generate the ShanghaiA’s ground truth part_A_train = os.path.join(root,’part_A/train_data’,’images’) part_A_test = os.path.join(root,’part_A/test_data’,’images’) part_B_train = os.path.join(root,’part_B/train_data’,’images’) part_B_test = os.path.join(root,’part_B/test_data’,’images’) path_sets = [part_A_train,part_A_test] I do not understand why I am receiving the error Could someone help me? Hi Nihed, It seems like you have not given the correct path and hence img_paths is empty. Try to give the exact path of the images and then run this code. Hi Pulkit! I do not have an GPU processor that works for this.. How do I use Google Colab? OR could you maybe send me the right pre weights because your I am unable to open your tar. file.. I am working on a MacBook Pro Kind regards, Nihed I mean that I do not understand how I should use this in Google Colab: cd CSRNet-pytorch python train.py part_A_train.json part_A_val.json 0 0 Because I receive this: [Errno 2] No such file or directory: ‘CSRNet-pytorch’ /content/drive/My Drive/CSRNet-pytorch [Errno 2] No such file or directory: ‘train.py part_A_train.json part_A_val.json 0 0’ /content/drive/My Drive/CSRNet-pytorch while the file is there in my google drive…… Hi Pulkit , Can you share the drive link for pre trained weights again ? it seems as if it is damaged because i tried open it in both linux and windows but failed to do so . It will be really helpful ! Hi Aayush, The link is working fine at my end. Here is the link for your reference: I am new in this field, i know only basics of machine learning. What are the pre-requisite to know this article completely. If you have source, then please send me their links. Thank you . Hi Rahul, You can refer this course: Hi! This is a great article! Can this framework be used to do people detection? Hi Jarvah, This framework is just to count the number of people in an image and will not be effective for detection tasks. For Object detection or people detection tasks, you can try frameworks like Faster RCNN or YOLO, etc. As, I am very new to machine learning. Kindly, clear me this error. I cant find .h5 file inside gt_file=’part_A/test_data/ground-truth/IMG_100.h5′,r in Part-B Cool Method .Thank you Hi Vignesh, For test images, you have to predict the count of people in the images and hence .h5 file is not available for test images. .h5 file contains the predictions. This is really great work! very impressed! I’d like to know whether I can use these scripts for commercial use. Hi Minoru, Contact me at [email protected] so that we can discuss where you will be using these scripts, what would be the application and other things. We can discuss these things and then decide whether it can be used or not. Thank for the great tutorial. How I can visualize the counted heads? either by boundary boxes or points on the considered head? Thank you Hi Somayah, It return the density plot. You can visualize that to see where are the people in the image. Hello Pulkit Sharma, Can we merge Part A and Part B images instead of splitting in two parts? Thankyou in advance. Hi Suraj, Part A and Part B contains two different type of problems. In Part A, we have images having a high density of people whereas Part B images have a lower density. You can try to merge these Part A and Part B images and then check the results. Hello Pulkit, When importing libraries it gives error like this. – no module named ‘model’ – no module named ‘image’ I’m using Anaconda3 and Python 3.7. how long does it take to train the network Hi Ruchika, It depends on the configuration of the system that you are using. I trained it on a system having 16 GB RAM, and 20 cores and it took around 5-6 hours to train the model. the link below of drive you have shared is not working please share a working link again Thanks Was the pre-trained model that you provided trained on part A dataset or part B dataset. If it was for part A, can you please provide the one trained on part B as well. Hi Divyakant, The pre-trained weights are for Part A images. I have not trained the model for Part B images. You can easily train the model for images in Part B as well following the steps mentioned in the article. If you get stuck somewhere, or need any assistance, I will be happy to help.
https://www.analyticsvidhya.com/blog/2019/02/building-crowd-counting-model-python/?utm_source=blog&utm_medium=20-popular-machine-learning-and-deep-learning-articles-on-analytics-vidhya-in-2019
CC-MAIN-2020-34
refinedweb
5,080
66.54
Glenn Morris wrote: > Stefan Monnier wrote: > >>> configure: error: cannot find install-sh, install.sh, or shtool in "." >>> "./.." "./../.." > >> We're miscommunicating: the original report showed the error to be the >> lack of install-sh and doesn't mention automake. So the missing rule is >> to call autogen.sh or autoreconf or something when install-sh >> is missing. > > (autogen.sh calls autoreconf which calls automake to add the files) > > Well, there's nothing to be done about it now. Any new make rule would > only take effect after running configure, and anyone who can run > configure does not need such a rule. Anyone would ran autogen.sh between > ~ Mar 20 and 25 should simply run it again if they have this issue. Hi Glenn, Actually, you *can* do something, assuming the victim has GNU make. Put something like the following in GNUmakefile, and then "make" works even before ./configure is run, even if it's just to instruct the user to run ./configure. [The following is part of gnulib's top/GNUmakefile, which is included automatically when you use its "gnumakefile" module. ] # Having a separate GNUmakefile lets me `include' the dynamically # generated rules created via cfg.mk (package-local configuration) # as well as maint.mk (generic maintainer rules). # This makefile is used only if you run GNU Make. # It is necessary if you want to build targets usually of interest # only to the maintainer. # Copyright (C) 2001, 2003, # If the user runs GNU make but has not yet run ./configure, # give them a diagnostic. _have-Makefile := $(shell test -f Makefile && echo yes) ifeq ($(_have-Makefile),yes) # Allow the user to add to this in the Makefile. ALL_RECURSIVE_TARGETS = include Makefile .DEFAULT_GOAL := abort-due-to-no-makefile # The package can override .DEFAULT_GOAL to run actions like autoreconf. -include ./cfg.mk include ./maint.mk ifeq ($(.DEFAULT_GOAL),abort-due-to-no-makefile) $(MAKECMDGOALS): abort-due-to-no-makefile endif abort-due-to-no-makefile: @echo There seems to be no Makefile in this directory. 1>&2 @echo "You must run ./configure before running \`make'." 1>&2 @exit 1 endif
http://lists.gnu.org/archive/html/emacs-devel/2011-03/msg01186.html
CC-MAIN-2018-09
refinedweb
343
60.51
Overview of Function A function is a self-contained block of statements that perform a coherent task of some kind. Every C program can be thought of as a collection of these functions. The programs written in C language are highil dependent on functions. The C program is nothing but a combination of one or more functions. Every C program starts with user defined function main( ). Each time when a new program is started, main( ) function must be defined. The main( ) calls another function to share the work. Syntax data type function (argument 1, argument 2) { //functions body; } Example:- #include <stdio.h> int main() { int x = 3; int x = 6; z = add`(x,y); // Function Call printf("z=%d",z); } add(a,b); // Function Definition { a+b; } Output: z=9 Why use function ? Types of Function There are basically two types of functions: Library functions: These function are allready defined in header file. Ex:- printf();, scanf();, sin();, cos();, etc.. User-defined functions: These function are defined by a user on his requirement. Ex:- india();, msg(); etc..
http://www.cseworldonline.com/tutorial/c_function.php
CC-MAIN-2019-18
refinedweb
176
67.15
Closed Bug 203639 Opened 18 years ago Closed 18 years ago Title tag not using carriage return Categories (Core :: Layout: Form Controls, defect) Tracking () People (Reporter: oleevye, Unassigned) Details User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030427 Mozilla Firebird/0.6 Build Identifier: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030427 Mozilla Firebird/0.6 In the exemple, the tooltip should look like: This should use carriage return BUT it looks like This should use [][] carriage return ([] is in fact a square...) I don't know if there is a good way to do multi line tooltips, this works in IE. Anyway, tell me if i'm making a mistake in thinking this should work like this :) Cheers mozilla team. Reproducible: Always Steps to Reproduce: 1. Open the test page 2. Hover the link with the cursor and wait a moment 3. A broken tooltip appears Actual Results: A tooltip with: This should use [][] carriage return Expected Results: I expected: This should use carriage return A testcase: <html> <head></head> <body> <a href='bla' title='This should use carriage return'>Some link</a> </body> </html> *** This bug has been marked as a duplicate of 67127 *** Status: UNCONFIRMED → RESOLVED Closed: 18 years ago Resolution: --- → DUPLICATE
https://bugzilla.mozilla.org/show_bug.cgi?id=203639
CC-MAIN-2021-10
refinedweb
222
75.1
Reading a CSV from a file is a very simple affair, and something that you are likely going to have to do many times during your career as a data scientist. As an example lets can read our CSV: import pandas To understand how to read CSV let’s use Python’s help function: help(pandas.read_csv) Help on function read_csv in module pandas.io.parsers: read_csv(filepath_or_buffer:Union[str, pathlib.Path, IO[~AnyStr]],:str='.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect``. By file-like object, we refer to objects with a ``read()`` method, such as a file handler (e.g. via builtin ``open`` function) or ``StringIO``. sep : str, default ','`` Alias for sep. header : int, list of int,. ... There are quite a lot of parameters that read_csv will accept, for many use-cases that you might find. I will not go into detail on those for now. Let’s just read our CSV: pd = pandas.read_csv("nativity_dataset.csv") display(pd) 220 rows × 3 columns It was that easy! You will notice that I used the display function to show the panda dataframe quite nicely. If you used the print() function it would have looked quite ugly: print(pd) Image URL ... Labels 0... ... NaN 1... ... NaN 2... ... NaN 3... ... NaN 4... ... NaN .. ... ... ... 215... ... NaN 216... ... NaN 217... ... NaN 218... ... NaN 219... ... NaN [220 rows x 3 columns] Ommitting the pandas display function¶ If you are too lazy to call display you can ommit it. For instance: pd 220 rows × 3 columns What happened there?¶ The python notebook called the display function for us because it was the last value in the the python block. Changing the column names¶ If you don’t like the column headers you can easily change it when reading the CSV: pd = pandas.read_csv("nativity_dataset.csv", names=["Precise Image URL", "Precise Source URL", "Precise Labels"]) pd 221 rows × 3 columns It was almost what we wanted. But seems like the previous column names are still there. No worries, it is easy to fix. pd = pandas.read_csv("nativity_dataset.csv", header=0, names=["Precise Image URL", "Precise Source URL", "Precise Labels"]) pd 220 rows × 3 columns You will notice that we have a column without any data(“Labels”). Let’s delete it. In [ ]: del pd["Precise Labels"] pd 220 rows × 2 columns The column is gone. Let’s save the panda dataframe to a CSV pd.to_csv("nativity_dataset_updated.csv") That was easy, right? There is a lot more that we can do with pandas and CSVs but I am sure this will help you get started. That will be all for now. Happy Coding! RESOURCES Google Colab Notebook: Github Repository: Recent Comments
https://spltech.co.uk/how-to-read-and-write-to-a-csv-using-pandadf/
CC-MAIN-2021-31
refinedweb
450
74.69
File manager rename and copy functions Please add features to the file manager to allow copying an existing file into a new one and renaming files. Renaming files is already possible. Open the file in the editor, tap its title and then the little rename icon. For folders, go into the folder, switch to "Edit" mode, and then you have a rename icon next to the "Done" button. For copying files I use a short script like this as an editor action: import console import editor import os import shutil DOCUMENTS = os.path.expanduser("~/Documents") old_name = editor.get_path() new_name = os.path.join(DOCUMENTS, console.input_alert("Duplicate File", "Enter new name", os.path.relpath(old_name, DOCUMENTS))) if os.path.exists(new_name): console.hud_alert("Destination already exists", "error") else: shutil.copy(old_name, new_name) ##editor.open_file(os.path.relpath(new_name, DOCUMENTS)) # For old Pythonistas editor.open_file(new_name) Of course this only works one file at a time. For copying multiple files stash is currently the best solution. PhoneManager !? Yes, I love it (now that I know it). 😀 Thanks for the suggestions, @dgelessus. The rename feature in the editor isn't enough. In my case, it's not even possible for one file. As an experiment, I renamed a .pyui file to .json. I changed some coordinates from "{{x,y},{w,h}}"strings to [[x,y],[w,h]]structures. It worked in the app that used it, but when I renamed the file back to .pyui, all attempts to open it cause Pythonista itself to crash. I know I can rename or copy files with function calls from the console or a program. However, the file manager should have this feature, too. It feels incomplete without them. @lsloan The UI editor doesn't handle malformed files very well. If you're in a crash loop, you can launch Pythonista by entering pythonista://in Safari's address bar. This will skip restoring the previously-open files. Of course that crashes Pythonista. You're changing the internal structure of a file that is not meant to be edited by hand. Okay, Pythonista should probably display an error instead of crashing entirely, but this is not exactly the normal use case of pyuifiles. ;) The current state is also much better than what it was like in version 1.5. There the editor would refuse to open files with an unknown extension, even if they were text files, and when renaming it would automatically set the extension to .pyif you used something other than .pyor .txt.
https://forum.omz-software.com/topic/2973/file-manager-rename-and-copy-functions/1
CC-MAIN-2021-43
refinedweb
418
69.07
Example of Celebrity Rekognition with AWS Want to share your content on python-bloggers? click here. Rekognition with Console Amazon Rekognition gives us the chance to recognize celebrities in images and videos. For our example, I will choose the images of Antentokounmpo Brothers and we will see if the Rekognition can recognize them. You can try this image in the AWS Console. Let’s see what we get: As we can see, it managed to detect Giannis and Thanasis Antentokounmpo! The rest brothers should wait until they become true celebrities apparently Rekognition with boto3 We can get call the API via Python and boto3 and we can get all the info from the API response which is in json format. We will provide an example of how you can simply get the name of the celebrities. We will work again with the same image. import boto3 import json # create a connection with the rekognition client=boto3.client('rekognition') #define the photo photo = "Giannis-Antetokounmpo-Brothers.jpg" # call the API and get the response with open(photo, 'rb') as image: response = client.recognize_celebrities(Image={'Bytes': image.read()}) for celebrity in response['CelebrityFaces']: print ('Name: ' + celebrity['Name'] + ' with Confidence: ' + str(celebrity['MatchConfidence'])) Output: Name: Thanasis Antetokounmpo with Confidence: 58.999996185302734 Name: Giannis Antetokounmpo with Confidence: 57.0 Notice that the response contains much information like the Bounding Boxes etc. As you can see we used the boto3, if you want to learn more about it you can have a look at the Basic Introduction to Boto3 Want to share your content on python-bloggers? click here.
https://python-bloggers.com/2020/10/example-of-celebrity-rekognition-with-aws/
CC-MAIN-2021-10
refinedweb
264
54.93
Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office. You can subscribe to this list here. Showing 4 results of 4 Jan Strube wrote: > No, there is no mechanism for doing this, although I think it has been requested before. Eric Hello. I am new at matplotlib and am trying to modify the lasso demo so that a line is drawn aound the polygon made of selected points, and so that this polygon area is shaded. Ive added the following code to the callback function but receive the error: CXX : Error creating object of type N2Py7SeqBaseINS_6ObjectEEE. Im sure this is a simple modification. Can anyone offer suggestions? def callback(self, verts): ind = nx.nonzero(points_inside_poly(self.xys, verts)) for i in range(self.Nxy): if i in ind: self.facecolors[i] = Datum.colorin else: self.facecolors[i] = Datum.colorout xyo=list() for i in ind: xyo.append(self.xys[i]) col = RegularPolyCollection(fig.dpi, 7, sizes = 3, offsets=xyo, transOffset=ax.transData) ax.add_collection(col, autolim=True) trans = transforms.scale_transform(fig.dpi/transforms.Value(72.),fig.dpi/transforms.Value(72.)) col.set_transform(trans) # the points to pixels transform colors = [colorConverter.to_rgba(c) for c in ('r','g','b','c','y','m','k')] col.set_color(colors) self.canvas.draw_idle() self.canvas.widgetlock.release(self.lasso) del self.lasso ____________________________________________________________________________________ Don't get soaked. Take a quick peak at the forecast with the Yahoo! Search weather shortcut. Hi, I'm trying to create an application that, among other things, will allow me to view an image, zoom into it, and move it around. Essentially what I can do by using imshow and show in ipython. However, I've noticed that in both interactive usage and my application the image comes up in a small set of axes that do not fill up the screen 100% (the image is rectangular). Zooming or dragging the image around then causes part of it to go off the axes, which is not desirable. What I would like to do is increase the size of the area where the image can be displayed to the area given to the canvas in my application. Then, if I drag the image around, part of it won't disappear. However, I'm not really sure how to do this. What is the best way to accomplish this goal (preferably for non-interactive usage - I'm using the QT4 back end)? Thank you in advance, David Levitan
http://sourceforge.net/p/matplotlib/mailman/matplotlib-users/?viewmonth=200702&viewday=4
CC-MAIN-2014-35
refinedweb
424
59.7
[c#] In .NET, which loop runs faster, 'for' or 'foreach'? foreach loops demonstrate more specific intent than for loops. Using a foreach loop demonstrates to anyone using your code that you are planning to do something to each member of a collection irrespective of its place in the collection. It also shows you aren't modifying the original collection (and throws an exception if you try to). The other advantage of foreach is that it works on any IEnumerable, where as for only makes sense for IList, where each element actually has an index. However, if you need to use the index of an element, then of course you should be allowed to use a for loop. But if you don't need to use an index, having one is just cluttering your code. There are no significant performance implications as far as I'm aware. At some stage in the future it might be easier to adapt code using foreach to run on multiple cores, but that's not something to worry about right now. In C#/VB.NET/.NET, which loop runs faster, for or foreach? Ever since I read that a for loop works faster than a foreach loop a long time ago I assumed it stood true for all collections, generic collections, all arrays, etc. I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended. What would be ideal is to have each scenario listed and the best solution for the same. For example (just an example of how it should be): - for iterating an array of 1000+ strings - foris better than foreach - for iterating over IList(non generic) strings - foreachis better than for A few references found on the web for the same: - Original grand old article by Emmanuel Schanzer - CodeProject FOREACH Vs. FOR - Blog - To foreachor not to foreach, that is the question - ASP.NET forum - NET 1.1 C# forvs foreach [Edit] Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter. Any time there's arguments over performance, you just need to write a small test so that you can use quantitative results to support your case. Use the StopWatch class and repeat something a few million times, for accuracy. (This might be hard without a for loop): using System.Diagnostics; //... Stopwatch sw = new Stopwatch() sw.Start() for(int i = 0; i < 1000000;i ++) { //do whatever it is you need to time } sw.Stop(); //print out sw.ElapsedMilliseconds Fingers crossed the results of this show that the difference is negligible, and you might as well just do whatever results in the most maintainable code There are very good reasons to prefer foreach loops over for loops. If you can use a foreach loop, your boss is right that you should. However, not every iteration is simply going through a list in order one by one. If he is forbidding for, yes that is wrong. If I were you, what I would do is turn all of your natural for loops into recursion. That'd teach him, and it's also a good mental exercise for you. "Are there any arguments I could use to help me convince him the for loop is acceptable to use?" No, if your boss is micromanaging to the level of telling you what programming language constructs to use, there's really nothing you can say. Sorry. Really screw with his head and go for an IQueryable .foreach closure instead: myList.ForEach(c => Console.WriteLine(c.ToString()); LOL Keep in mind that the for-loop and foreach-loop are not always equivalent. List enumerators will throw an exception if the list changes, but you won't always get that warning with a normal for loop. You might even get a different exception if the list changes at just the wrong time. This should save you: public IEnumerator<int> For(int start, int end, int step) { int n = start; while (n <= end) { yield n; n += step; } } Use: foreach (int n in For(1, 200, 4)) { Console.WriteLine(n); } For greater win, you may take three delegates as parameters. It is what you do inside the loop that affects perfomance, not the actual looping construct (assuming your case is non-trivial). In cases where you work with a collection of objects, foreach is better, but if you increment a number, a for loop is better. Note that in the last case, you could do something like: foreach (int i in Enumerable.Range(1,10))... But it certainly doesn't perform better, it actually has worse performance compared to a for. for has more simple logic to implement so it's faster than foreach. I did test it a while ago, with the result that a for loop is much faster than a foreach loop. The cause is simple, the foreach loop first needs to instantiate an IEnumerator for the collection. Jeffrey Richter talked the performance difference between for and foreach on a recent podcast: Every language construct has an appropriate time and place for usage. There is a reason the C# language has a four separate iteration statements - each is there for a specific purpose, and has an appropriate use. I recommend sitting down with your boss and trying to rationally explain why a for loop has a purpose. There are times when a for iteration block more clearly describes an algorithm than a foreach iteration. When this is true, it is appropriate to use them. I'd also point out to your boss - Performance is not, and should not be an issue in any practical way - it's more a matter of expression the algorithm in a succinct, meaningful, maintainable manner. Micro-optimizations like this miss the point of performance optimization completely, since any real performance benefit will come from algorithmic redesign and refactoring, not loop restructuring. If, after a rational discussion, there is still this authoritarian view, it is up to you as to how to proceed. Personally, I would not be happy working in an environment where rational thought is discouraged, and would consider moving to another position under a different employer. However, I strongly recommend discussion prior to getting upset - there may just be a simple misunderstanding in place. The two will run almost exactly the same way. Write some code to use both, then show him the IL. It should show comparable computations, meaning no difference in performance. My guess is that it will probably not be significant in 99% of the cases, so why would you choose the faster instead of the most appropriate (as in easiest to understand/maintain)?
http://code.i-harness.com/en/q/5942f
CC-MAIN-2018-47
refinedweb
1,126
61.56
Course Highlights and Why VMware Course in Chennai at FITA Academy? Upcoming Batches Classroom Training - Get trained by Industry Experts via Classroom Training at any of the FITA Academy branches near you - Why Wait? Jump Start your Career by taking the VMware Training in Chennai! Instructor-Led Live Online Training - Take-up Instructor-led Live Online Training. Get the Recorded Videos of each session. - Travelling is a Constraint? Jump Start your Career by taking the VMware Online Course! Syllabus - Introduction to Virtualization - Understanding Data Center Infrastructure - Installation of ESXi Server - Virtual Machine Concepts - Virtual Machine Creation & Management - Configuring and Managing Storage - Configuring Storage - VMFS Datastores - VSAN - Configuring and Managing Virtual Networks - Configuring Standard Virtual Switch Policies - Install & configure vCenter Server - VM Migration - VMware Clusters High Availability - Fault Tolerance - Host Scalability (DRS Cluster) - Patch Management - Data Protection - Veeam Backup - Access and Authentication Control - Resource Management and Monitoring - Scheduled Tasks, Events & Alarms - vSphere Web Client - VMware vShield Endpoint - Advanced Topics:Distributed Switch - VMware vCenter Standalone Converter - Up-gradation of Server - Managing vSphere Using command line interface - Understanding ESXi Server Architecture - Troubleshooting Virtual Interface Have Queries? Talk to our Career Counselor for more Guidance on picking the right Career for you! . Trainer Profile - At FITA, we zealously practice and implement the Experiential method of learning. VMware Mentors at FITA trains the students with the right blend of practical and theoretical knowledge of the Vmware concepts and techniques. - VMware Tutors at FITA trains the students with Industry-specific skill sets. - VMware Instructors at FITA Academy are Expertise and Certified professionals from the Cloud platform. - VMware Mentors at FITA Academy Institute are Real-time professionals from the Cloud domain and they provide hands-on training managing and deploying virtual machines and advanced techniques related to virtualization. - VMware Trainers at FITA Academy broadens the knowledge of the students on the virtualization concepts by training them extensively on the latest practices that are used in the VMware platform. - VMware Mentors at FITA Academy provide equal individual attention to all the students and they provide in-depth training of VMware concepts with complete hands-on training and practice. - VMware Instructors at FITA Academy supports and aids the students in building their resume professionally and enhances their confidence level by conducting numerous mock interview sessions and giving them a mammoth of insights on the handling of the interviews. Training in Chennai About VMware Certification Training in Chennai at FITA Academy VMware Certification Training in Chennai VMware Course Certification is one of the professional accomplishments which demonstrate that the candidate has acquired extensive knowledge of the significance of the virtualization concepts and its techniques. With a real-time project experience provided at the end of the VMWare course, this certification states that the candidate has obtained the necessary in-demand skills to work as a VMware professional. Having this VMware certificate along with your CV aids in boosting your profile at the time of the interview, and also it opens the gate for a wider range of career opportunities. VMware Certification Course in Chennai at FITA Academy imbibe the necessary technical skill sets that are required for professional Developers or Administrators under the guidance of our Real-time professionals.VMware training in Chennai at FITA Academy is provided by professionals who have 8+ years of experience in the VMware Cloud platform. Besides, earning the certificate of the FITA Academy’s VMware Training Course certification, earning a global credential also upsurges the possibilities of accessing lucrative careers. Our VMware Trainers at FITA Academy provides continued guidance and support to clear the global certification exam such as (VCA) – VMware Certified Associate, (VCP)VMware Certified Professional, (VACP) VMware Certified Advanced Professional, and (VCDX) VMware Certified Design Expert and helps you in uplifting your career opportunities. Have Queries? Talk to our Career Counselor for more Guidance on picking the right Career for you! . Job Opportunities After Completing VMware Training in Chennai The demand for IT professionals with Virtualization skills is currently sky-rocketing in the IT domain and it is predicted to have voluminous growth in the upcoming days as well. The prime reason for the increased growth is because of the number of organizations that are rapidly shifting their focus towards cloud and virtualization for cost-cutting, increased efficiency, and scalability of resources. When it comes to virtualization, VMware is the pioneer virtual cloud solution provider for enumerable businesses across the globe. VMware has occupied a prominent position in the marketplace of cloud computing and virtualization owing to its robust features. It can control various types of OS on a single server or computer laterally and therefore it resulted in the whittle down of the expenditure of the IT infrastructure drastically. Also, in the meanwhile ensuring the scalability, flexibility, and agility stupendously. This aided the businesses to be more profitable and agile along with the best security features for its customers. From the above-mentioned points, we can almost say that VMware has created a striking revolution in the IT industry. These are the major reasons on how VMware has managed to survive the competitive edge in the Cloud and virtualization platform. Furthermore, gaining a VMware certification helps you to access a myriad of career opportunities. The common job profiles that are offered upon the completion of the VMware certification exams are – System Engineers, Testers, System Administrators, Developers, Service Providers, and Network Operators. The notable recruiters of the VMware professionals are Cisco, IBM, HCl, TCS, and much more. The average salary offered for an entrant VMware System Administrator is Rs. 7,50,000 to Rs. 10,00,000 per annum. Globally, a VMware System Administrator earns around $ 98,945 yearly. VMware Training in Chennai at FITA Academy imbibes the in-demand professional and technical skills that are needed for a VMware professional under the mentorship of industry experts with certification. Student Testimonials VMware Training in Chennai at FITA Academy was conducted well. I liked their training methodologies. Well-structured VMware Course modules with hands-on training were provided at FITA Academy. Special mention about my VMware Mentor who thought all the concepts of the VMware in-depth. I will suggest the FITA Academy Training Institute for my friends. I am System Administrator by profession. I wanted to learn the VMware course to uplift my career opportunities at my office. I came to know about FITA Academy Training Institute upon the suggestion given by my friend and so I enrolled for the VMWare Course. I should tell you that everything was so very nice here. Best Training Faculty, Updated courseware most of all flexible timings. The Support Team was really so understanding that they ensured that I don't miss even a single session because of my work. If you are a working professional then you can really opt FITA Academy for any Training. Great Work FITA Academy. Keep it up. I am truly happy. My overall experience at FITA Academy's VMware Course in Chennai at FITA Academy was too good. My Trainers extensively thought about the concepts of vSphere, Virtual Machines, vSphere Storage, VMWare Cluster, and other important topics with live-time examples. Also, he was so patient enough to clarify all our doubts. My sincere thanks to him. Good work FITA Academy! I have completed my VMware Training at FITA Academy. Great place to learn about the VMware platform. Comprehensive training on how to configure and handle the vSphere 6.5 was provided. Learned a lot of new things regarding the virtualization concepts as well which I was not familiar with. Thanks to my VMware Trainer who helped me in building my resumes and also widened my knowledge with numerous mock interview practices. Any fresher with no doubts can choose this platform to learn VMware Course. Have Queries? Talk to our Career Counselor for more Guidance on picking the right Career for you! . VMware Training in Chennai Frequently Asked Question (FAQ) - VMware Course at FITA Academy is conducted and curated by Cloud Experts with more than 10+ years in VMware Course in Chennai at FITA Academy. - The Only Training Academy in Chennai that widens the knowledge of the students with the right proportion of theoretical and practical knowledge of the VMware concepts. - Above 30,000+ students trust FITA. - Comprehensive Coverage with 60+ hours of VMware Training in Chennai at FITA Academy. - Nominal Cost of IT working professionals and students in the mind. - Corporate Training in Chennai. - VMware Course timings are scheduled in the manner to suit the timing of the students and working professionals. - Resume Building Support and Interview Tips. - Real-time Virtualization projects and case studies. - FITA Academy has placements tie-ups with more than 1200+ small, medium, and large scale enterprises, and these companies have job openings for VMWare Developer, Administrator, and other professional roles that are related to the Cloud platform. - FITA Academy training institute has a Dedicated Placement Officer to support the students with Placement assistance. - The Placement cell helps the students with various mock interviews and group discussions training sessions for them to face the interview with confidence. You can enroll for the VMware Course in Chennai at FITA Academy VMware Course in Chennai at FITA Academy and will I be given enough practical Training for the VMware Certification Course? - We provide maximum individual attention to the students. The Training batch size is limited for 5 - 6 members per batch. The batch size has been optimized for equal individual attention to all the students and to clear the doubts of the students in complex topics clearly with tutors. - FITA Academy provides the necessary hands-on practical training to students with many Industry case studies and real-time projects. VMware Mentors at FITA Academy are Certified Cloud Experts from the Cloud Computing field. The VMware Trainers at FITA Academy are real-time professionals from the Cloud platform and they provide a holistic training of the virtualization concepts to the students. We accept Cash, Bank Transfer, G Pay, and Card Transactions. FITA Academy provides the best VMware Training in Chennai with wonderful guidance from expertise. Visit FITA Academy and enhance your career knowledge with best guidance. We have various branches in Chennai near by you Additional Information Looking for the best VMware Training Institute in Chennai? Then FITA Academy is the ideal choice for VMware Training in Chennai. Call +91 93450 45466 for VMware Course details. VMware Incorporation is an American based company that offers virtualization and cloud software and services. They offer compatible software products for x86 computers. VMware is a part of EMC Corporation and it’s located in Palo Alto, California. The VMware desktop version is compatible with. VM stands for virtual machines, it is widely installed on operating systems compatible with computers and servers that can host other operating systems, each operating system behaves smoothly as it was installed on an individual machine with its hardware configuration and software. FITA Academy offers the best VMware Training in Chennai by certified professionals as per industry standards. Benefits Of Taking VMware Training Chennai Virtualization is the most advanced technology that powers multiple operating systems in a single computer or server at the same time. It has revolutionized the IT industry and minimizes expenditure invested in IT infrastructure. Virtualization technology will increase flexibility, agility, and scalability while reducing expenditure. Workloads can be deployed quickly, the process becomes automated, and managing IT becomes simpler. As industries continue to use VMware technology, there is a massive demand for skilled and VMware certified professionals. Get trained in VMware Course in Chennai at FITA Academy to broaden your career horizon. Rated As Best VMware Training Institute In Chennai FITA Academy Chennai is a leading VMware Training Institute in Chennai with branches in Tambaram, OMR, Anna Nagar, Velachery, and T Nagar. Our experienced trainers will assist students to gain industry exposure with practical oriented training as per industry standards. Our VMware course syllabus is designed by certified professionals that cover beginner to advanced concepts. With our VMware course in Chennai, you can practically learn advanced concepts. Interested in our VMware Training in Chennai? Call 93450 45466 to have a chat with our experienced career counselor to know about VMware course duration, fee structure, and time. Join us for VMware Course in Chennai to start your dream career in IT. VMware Industry Updates VMware solutions run on the desktop software and the servers.VMware workstation pro is for the operating system or the demo session with the business. Virtualization is the base for cloud computing and the concept of virtualization is a part of cloud computing. The deliverables and networking are handled with a one-stop solution using the VMware solutions. Virtualization is about virtualizing the hardware of the company whereas cloud computing is about the serverless computing for maintaining the infrastructure of the business. VMware vCenter new server od, oc, ob, oa are the previous releases of the VMware. Join the VMware Training in Chennai to gain in-depth knowledge of this technology. The evolution of VMware brings in the different versions and it is essential to use the latest version of the VMware. If you desire to virtualize your computer then the virtual machine’s configurations are important to check. If your version is old and you are installing the latest version of VMware then the new features with the virtualization are not used to the fullest. The hardware versions are essential to be updated as this creates the connectivity between the virtual machine and the host server. VMware vCenter new server update The new options in the new version include the screening for the issues in the VMware, adds the models in the library service for the content, CLI tool, burst filter, HCI cluster feature, App defense V server plugin, compliance check, copy settings, and attach or detach of the files are some of the attributes to the latest version. The screening for the issues deals with the appropriate VMware articles for the knowledge which is easy to solve the issues when handling the new version. The embedded link mode in the vCenter controls the vCenter server appliances. CLI python tool The conversion of the server application to the platform services at an external location is taken care of by the CLI tool. The burst filter in the server prevents the flooding problem due to the identical events in the database for a limited period. The VMware V motion helps support the premises systems which work through on-line and VM ware cloud. The API or V sphere client or V sphere web client is used to using the V motion function. To make use of the new attributes in the VMware updates it is essential with the changes in the on-prem and vCenter system for the server and the new version of 6.7 from the center server. VMware Course in Chennai brings the knowledge and the industry specification into the course to make the students ready for the job. Library for the virtual appliance OVA is a library to maintain content in virtualization and these files are opened at the time of import by unzipping option. This content library is helpful in the deployment of the virtual machines with the library item. The instances in the vCenter help for the control of the reproducing the data with the other controller for the platforms from external sources instances. In the replication mode, the platform for the external services is controlled in all the topologies. The platform for external services is used to control the restored syncs and active peers. Application Management user interface The HCI provides the guided user experience for configuration. It automates the repetitive operations, uses embedded technology for the best practices, and distributes a wizard that is centralized to share the experience of the completed projects. To manage the settings for the firewall in the new version the Application management with the UI is used to edit and configure. The administration is managed from the shell administrator group and can access the vCenter server appliances using the administrator in the shell which is called bash shell. The active directory windows 2016 is supported in the vCenter server new version update. The dark theme and the color for the interface are handled with the color change scheme in the V sphere client display. Plug-in used in the new version The app defense vCenter server plugin in the VMware is the integrated one. The applications running with the help of the V sphere are provided with the app defense to gain multiple pros. App defense aids for the life cycle management, monitoring the behavior of the application with visibility, security calculations, and fixing the issues within the vCenter Server. The client of VSphere is used to check the host profile check regarding the compliance and this check happens during the interval or at a future process. VMware Course in Chennai outnumbers a good number of students every year to match the industry demand for the VMWare professionals. vCenter server is used to take from the host profiles the individual profiles or a group of sub-profiles and create profiles. The wizard with the copy setting helps for creating the profiles. The ESXi hosts along with the clusters are used to attach or detach the host profiles. The dialogue box is used by the cluster to attach or detach. The different patches of the VMware vCenter server new version are the full patch, security patch, product fixes of the third party, and these patches are updated with the version of the JRE. These patches are downloaded using the VMware patch download center. VMware Training in Chennai is the best training to enter into the networking profession. The information regarding the OS updates for the photon is derived from the appliances for the V center that is the photon OS which deals with the interface for appliance management is used to know more about the patching. VMware Course in Chennai is designed with a detailed syllabus and engaged by the expert professionals from the industry. The third-party customization and using builder for the image is known by seeing the installation of the ESXi and the documentation part is set up. The different types of issues are the overall issues, issues related to networking, issues related to security, installation issues, storage issues, issues due to updates, management issues because of virtualization, issues when using the tools, licensing issues, os issues from the guest, configuration problems from the server, issues related to internationalization and V sphere client issues of CIM, vSphere web client issues, vCenter server issues, and API issues are the wide range of issues that are covered in the new version. If the ESXi host is attached version 6.0 through the host profile and the host upgraded to the incremental version 6.7 then this will lead to miscellaneous error. This issue is resolved in this version. When performing the actions like taking out the elements from the host profile, the ESXi host has been changed to version 6.7, the error occurs, and even after the remediation the host appears to be without any complaint. If the filter is used during a system update and it no longer exists then it leads to the vpxd failure. Due to the race with thread, the vpxd service tends to fail. Unable to stage patches through a controller that controls the external sources. If the patches are staged, the update repository will use the patches and try to upstage and this will lead to the error like an error in invocation. After a data refresh, the grid for the old performance values is not retained and the values can be set in a sorting order for column values. The issue is not there in this new version. If the “SAN” field consists of extra details then the v Sphere certificate manager will not change one machine to the other machine. The extra details like the sites, common names, and IP addresses. vSphere manager issue The latest version is released with the fix to these concerns and the vSphere manager will check the name of the system name mentioned with the software. If the ESX host is sacked from the ESXi host then the vCenter server will stop responding to the Startups in the ESXI. The issue is changed with this release. This issue has been handled and fixed in this version. VMware Training in Chennai trains and helps the students to know their potential with real-time projects. The Syslog files grow exponentially and the rotation of the log may stop after the first round. Compression for the Syslog files also stops. The issue is fixed in the new version and enhanced with the postulated services. The LAG issue with the network is corrected with this version. If the group link aggregation is used to import the switch configuration for the Vsphere distribution then LAG information is not inserted in the server database from the vCenter. After restarting the vpxd service some LAGs are missing and the issue is solved in this new release. If the LAG is missing then reimport the v Sphere switch configuration distribution and manually create the LAG which is missing. The cloning of a template or the virtual machine deployment with template leads to VM static MAC conflict alarm and this concern is solved in the new release. VLAN settings provide incorrect health details to check shock with switch port groups along with NSX logical and this is solved in the latest version. The problems in the performance of the VXLAN are fixed in the new release and it uses the lower rates of sampling for the high performance. vCenter server application management The issues from the vCenter management interface for the server appliance lead to the HTTP error and this is solved in the latest release. This improves the label of the user interface and the Supported protocol is provided in the URL field of the server which is proxy. An updated version of the components Postgres in the previous version is now changed and the Procmail is also been changed. cURL with vCenter service appliance has been changed. The version of the Eclipse jetty has been changed. The validation of the XML which utilizes the –schema Validate flag is now disabled in the VMware OVF Tool. The version OpenSSL-1.0.2o is the updated version of the OpenSSL library in the latest release. The SQLite database has a new version. The version of libpng-1.6.34 is updated to the libPNG library. The third-party python library is used with the updated version in the new release. The Tomcat server in the Apache is used with the new change in the version. The libxml library is used with the new version which enhances the services. The updated version is called as a package from Apache belongs to version 3.4.0. The JRE package of the Oracle is updated with the new version. To correct the issues in CVE-1327 and CVE 2018-11776 apache struts is updated as 2.5.17. The glibc is now used with the 2.22-21 versions. Error due to unregistering of the API in the VSphere v Sphere and during the disconnected stage the event and manager for the alarm are not active which leads to error. The disconnected state and the awareness provider concerning the storage create the error. These storage concerns are fixed in the latest version. In the V sphere client, the unauthorized error is shown if the features are not available in the datastore level. It is difficult to use the ISO file using a data store if the features are not available. These types of concerns are fixed in the latest version. VMware Course in Chennai trains the students and prepares them for the interview with the mock interviews from the trainer. The CLI installer in the vCenter server appliance has been changed to the new version. Services from the second platform controller in the existing version might fail and services from the second platform controller with the eternal deployment also go with stage 2 in the existing v Center. The connectivity is upgraded in the latest version and the validation with SSO is updated. During making changes or during the installation the installer named GUI shows an error message. The new version is designed with no such errors and the failure of the first boot creates an error specific message. The DNS security extensions with DNS servers which are used to upgrade the v Center server appliance might fail in the vCenter server system. When resolving the hostname the system uses the RR set signature of the DNSSEC is used in the place of IP address. These issues are related to the upgrading and it is solved in the new version. The new version shows an error stating that the IP address already exists. If the shutdown of the source appliance fails in the 2nd stage of the upgrade of the V center because of a long time due to network issues. The error is due to the network settings in the newly deployed appliance with the target is not active. The issue is taken care of and fixed in the latest version. Different types of issues like the virtual machine management issues, deployment of replication appliance, handling OVF file, undeleted tasks handling and CLS task, OVF tool issues, Guest OS issues, issues related to licensing, internationalization issues, API issues, CMI issues, SNMP issues, VSAN issues, edit customization option with the client of the V Sphere, Paravirtual SCSI disk adapter issues, WebMKS console issues, ESXI issues and fault tolerance issues are resolved in the latest version to enhance the services to the wide range of followers. Management issues The ESX manager server in the vSphere shows an error due to the serialization and deserialization problems. When communicating with the agent manager ESXi the error is seen. These concerns with the v Sphere ESX agent is solved in the recent release. The vSphere replication carries an error message if the cluster does not have shared storage and the deployment fails due to the error. The OVF descriptor becomes invalid. The issue is solved after this release. This error and the problem with the deployment is solved in the latest version. OVF file The namespace and the specified prefix makes the OVF file to fail. The system handles the default namespace and the issue is solved in the latest version. The error in the cross-server migration with vCenter is fixed in the latest version. Dealing with the undeleted tasks When dealing with the undeleted tasks or new tasks in the vCenter server system the content library service will automatically clean the outstanding tasks which lead to the failure of the new tasks also. The issue is settled in the latest version of VMware. A separate library is created by the content library service called SMB share and if it fails then it takes the storage space in the server system of the v Center. The issue with the storage does not disturb the NFS mounts. VMware consists of articles with a knowledge base that also help in solving these issues. Issues with OVF tools When the template is used to deploy the ISO file in the v Center Server or to the ESXIi host the failure happens because the tool finds it difficult to read the content in the ISO file. The issues in the old are changed in the new release. Import operations The import operations in the VMware workstation or fusion in the VMware is done with the help of the paravirtual SCSI in the VMware disk adapter and this may face failure with an error message. This problem is fixed in the latest release of VMware. The card adapters with sound are used for import and export which also ends with error message and failure. The issue is corrected in the latest version. The deployment of a virtual machine with the help of the OVF tool in the VCloud director ends up with failure and vCloud director API versions are the right one to deploy the virtual machines with the latest version. This problem is handled and corrected in the latest version. VMware Course in Chennai is the best course for the students with an interest towards virtualization. When doing the Linux customization the IPV6 loopback is deleted and this problem of deleting the IPV6 entries is taken care of in the latest version. OS issues with virtual machine If RHEL is used for the customization of IP for a test recovery then the host file is empty on the place where it is recovered. The issues in the old are changed in the new release. Issues with licensing The VM ware authority certificate is automatically given to the ESXi hosts who have custom certification. The issue is solved and the vCenter server essential plus gives license capacity for the host to the wireless virtual machine. For the AvSAN 2-cluster host one witness and two hosts are required. The vCenter server takes the witness appliance like a host and because of this the witness also resides in the virtual machine. So, the witness also gets a license for hosting and the issue is fixed in the latest version. Issues with the internationalization The non-ASCII characters in the content library show failure and this will not sync. If it is Chinese or Japanese in the library then it will fail due to the multi-byte in non-ASCII characters. These synchronization issues are solved in the latest release. Join the VMware Training in Chennai and become a follower of the advancement in the VM ware. Issues with the configuration If the SSL protection is active then it is not possible to create an active directory with LDAP source for identification. The error message is shown if the SSL protection is connected to the controller used for the domain. The issues in the old are changed in the new release.
https://www.fita.in/vmware-training-in-chennai/
CC-MAIN-2022-05
refinedweb
5,006
52.8
On Thu, Feb 21, 2013 at 6:57 AM, Ken Giusti <kgiu...@redhat.com> wrote: Advertising > make still fails on Centos-5 due to swig parse error. See > > > I've tried Rafi's suggestion - we could simply ifdef-out the definition > when the header is processed by swig: > > #ifndef SWIG // older versions of SWIG choke on this: > static inline pn_delivery_tag_t pn_dtag(const char *bytes, size_t size) { > pn_delivery_tag_t dtag = {size, bytes}; > return dtag; > } > #endif > > > This seems to work - at least the build completes and all python unit > tests pass. > > Given that this is a inline function, I don't think swig is going to > wrap/export it anyways, right? > > Not that I'm comfortable with the whole "static functions exported via API > headers" thing - seems like a recipe for disaster, ABI-wise. > Yeah, I don't think we need swig to see this. I'd say go with this for 0.4 and let's work on a better API for 0.5. --Rafael
https://www.mail-archive.com/proton@qpid.apache.org/msg01939.html
CC-MAIN-2018-05
refinedweb
163
78.28
separating lab image into 3 components Hello Everyone, I want to dividide a BGR image into 3 images containing the 3 different CIE Lab color components (with just one channel). I know that I can do something like this: #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main( int argc, char** argv ) { Mat src = imread( "/home/diego/Documents/sunset.jpg", -1 ), lab; cvtColor(src, lab, CV_BGR2Lab); imshow("lab", lab); return 0; } And this gives me a kind of result like this However I read something that tells me that I need to treat the Luminance between 0 and 100, and a,b with values between -127 to 127 (So I don't know if this image is right or wrong). I would like to ask what is meant with these values... are these ones the pixel values, are these ones normalized values from the original 0 to 255? Are the values of this 3 channel image representing L((lab[0]), A(lab[1]), and B(lab[2])? I have checked in several webpages to give me an idea but I just see very theoretical information about how the 3 axis Lab color space is composed but nothing that I can convert into real things. Thanks and sorry for so many questions. Hi, and thanks. I already did it. and solved it with split as you said... Actually it was pretty easy. I didn't have to cope with all of those questions cause OpenCV did the job for me.
https://answers.opencv.org/question/64108/separating-lab-image-into-3-components/
CC-MAIN-2021-25
refinedweb
252
71.34
I’ve already read a lot of articles about how Flutter compares to other mobile development frameworks, but most of them were written from a theoretical point of view. It’s already been well established that Flutter is a solid choice for creating mobile applications and that it’s a worthy opponent to frameworks like React Native and Xamarin Forms. Everyone agrees that Flutter looks good on paper, but how can companies who still doubt Flutter be convinced that they should at least consider using it? Theories and opinions are one thing, but what we really need more of is proof of Flutter’s capabilities and performance. This year I graduated in Applied Computer Science at University College Ghent in Belgium. During my last year I was given the opportunity to write a thesis around a topic of my choice. I decided to write my thesis around Flutter because I hoped it would be one of the first of its kind. In the first section I discussed how Flutter works, what Dart is and why it’s ideal for Flutter and I also discussed a couple of state management techniques. In the second section I performed two experiments. During the first experiment I created the same app five times, each time with a different framework. The frameworks I used were native Android, native iOS, Flutter, Xamarin Forms and React Native. During the second experiment I measured the CPU usage of the apps I created in the first experiment. In this article I will share the results of these experiments. Creating the same application five times I’m going to be honest with you, this first experiment wasn’t really fair. I don’t have the same amount of experience with every framework I used. If I were to make a ranking of the amount of experience I had with each framework from highest to lowest, it would probably look like this: - Android - Flutter - Xamarin Forms - iOS - React Native I do however want to point out that I had already created mock-ups of the application so I wouldn’t have to mess around with thinking about the UI during the development of the first app. I also knew enough about every framework to create the application without Googling a lot, so there wasn’t much of a learning curve. The name of the application I created is Cocktailr. As the name indicates, this app is for cocktail lovers who want to discover new cocktails and also search for cocktails they can make with ingredients they have or want to use.The application exists out of four screens: a cocktail list screen, a cocktail detail screen, an ingredient list screen and a cocktail creation screen. The images underneath are the mock-ups I created before developing the applications. I don’t think I have to show you the screens of the five apps I created because, spoiler alert, they all look nearly identical to the mock-ups (apart from some minor inconsistencies which I’ll discuss later). Instead, I’m going to discuss what it was like to develop the app with each framework and also point out some of the difficulties I encountered. I’m also going to compare the amount of time it took to create the apps per framework. Creating the native Android application To create the native Android application I used Android Studio as IDE and Kotlin as programming language. The 3rd party packages I relied on were Glide for fetching network images, Retrofit for consuming HTTP requests and GSON to convert JSON objects into POJOs (Plain Old Java Objects). I also used something called the Navigation Component, which is a part of Android Jetpack, a suite of libraries, tools, and guidance to help developers write high-quality apps easier. It was still in alpha at the time, but I loved it and I felt comfortable using it. To create layouts on Android you can either use a visual layout builder or you can create it in XML. Usually you’ll work with both to get the best of both worlds. The main problem I had (and still have) with Android development is that there are too many ways to accomplish a certain task. If you were to Google how to make network requests on Android you would discover all kinds of different packages and documentation. That’s why the Android developers at Google are currently working on Android Jetpack, the set of tools I mentioned earlier. This will make finding the right tools to solve your problems more straightforward. Since both Java and Kotlin are supported for Android development, you’re sometimes going to find code samples or tutorials written in the language you’re not using. Android Studio does have support for turning Java code into Kotlin code but the ‘translation’ isn’t always 100% accurate. Another difficult problem is that it can be quite hard to add elements to your layout dynamically (Jetpack Compose, which allows you to create layouts declaratively like with Dart, wasn’t around when I created this project). On the cocktail detail screen I wanted to add a table with the names of the ingredients of the cocktail and also a measurement per ingredient. I found it quite difficult to add rows to a table programmatically. There isn’t a lot of information about it in the official Android documentation, so when you have a problem like this you’re probably going to have to look for a solution on websites like StackOverflow. I was eventually able to add the rows programmatically but the solution was, in my opinion, quite cumbersome. The Kotlin code underneath is the function I wrote to create table rows programmatically. private fun createTableRows() { tl_cocktail_detail_ingredients.removeAllViews() val params = TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1f) val tv1 = TextView(this.context) tv1.text = "INGREDIENT" tv1.background = ContextCompat.getDrawable(context!!, R.drawable.grid_border) tv1.setPadding(6, 6, 6, 6) tv1.layoutParams = params tv1.gravity = Gravity.CENTER tv1.setTextColor(ContextCompat.getColor(this.context!!, R.color.black)) tv1.typeface = Typeface.DEFAULT_BOLD val tv2 = TextView(this.context) tv2.text = "AMOUNT" tv2.setPadding(6, 6, 6, 6) tv2.layoutParams = params tv2.gravity = Gravity.CENTER tv2.setTextColor(ContextCompat.getColor(this.context!!, R.color.black)) tv2.typeface = Typeface.DEFAULT_BOLD val tr = TableRow(this.context) tr.background = ContextCompat.getDrawable(context!!, R.drawable.grid_border) tr.addView(tv1) tr.addView(tv2) tl_cocktail_detail_ingredients.addView(tr) if (!cocktail?.ingredients.isNullOrEmpty() && !cocktail?.measurements.isNullOrEmpty()) { cocktail!!.ingredients.forEachIndexed { index, ingredient -> val tv1 = TextView(this.context) tv1.text = ingredient tv1.background = ContextCompat.getDrawable(context!!, R.drawable.grid_border) tv1.setPadding(32, 6, 6, 6) tv1.layoutParams = params val tv2 = TextView(this.context) if (index >= cocktail!!.measurements.count()) { tv2.text = "" } else { tv2.text = cocktail!!.measurements[index] } tv2.setPadding(32, 6, 6, 6) tv2.layoutParams = params val tr = TableRow(this.context) tr.background = ContextCompat.getDrawable(context!!, R.drawable.grid_border) tr.addView(tv1) tr.addView(tv2) tl_cocktail_detail_ingredients.addView(tr) } } } Something that isn’t really an issue but I also find quite cumbersome is how certain styling has to be done. Let’s say you want to create a text field with a border around it. To accomplish this, you’ll have to add the text field to the layout of your screen but you’ll also have to create a separate XML file to define the border. Then, you need to set that separate file as the background of the text field. It isn’t difficult at all, it just feels like a lot of work for such a simple task. The XML code underneath is set as background of the textfield to create a border around it. <?xml version="1.0" encoding="utf-8"?> <shape xmlns: <solid android: <corners android: <stroke android: </shape> Creating the native iOS application To create the native iOS application I used Xcode as IDE and Swift as programming language. No 3rd party packages were used. I based my way of working on the book “App Development with Swift”, which is an official book by Apple. Even though I’m an Android developer at heart, I must say it’s a lot easier to find the best way to tackle a certain problem. There are for example less ways to add functionality like consuming HTTP requests, which makes it easier to find the solution that fits best for the needs of your project. Something that I had to figure out that wasn’t described in the book was how to subscribe to changes happening in the cocktail repository, the class were all cocktail objects are stored. I didn’t want to refetch all cocktails every time the cocktail list screen was opened. To solve this problem I used something called the NotificationCenter. Thanks to the book I mentioned earlier I hardly had to google anything. In fact, the article I found on NotificationCenter was the only source of information I used apart from the book. I was lucky that the article had an example on how to use it in Swift, but during the development of other applications I encountered the same issue I had on Android. Older articles or StackOverflow answers might have solutions provided in Objective-C, the language used for iOS development before Swift was introduced. Even though I didn’t have this issue during the development of the native iOS application for Cocktailr, I thought it was worth mentioning that it exists. My main issue with iOS development is that a Storyboard, the visual layout builder for iOS apps, can be more complex than necessary. For example, finding a setting to add a border around a text field can be very difficult. Luckily, it’s a lot easier to do this programmatically than it is in Android. SwiftUI, a way to create layouts declaratively with Swift, wasn’t around when I created this app by the way. It’s also possible to make changes to your layout in the XML file of a Storyboard, but unlike Android, the XML is a mess. The XML code underneath is the cocktail list screen, which actually only contains a list when you think about it. <scene sceneID="aud-0C-1Pk"> <objects> <tableViewController id="3Sf-E8-Zfo" customClass="CocktailTableViewController" customModule="Cocktailr_iOS" customModuleProvider="target" sceneMemberID="viewController"> <tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="9Np-nI-tQC"> <rect key="frame" x="0.0" y="0.0" width="414" height="896"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/> <prototypes> <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="CocktailCell" id="qUV-tm-57K" customClass="CocktailTableViewCell" customModule="Cocktailr_iOS" customModuleProvider="target"> <rect key="frame" x="0.0" y="28" width="414" height="44"/> <autoresizingMask key="autoresizingMask"/> <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="qUV-tm-57K" id="4Hj-H9-rtF"> <rect key="frame" x="0.0" y="0.0" width="414" height="43.5"/> <autoresizingMask key="autoresizingMask"/> </tableViewCellContentView> <connections> <segue destination="IYp-bk-shv" kind="show" identifier="CocktailDetailSegue" id="bjc-Sd-8ni"/> </connections> </tableViewCell> </prototypes> <connections> <outlet property="dataSource" destination="3Sf-E8-Zfo" id="Arh-Wp-anV"/> <outlet property="delegate" destination="3Sf-E8-Zfo" id="qJE-tE-xa7"/> </connections> </tableView> <navigationItem key="navigationItem" title="Cocktailr" id="0Li-fu-c3B"> <barButtonItem key="backBarButtonItem" title=" " id="4vq-K8-peJ"/> <barButtonItem key="rightBarButtonItem" title="Search" image="Search Icon" id="fCh-D0-Tws"> <connections> <action selector="searchBarButtonClick:" destination="3Sf-E8-Zfo" id="0Pk-I0-Hsb"/> </connections> </barButtonItem> </navigationItem> <connections> <segue destination="UPM-k4-dYF" kind="show" identifier="SearchTableViewSegue" id="e9G-mk-bUI"/> </connections> </tableViewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkZ-bW-bEE" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="886" y="-457"/> </scene> I encountered a problem during the creation of the cocktail list page. The list, or TableView as it’s called on iOS, exists out of custom cells. Each cell contains the information of one cocktail: an image, its name and its ID. When you scroll through the list of cocktails you’ll see that all of a sudden the cocktail names don’t match with the images anymore. This happens because the cells of the list are reused when you scroll through the list and it takes a bit longer to load an image than it does to load text. Some iOS developers have told me this is an issue all junior iOS developers encounter and that it’s quite easy to fix. I thought it was still worth mentioning, as I didn’t have a similar problem with any of the other frameworks. I also had to use a TableView to create the table on the cocktail detail page, as there isn’t an iOS component to create tables. The name ‘TableView’ can be quite misleading. Creating the Flutter application To create the Flutter application I used Visual Studio Code as IDE and Dart as programming language. The 3rd party packages I relied on were Image_picker for taking photos, Http for consuming HTTP requests and RxDart to use Observables for data streams. I used the BLoC state management technique for this application, but I didn’t use the 3rd party package. I found all of the information I needed to create this application in the official Flutter docs and in articles about BLoC written by Didier Boelens. Flutter doesn’t have a visual layout builder. You also don’t need an additional language like XML to create your layout. You use Dart to create widgets which together will form your layouts, and you build these layouts declaratively. The biggest problem I faced during the development of this application was state management. I didn’t have a lot of experience with BLoC at the time and the Provider package wasn’t around when I created this application. BLoC is, in my opinion and as regularly stated by Google, the superior state management technique. It has a huge learning curve to it though. I didn’t have any experience with Redux or Scoped_Model either, and only using setState() wasn’t going to suffice, so I had to resort to BLoC. Flutter provides its own widgets, and it has a lot of them! One of them is a Table widget, which made it really easy to create the table on the cocktail detail page. I had problems creating this table with both Android and iOS, so this was a nice change of pace. The code underneath is the function to create all the table rows. List<TableRow> _createTable(Cocktail cocktail) { List<TableRow> tableList = []; tableList.add( TableRow( children: [ Padding( child: Text( "INGREDIENT", textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.bold), ), padding: EdgeInsets.all(4), ), Padding( child: Text( "MEASUREMENT", textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.bold), ), padding: EdgeInsets.all(4), ) ], ), ); for (int i = 0; i < cocktail.ingredients.length; i++) { tableList.add( TableRow( children: [ Padding( child: Text(cocktail.ingredients[i]), padding: EdgeInsets.all(4), ), Padding( child: Text(i < cocktail.measurements.length ? cocktail.measurements[i] : ''), padding: EdgeInsets.all(4), ) ], ), ); } return tableList; } The only other ‘issue’ I encountered is that the iOS app doesn’t have a native look-and-feel. I used the Material widgets to create the application. Native Android apps implement Material design, but native iOS apps implement Cupertino design instead. A lot of widgets do look native on both platforms though, like the List widget for example. Other widgets like the AppBar widget don’t. Some widgets like the Switch widget have an adaptive constructor, which allows you to create a switch that look native on both platforms. It’s possible to create separate widgets for Android and iOS for widgets without an adaptive constructor, but unfortunately that costs more time. Creating the React Native application To create the React Native application I used Visual Studio Code as IDE and TypeScript as programming language. I relied on a lot of 3rd party packages to create this application: - Expo to make the development of the application easier and because it has picture taking support built-in. - React-native-easy-toasts for showing a toast on the cocktail creation screen. - React-native-elements because it has a lot of beautiful UI components. - React-native-svg-transformer to be able to use SVG icons. - React-navigation for the navigation of the app. - Styled-components to make it easier to style components. React Native doesn’t have a visual layout builder. You use a language called JSX to create your layouts declaratively. Managing state was one of the biggest challenges I encountered during the creation of this application. I didn’t know Redux, and learning it would have been a big time investment. This was not the fault of React Native, it was my own fault. The only styling issue I encountered was during the creation of the cards used in the list of the cocktail list screen. To create shadows on this card for Android I had to use the ‘elevation’ property. To have the same effect on iOS I had to use the ’shadow-color’, ’shadow-radius’, ’shadow-opacity’ and ’shadow-offset’ properties. Having to do styling in two different ways to have the same result on both Android and iOS isn’t really great when your goal is to make a cross-platform app. The code underneath shows the style I created for iOS and the elevation property I used for Android. It also shows the CocktailCard as a whole, written in JSX. const styles = StyleSheet.create({ cardWrapper: { shadowColor: '#000000', shadowOffset: { width: 0, height: 3, }, shadowRadius: 2, shadowOpacity: 0.3, }, }) export default class CocktailCard extends React.PureComponent { render() { const { id, image, name, onPress } = this.props return ( <CocktailCardWrapper elevation={5} style={styles.cardWrapper} onPress={onPress}> <CocktailImage source={{ uri: image }} /> <CocktailText> <CocktailName>{name}</CocktailName> <CocktailId>{`ID: ${id}`}</CocktailId> </CocktailText> </CocktailCardWrapper> ) } } The Android and iOS app created with React Native did have a native look-and-feel. That’s because React Native uses widgets of the platform it’s running on instead of providing its own widgets like Flutter does. Both Flutter and React Native support Stateful Hot Reload, but I have to say that it’s faster on Flutter than on React Native. On React Native it took longer to reload the app and sometimes it wouldn’t even work at all. The fact that it took longer might have something to do with the use of Expo. Creating the Xamarin Forms application To create the Xamarin Forms application I used Visual Studio for Mac as IDE and C# as programming language. The only 3rd party packages I relied on was Xam.Plugin.Media for taking pictures. Xamarin Forms has a visual layout builder, but it isn’t as good as the ones you use for native Android and native iOS development. You’ll do most of the layout building with the XAML language, which is very similar to XML. When I created this application, Xamarin Forms didn’t support Hot Reload. At the time of writing this article it’s either in beta or already supported. I don’t know how well it performs in comparison to the Hot Reload of Flutter and React Native though. Xamarin Forms is a cross-platform framework but when it comes to styling it doesn’t seem to be as straightforward as Flutter or React Native. I wanted to change the colour of the app bar to red. Apparently this isn’t a change you can make in the shared codebase, you need to change the colour of the app bar on Android and iOS separately. This is also the case for the colour of the selected item in the bottom navigation bar. Because you have to do the same styling twice, you might end up with inconsistencies between your Android and iOS applications if you’re not careful. Now that we’re on the topic of colours, I was unable to change the colour of the search icon in the app bar on the cocktail list screen and the camera icon of the cocktail detail screen. There is probably a way to change these colours, but it’s not straightforward at all. The images underneath illustrate the colour inconsistencies between Android and iOS. The biggest issue I encountered was, again, the table on the cocktail detail screen. The styling of the table wasn’t the issue though. I have to iterate over the list of ingredients and the list of measurements, but iterating over two lists isn’t possible to create your layout. I had to create a new model which contains the ingredient and its measurement. Then I was able to iterate over a list of those objects. This is the only framework where I had to change the models in such a way and it’s very cumbersome. Conclusion of the first experiment The table below shows how much time it took to create every screen per framework. As you can see, I was able to build the Flutter application and the React Native application faster than either one of the native applications. You also have to keep in mind that because these are both cross-platform frameworks I was able to make an Android and iOS application in less time than one native application. Creating the Flutter application only took approximately ⅓ of the time it took to create both native applications combined. This proves how much time you save by using cross-platform frameworks. Their Hot Reload functionality also sped up the development cycle a lot. Both the Flutter and the React Native applications look nearly identical to the mock-ups. The Xamarin Forms application has some minor yet visible differences. I was able to create the Flutter app faster than the React Native app, but that’s because I had more experience with Flutter than with React Native. I also didn’t know how to manage state properly in the React Native. That’s why declare both Flutter and React Native the winners of this experiment. Measuring the performance of the Android applications This experiment will determine the performance of the Android applications created during the first experiment. To conduct this experiment, I used the Android Profiler, a tool built into Android Studio. This tool allows you to collect data about CPU-usage, network activity and memory/battery consumption. I chose to focus on the CPU-usage as performance indicator for this experiment. It’s best to use a physical device for this experiment. I used the smartphone the smartphone I owned at the time, a OnePlus 6T with the following specifications: - Operating System: Android 9.0 (Pie); OxygenOS 9.0.13 - Chipset: Qualcomm SDM845 Snapdragon 845 (10nm) - CPU: Octa-core (4x2.8 GHz Kryo 385 Gold & 4x1.7 GHz Kryo 385 Silver) - GPU: Adreno 630 - Memory: 8 GB RAM - Storage: 128 GB ROM How the experiment was conducted When conducting this experiment, a certain route was followed in every application and in the meantime the Android Profiler kept track of the CPU-usage. This tool then generated graphs to visualise the data it gathered. These steps were followed in every application: - Open the app and wait until the cocktails are loaded in - Start measuring the CPU-usage - Scroll down to the bottom of the list of cocktails - Scroll back up to the first cocktail in the list - Click the first cocktail in the list - Return to the list of cocktails - Open the list of ingredients - Scroll down to the bottom of the list of ingredients - Enter ‘Gin’ into the search field - Click on the ‘Gin’ ingredient. (This brings you back to the cocktail list screen.) - Scroll down to the bottom of the list of cocktails again - Scroll back up to the first cocktail in the list again - Click the first cocktail in the list - Return to the list of cocktails - Click on the ‘suggestion’ button in the bottom navigation bar - Write the word ‘description’ as description - Click on the camera button, grant permissions and take a picture - Tap the ‘Make suggestion’ button Preparations for the experiment I was able to install the native Android application correctly on my device using Android Studio, which was very easy. Correctly installing the other applications wasn’t as straightforward. To install the Flutter application for example, I had to use the command flutter run — profile. I wasn’t able to use a debug build because the Flutter application would have been compiled JIT (Just In Time, used for debugging) instead of AOT (Ahead Of Time, used for release and profile builds). This would have tempered the performance of the application. In the Xamarin Forms project I enabled ‘Enable developer instrumentation (debugging and profiling)’ before installing the application. To install the React Native application I first had to start Expo and then enable profiling and install the application. Results of the experiment The graphs underneath were generated by the Android Profiler. The green waves represent the CPU-usage of the application. The dark blue waves represent the CPU-usage of other processes. The vertical lines represent the moments in time where started and stopped measuring the CPU-usage. Take a moment to look back at the steps I followed in every application to notice that certain actions were more CPU-intensive than others. The spike you see near the beginning of every graph is when I started scrolling in the list of cocktails. The spike near the middle of the graph is when I started scrolling in the list of cocktails again, but this time all cocktails with gin as ingredient were shown. That list has more cocktails in it than the original one. CPU-usage of the native Android application: CPU-usage of the Flutter application: CPU-usage of the React Native application: CPU-usage of the Xamarin Forms application: Conclusion of the second experiment The table below contains statistics based on the data off the graphs that were generated by the Android Profiler. The first thing that stood out to me is that every application has a minimum CPU-usage of 0%. This happened when I opened the cocktail creation screen. At that time, the application is in a static state, causing the CPU temporarily unused. The second thing that stood out to me is that the 4 apps can be split into 2 groups. The CPU-usage of the Flutter application peers with the CPU-usage of the native Android application, while the CPU-usage of the React Native application matches the CPU-usage of the Xamarin Forms application. Before conducting this experiment, I had anticipated that the native Android application would have been the most performant one and the apps of the cross-platform frameworks would follow. For the most part this is true, but the Flutter application is an exception to this. The Flutter application was even slightly more economical on the CPU. When I was conducting the experiment it was already noticeable to me that the Xamarin Forms and the React Native application struggled when I scrolled through the list of cocktails. I think this is because of all of the cocktail images that needed to be downloaded. The Xamarin Forms application also struggled a bit when I was scrolling down the list of ingredients, which only had text and no images. It’s obvious that the CPU-usage of the Flutter application is smaller than that of the React Native and Xamarin Forms applications, and that’s why I declare Flutter the winner of this experiment. Is Flutter more performant than React Native and Xamarin Forms? In the second experiment it was concluded that the Flutter application was less taxing on the CPU than the React Native and Xamarin Forms applications. This doesn’t automatically prove that Flutter is more performant than React Native or Xamarin Forms. There are a lot of features that the Cocktailr app doesn’t have, like caching for example. That would reduce the amount of network requests that need to be made and would make the app more performant, meaning that it could lead to different results. I also only used CPU-usage as a performance indicator. I don’t have any data on the memory or battery consumption for example. These are also an important performance indicators. I didn’t know beforehand what the results of this experiment were going to be. All I hoped to prove is that Flutter can stands its ground against other cross-platform frameworks, and I think I achieved that goal. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/inthepocket/flutter-versus-other-mobile-development-frameworks-a-ui-and-performance-experiment-3el
CC-MAIN-2021-25
refinedweb
4,750
53.71
view raw I asked a related question yesterday and fortunately got my answer from jlarsch quickly. But now I am stuck with the next part, which starts with the h=area() line. I'd like to know the python version of the area() function, via which I will be able to set the colors. Could someone shed me some light again? Thanks much in advance. ... Subplot (2,1,1); H = plot (rand(100,5)); C = get (H, 'Color') H = area (myX, myY); H(1).FaceColor = C(1); H(2).FaceColor = C(2); Grid on; ... The pretty much exact equivalent of MATLAB's Area plot is matplotlib's stackplot. Here is the first MATLAB example from the above link reproduced using matplotlib: import matplotlib.pyplot as plt import numpy as np x = np.arange(4) y = [[1, 3, 1, 2], [5, 2, 5, 6], [3, 7, 3, 1]] plt.stackplot(x, y) plt.show() And here is the result:
https://codedump.io/share/etwmVxu2e3Sp/1/python-version-of-harea-in-matlab
CC-MAIN-2017-22
refinedweb
158
86.81
How do I pass url parameters to chrome headless? Simply, this works fine. chrome --headless --dump-dom test.html However, this does not work. chrome --headless --dump-dom test.html?data=test test.html <!DOCTYPE html> <html> <body> <p>something</p> </body> </html>? - Remove transition and delay of Bootstrap 4 Collapse element I want to remove the transition and the delay of the Bootstrap 4 Collapse element. I'm using CSS to remove the transition itself: .collapsing { -webkit-transition: none; transition: none; display: none; } #collapseExample {background: red;} That part works fine. But there is still some delay before the Collapse element shows. Is there any way to remove that? Here's the HTML: Navbar > <form class="form-inline my-2 my-lg-0"> <button class="btn btn-primary" type="button" data- Button with data-target </button> </form> </div> </nav> <div class="collapse" id="collapseExample"> <div class="container">. </div> </div> - How to highlight every other row with %? How do I highlight (i.e. change the background color) every other row with %in JavaScript? I was thinking about if (i % 2 == 0). Does this work? // declaring variables var rows = 12; var cols = 3; document.write('<table border=2>'); for (var k = 0; k < head.length; k++) { // input the heading of the table document.write('<th>' + head[k] + '</th>'); } for (var i = 0; i < rows; i++) { document.write('<tr>' + 0 + '</tr>'); if (i % 2 == 0) { // don't know what to put in here } else { } for (var j = 0; j < cols; j++) { document.write('<td>' + Table[i][j] + '</td>'); } } document.write('</table>'); - Document.execCommand not updating currently active element I have a pre tag which encloses an input tag. There is a paste event listener tied to the pre tag. $(function() { if (document.querySelector('pre[contenteditable="true"]') != null) { document.querySelector('pre[contenteditable="true"]').addEventListener("paste", function(e) { e.preventDefault(); //alert("test"); var text = e.clipboardData.getData("text/plain"); document.execCommand("insertHtml", false, text); }); } }); <script src=""></script> <pre id="previewEmailBody" class="blurbBody" placeholder="Reply" style="display:block" contenteditable="true">Testing <input class="emailBodyToken" name="[Test]" size="54" value="[Test]" > Testing</pre> Now - if I click on input element and do text paste - it is not updating the input element instead it is updating the text in the pre element. The above behavior was observed only in firefox. In chrome, it updates the input element as expected. I want the same behavior in firefox as well. Do suggest a way around this. Working example: - AJAX CalendarExtender Not working in Google chrome Version 66 AJAX CalendarExtender Not working in Google chrome Version 66 but working fine in Mozilla Firefox and IE10.... Here is my code - How to click on print or save button of print window in chrome browser using webdriverio? How to save a print using a print button of a print window in chrome browser? webdriverio version: 4.9.11 - Chrome app upload fail I modified some image files and ' manifast ' files, then removed the " app " value and uploaded it incorrectly So I put in the " app " value back and tried to upload it again. But I am getting the below error. ErrrorMessage : An error occurred: Failed to process your item. This item is not an app, please remove app section from manifest. Please tell me how to go back to the previous version or fix the problem. - Replace words/phrases in existing PDF or docx with other words I am trying to make a dynamic PDF generator as an .NET Core API. I want to take an existing PDF, or .docx file, and edit it so it replaces the current name (John Doe) with something that can be replaced like #NAME_PLACEHOLDER. I then want to transform #NAME_PLACEHOLDER -> John Doe(or whatever is in the KeyValuePairor Dictionary<string, string>). I am running this on a Docker environment, so I can easily execute commands and I am willing to do that as well. So far I have tried a few things: - 1) pdf2htmlEX - Executes as pdf2htmlEX file.pdf - Does the job pretty well - Can be converted back to PDF using Google Chrome headless or similar - Problem: Only the characters used in the PDF can be used to replace. So if I only use A, B, Cas characters, it will make Dinto Times New Roman (or default font) - 2) LibreOffice ODT to PDF - This was pretty nice, because I could simply unzip the .odt file, open content.xml, search and replace, then save it as an .odt file again - Could be converted into PDF rather easily using soffice --convert-to pdf - LibreOffice is quite nice - Problem 1: Microsoft Word -> Save as ODT tends to break the formatting, so we have to use LibreOffice to go and change it back again - Problem 2: We don't want to move away from Microsoft's Office suite - 3) HTML to PDF using Chrome Headless - What you see is what you get - By far the best option, if we're all developers aaand have unlimited time - Problem 1: Only our developers can make changes, since our marketing department do not know HTML - Problem 2: Our existing PDFs would have to be rewritten in HTML As you can see, I have tried a bunch of things. None of them, except Chrome Headless, has lived up to my expectations. What I really like about #3 is what you see is what you get. I can make the whole thing in HTML, press CTRL+P and see what it looks like as a finished PDF, basically. I am looking for a better solution, though. It can be paid. It can be free. All I need is to change out words/phrases with other words dynamically, which apparently seems like a tough thing to do. - Unable to download any file using selenium I want to download a file using selenium.Since phantom js and chrome headless doesnot supoort downloading so i tried the below thing.But the issue when i use this code in normal chrome it is saying path too long and not downloading the file.How can i achieve downloading the file both in chrome and headlesss import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import com.fasterxml.jackson.databind.ObjectMapper; public class Downjar { public static void main(String[] args) throws ClientProtocolException, IOException { System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver"); ChromeOptions options = new ChromeOptions(); options.addArguments("--test-type"); //options.addArguments("--headless"); options.addArguments("--disable-extensions"); //to disable browser extension popup", "C://Users//poltu//Downloads//");); driver.get(""); driver.findElement(By.xpath("html/body/div/div/div[2]/p[2]/a")).click(); } } - Not able to capture image while generating pdf using puppeteer API Node- v8.11.1 Headless Chrome Im trying to generate PDF but somehow the background image is not captured in the PDF. Below is the code. Any help is appreciated const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({headless: true}); const page = await browser.newPage(); await page.goto('', {waitUntil : 'networkidle0'}); await page.pdf({path: 'hn40.pdf', printBackground: true, width: '1024px' , height: '768px'}); await browser.close(); })();
http://codegur.com/48214674/how-do-i-pass-url-parameters-to-chrome-headless
CC-MAIN-2018-17
refinedweb
1,230
59.5
Advances in the computer world occur very swiftly. This article keeps the reader abreast of what is hot and trending in open source Web development. The author has chosen 10 open source tools and practices to create awareness about them. The field of Web development is constantly changing with new frameworks, tools and best practices being used to develop any website. Since its difficult to consider all thats hot in Web development tools and technologies here, Ive put together 10 unique open source tools and practices that are trending today. The Internet of Things (IoT) The Internet of Things (IoT) is one of the hot technologies currently. According to Technavio (a tech-focused research firm), the global IoT market is expected to grow at a CAGR of 31.72 per cent from 2014 to 2019. The IoT is the network of physical objects gadgets, devices, consumer durables, cars and trucks, industrial and utility components, sensors, and other everyday objects – that are embedded with electronics, software, sensors and network connectivity, enabling them to generate, exchange and consume data. The IoT allows objects to be controlled and sensed remotely. As more devices are being connected and made network accessible, Web developers will have to come up with new solutions to help users control and communicate with their everyday gadgets and equipment. Motion UI MotionUI is a Sass library for creating flexible UI transitions and animations. Developed by the folks at ZURB, its widely used for creating animation and CSS transitions easily. Its now a standalone library that powers the transition effects used in a number of Foundation components, including Toggler, Reveal and Orbit. Motion UI has more than two dozen built-in transition classes. You can also create custom transition classes using Motion UI’s mix-in library. Browser based IDEs Traditionally, Web development IDEs have been used with desktop applications. For the past few years, we have seen numerous browser based cloud IDEs being developed rapidly. These IDEs dont require any software other than a Web browser, which allows developers to write code from any computer, over the Internet. Some popular browser based IDEs are Cloud9, Aptana, Mozillas WebIDE, Codiad, Codebox, Orionhub and Icecoder. In this list, Codiad, Codebox and Orionhub are 100 per cent open source. There are restrictions in the Cloud9 free version; we can use only one private workspace. Elasticsearch (Elastic), a distributed search engine Elasticsearch is a highly scalable open source full-text search and analytics engine. Elasticsearch allows you to store, search and analyse large volumes of data quickly and in near real-time. It provides a distributed, multi-tenant-capable full-text search engine with a RESTful Web interface and schema-free JSON documents. Elasticsearch is developed in Java, and is released as open source under the terms of the Apache License. Developed by Shay Banon, the first version of Elasticsearch was released in February 2010. Some of the well-known users of Elasticsearch are Wikimedia, GitHub, Stack Exchange (StackOverflow), StumbleUpon, Mozilla, Quora, Madeus IT Group, Foursquare, Etsy, SoundCloud, FDA, CERN, Centre for Open Science, Reverb, Netflix and Pixabay. Docker Docker is a new container technology. Its very popular nowadays because it allows users to run multiple apps on the same old servers, and it also makes it very easy to package and ship programs. A Docker container has all the dependencies it requires to run an application. Docker automates the deployment of applications inside software containers, by providing an additional layer of abstraction and automation of operating-system-level virtualisation on Linux. Docker uses the resource isolation features of the Linux kernel, such as cgroups and kernel namespaces, and a union-capable files system such as aufs, as well as other features. This allows independent containers to run within a single Linux instance, avoiding the overhead of starting and maintaining virtual machines. Responsive design Responsive Web design is becoming most important as mobile traffic is increasing day by day. This is also a must-have feature in your website, because Google is boosting the rankings of mobile-friendly pages on mobile search results. So if your sites pages arent mobile-friendly, there may be a significant decrease in mobile traffic from Google Search. Responsive design helps Google to provide the relevant, high quality search results that are optimised for specific devices. Responsive design is also no longer restricted to being just mobile-friendly’ or to mobile responsiveness alone. There are already plenty of other devices, screens and integrated wearable gadgets like the Apple watch, Google Glass and Oculus Rift which are much talked about technologies. There are some popular open source frameworks which have developed responsive design like Bootstrap, Foundation, Skeleton, YAML 4, Tuktuk, Less Framework, etc. Card layouts As mentioned in the previous point, responsive design is one of the foremost Web design trends. To make a website responsive, we have to reposition the column into one, two or three columns based on the screen size. For smaller screens, it is preferable to display the content in only one column. This concept has refocused attention on card layouts’ as a design pattern for displaying information in bite-sized chunks. Card layouts were initially popularised by Pinterest a couple of years back and have since become a trend for content-heavy Web pages. The open source jQuery Masonry plugin can be used to design card layouts with dynamic heights and widths. In common card designs, information includes the post title, images or brief descriptions, apart from titles, user names, pictures and various icons. Material design Material design is a design language developed by Google. It is a specification for a unified system of visual, motion and interactive design that adapts across different devices and screen sizes. Material design makes more liberal use of grid-based layouts, responsive animations and transitions, padding, and depth effects such as lighting and shadows. Popular material design frameworks are Material Design Lite (an official Google framework), Materialize, Material-UI, Polymer, Surface, Paper Theme for Bootstrap, Material Design for Bootstrap, Angular Material, etc. JavaScript MV* frameworks JavaScript MV* refers to any framework that implements one of the many MV* (as in, model-view-wildcard) design patterns. Theres MVC (model-view-controller), MVVM (model-view-view model), MVP (model-view-presenter), etc. JavaScript frameworks are a fast growing Web development stack. They help a lot in rapid Web development. These JavaScript frameworks help you to structure your code so that it is scalable, reusable and maintainable. Popular JavaScript frameworks are Angular.js, React, Polymer, Ember.js, Vue.js, Backbone and many more. Single page Web apps One of the hottest trends in Web design is to develop a single page website. Over the past couple of years, we have seen that single page websites are a popular choice among Web designers. Single page websites also help to reduce the extra markup from the Web page. When the Web app needs information, it pulls it from the database and pours it into the local mould. Apart from the top 10 latest open source Web design tools and practices mentioned in this article, some other popular languages and frameworks are Node.js (an event-driven I/O server-side JavaScript environment based on V8), Go and Swift programming languages, the HTML 5 video and player, etc. Do try these hot Web development technologies if you havent done so already.
https://www.opensourceforu.com/2016/06/what%C2%92s-hot-in-open-source-web-development/
CC-MAIN-2020-50
refinedweb
1,226
53.51
In order to achieve that I want to use fsolve from scipy package. So I have first to create a function f(x), i.e. - Code: Select all def func f(x, imax): for i in range(imax): y = [ x[i]-2*x[i-2]...-1/x[i]**2, ] #this should be a matrix containing the #equations in where all the equations are # seperated with ',' return y After define the function you use fsolve like this: scipy.optimize.fsolve( func, inGuess, args = ( imax ). So the argument to fsolve is a function containing the system of equations. My problem is how to create this function having the number of equations depended from imax. e.g. I want to write fsolve(func,args(10)), or fsolve(func,args(20)) etc This is an example that works: - Code: Select all >>> def func2(x): y = [x[0]*cos(x[1]) - 4, x[1]*x[0] - x[1] - 5] return y >>> x0 = scipy.optimize.fsolve(func2, [1, 1]) >>> print x0 [ 6.5041, 0.9084]
http://www.python-forum.org/viewtopic.php?f=6&t=1465
CC-MAIN-2016-40
refinedweb
169
73.37
diophantine A quadratic diophantine equation solving library. This package is not currently in any snapshots. If you're interested in using it, we recommend adding it to Stackage Nightly. Doing so will make builds more reliable, and allow stackage.org to host generated Haddocks. Math.Diophantine A quadratic diophantine equation solving library for haskell. Overview: This library is designed to solve for equations in the form of: ax^2 + bxy + cy^2 + dx + ey + f = 0 Throughout the library, the variables (a,b,c,d,e,f) will always refer to these coefficients. This library will also use the alias: type Z = Integer to shorten the type declerations of the data types and functions. Installation: To install the library, just use cabal along with the provided install files. Use: import the library with: import module Math.Diophantine The most import function of this library is solve :: Equation -> Either SolveError Solution. The types of equations that this library can solve are defined by the different instances of Equation: GeneralEquation Z Z Z Z Z Z- where the six Integers coincide with the six coefficients. LinearEquation Z Z Z- where the 3 integers are d, e, and f. SimpleHyperbolicEquation Z Z Z Z- where the 3 integers are b, d, e, and f. ElipticalEquation Z Z Z Z Z Z- where the six Integers coincide with the six coefficients. ParabolicEquation Z Z Z Z Z Z- where the six Integers coincide with the six coefficients. HyperbolicEquation Z Z Z Z Z Z- where the six Integers coincide with the six coefficients. For most cases, one will want to call solve with a GeneralEquation. A GeneralEquation is used when one does not know the type of equation before hand, or wants to take advantage of the libraries ability to detirmine what kind of form it fits best. One can call specializeEquation to convert a GeneralEquation into the best specialized equation that it matches. This function is called within solve, so one can pass any type of function to solve. The specific functions will try to match to a GeneralEquation if they can; however, they will throw an error if they cannot. The error behavior exists only because these functions should only be called directly if and only if you know at compile time that this function will only ever recieve the proper form. One may want to use these directly for a speed increase, or to clarify a section of code. The solve* functions will return a Solution. Solutions are as follows: ZxZ- ZxZ is the cartesian product of Z and Z, or the set of all pairs of integers. This Solution denotes cases where all pairs will satisfy your equation, such as 0x + 0y = 0. NoSolutions- This Solution denotes that for all (x,y) in Z cross Z, no pair satisfies the equation. SolutionSet [(Z,Z)]- This Solution denotes that for all pairs (x,y) in this set, they will satisfy the given equation. There is also a readEquation :: String -> Either ParseError Equation and solveString :: String -> Either SolveError Solution for parsing equations out of strings. This will do some basic simplification of the equation. TODO: - Finish the implementation of solveHyperbolic
https://www.stackage.org/package/diophantine
CC-MAIN-2017-43
refinedweb
528
55.13
Join the community to find out what other Atlassian users are discussing, debating and creating. I'm using a scripted condition on a workflow transition which only allows the transition if: The script I am using is as follows: import java.sql.Timestamp def today = new Timestamp(new Date().time) def branch def fixVersions = issue.fixVersions if(fixVersions){ if(fixVersions*.startDate == [null]){ return true } def branchDate = fixVersions[0].startDate branchDate.setHours(branchDate.getHours() +9) branch = new Timestamp(branchDate.time) } if (today > branch) { return true } else { return false } Expected Result: If the FixVersion Start Date is set to Jan 13, 2022, the condition should be TRUE after 9am on Jan 13, 2022. Actual Result: If the FixVersion Start Date is set to Jan 13, 2022, the condition is TRUE after 9am on Jan 14, 2022. Any ideas what I may be doing wrong? Have you tried using TimeCategory? Try this: import groovy.time.TimeCategory def fixVersions = issue.fixVersions if(!fixVersions) return true //there are no fixversions on the issue if(fixVersions.every{!it.startDate}) return true //all fix version have no start dates def branchDate = use(TimeCategory){ fixVersions[0].startDate + 9.hours } if(branchDate <= new Date()) return true //current date is after the branch date return false //all other true conditions failed The timecategory block will show an error in the code editor, but it should.
https://community.atlassian.com/t5/Adaptavist-questions/Using-a-date-time-stamp-in-workflow-transition-condition/qaq-p/1910867
CC-MAIN-2022-05
refinedweb
225
50.53
“.pyx” - Pyarmor is command line tool, the main script is “pyarmor.py”, you can run it by python2.6 later. Supported Python Versions Pyarmor need python 2.6 or later, but it supports to run/import the encrypted scripts from Python 2.3 to the latest Python (3.4) by Cross Publish (See below). Supported platforms Windows, Linux, including Embeded Linux are supported, The following operation systems have been tested: - Windows XP, Windows7 both x86 and amd64 - Ubuntu 13.04 both i686, x86_64 and armv7 Installation - Install corresponding Python - Run pip to install pyarmor package from pypi.python.org - $ pip install pyarmor - Or download the package from pypi.python.org and extract the downloaded package to any path, for example, /opt/pyarmor Wizard. Basic Usage The normal scenario for a developer to use pyarmor is - Generate project capsule for each project - Encrypt python scripts with project capsule - Distribute the encrypted scripts to target machine Next it’s an example to show you how to use pyarmor to encrypt scripts and how to distribute encrypted scripts. Encrypt Script Distribute Script. Generate Special “license.lic”. Advanced Usage Run Encrypted Script.pyx')" Or create a startup script startup.py like this,: import pyimcore import pytransform pytransform.exec_file('main.pyx') Then run startup.py as normal python script. You can read the source file pyarmor.py to know the basic usage of pytransform extension. Cross Publish Generate “license.lic” For Special Machine Periodic “license.lic” Generate license.lic which will be expired in Jan. 31, 2015: $ python pyarmor.py license --with-capsule=project.zip --expired-date \ 2015-01-31 This command will generate a new “license.lic” will be expired in Jan. 31, 2015. Change Logs 2.3.2 - Fix error data in examples of wizard 2.3.1 - Implement Run function in the GUI wizard - Make license works in trial version 2.2.1 - Add a GUI wizard - Add examples to show how to use pyarmor 2.1.2 - Fix syntax-error when run/import encrypted scripts in linux x86_64 2.1.1 - Support armv6 2.0.1 - Add option ‘–path’ for command ‘encrypt’ - Support script list in the file for command ‘encrypt’ - Fix issue to encrypt an empty file result in pytransform crash 1.7.7 - Add option ‘–expired-date’ for command ‘license’ - Fix undefined ‘tfm_desc’ for arm-linux - Enhance security level of scripts 1.7.6 - Print exactaly message when pyarmor couldn’t load extension “pytransform” - Fix problem “version ‘GLIBC_2.14’ not found” - Generate “license.lic” which could be bind to fixed machine. 1.7.5 - Add missing extensions for linux x86_64. 1.7.4 - Add command “licene” to generate more “license.lic” by project capsule. 1.7.3 - Add information for using registration code 1.7.2 - Add option –with-extension to support cross-platform publish. - Implement command “capsule” and add option –with-capsule so that we can encrypt scripts with same capsule. - Remove command “convert” and option “-K/–key” 1.7.1 - Encrypt pyshield.lic when distributing source code. 1.7.0 - Enhance encrypt algorithm to protect source code. - Developer can use custom key/iv to encrypt source code - Compiled scripts (.pyc, .pyo) could be encrypted by pyshield - Extension modules (.dll, .so, .pyd) could be encrypted by pyshield. Known Issues [Need document] Bug reports Send an email to: jondy.zhao@gmail.com, Thanks. More Information The trial license will be expired in the end of this quarter, after that, you need pay for registration code from You will receive information electronically immediately after ordering, then replace the content of “license.lic” with registration code only (no newline). 2015-03-05 10:48 + China Standard Time 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/pyarmor/2.3.2/
CC-MAIN-2018-51
refinedweb
633
61.63
WSTP C FUNCTION WSTestHead() This feature is not supported on the Wolfram Cloud. This feature is not supported on the Wolfram Cloud. DetailsDetails - WSTestHead() fails if the current object on the link is not a function with a symbol as a head, or if the name of the symbol does not match head. - WSTestHead() returns 0 in the event of an error, and a nonzero value if the function succeeds. - Use WSError() to retrieve the error code if WSTestHead() fails. - WSTestHead() will reset the stream pointer to the expression on the link just prior to calling WSTestHead() if the function fails. This operation behaves as if the programmer called WSCreateMark(link); WSTestHead(…); WSSeekToMark(…). - WSTestHead() is declared in the WSTP header file wstp.h. ExamplesExamplesopen allclose all Basic Examples (1)Basic Examples (1) #include "wstp.h" /* test whether the head of the incoming object is "ReturnPacket" */ void f(WSLINK lp) { int args; if(WSTestHead(lp, "ReturnPacket", &args)) { /* read the contents of the ReturnPacket[] */ } else { /* the head of incoming packet is not "ReturnPacket" */ } }
http://reference.wolfram.com/language/ref/c/WSTestHead.html
CC-MAIN-2016-26
refinedweb
171
63.29
for, do, and whilewith breakand continue whileLoop do-whileLoop forLoop forLoop forLoop or for-each Loop forLoop breakStatement breakStatement breakStatement continueStatement for, do, and whilewith breakand continue Java loops (iterative statements - while, do, and for) are used to repeat the execution of one or more statements a certain number of times. Java provides three looping statements ( while, do, and for) to iterate a single or compound statement. Along with the iterative statements Java also provides break and continue statements to control the execution of a looping statement. Java's break and continue statements used in labeled and unlabeled forms discussed later in this tutorial. whileLoop Java's while loop is an entry-controlled iterative statement. It has the following syntax in a Java program: while (booleanExpression) Statement //single or a block enclosed in { and } Java's while loop keeps executing the booleanExpression and Statement repeatedly until the booleanExpression evaluates to false. A while statement starts execution by evaluating booleanExpression, if it returns true then Statement is executed. This cycle is repeated until the booleanExpression returns false or a break is executed within from loop's body. The following program illustrates the use of while loop. /* WhileLoopDemo.java */ //Demonstrates while statement public class WhileLoopDemo { public static void main(String[] args) { int fib = 0, step = 1; while (fib < 50) { System.out.print(fib + " "); fib = fib + step; step = fib - step; } } } OUTPUT ====== 0 1 1 2 3 5 8 13 21 34 Above program prints fibonacci numbers from 0 to 50. After printing 34, the value of fib becomes 55 that is larger than 50, therefore in next iteration expression fib < 50 returns false and the execution of while stops here. If the boolean expression in while statement's parentheses does not evaluate to false, the loop will be executed indefinitely and will never terminate. do-whileLoop In Java's while statement you have seen that the booleanExpression is tested for truth before entering in the loop's body. On the contrary, in Java's do loop booleanExpression is tested for truth when exiting from the loop. If it returns false then control does not execute loop's body again else it will do. So, on the basis of where booleanExpression is evaluated (while entering in loop's body or while exiting from loop's body) loops can be categorized as entry-controlled and exit-controlled. Java's do loop is an exit-controlled loop. From the above context, you can also conclude that the body of exit-controlled loop will be executed at least once even if the test condition returns false in first time. Basic syntax of Java's do statement is as follows. do Statement //single or a block enclosed in { and } while (booleanExpression); Note that there is a semicolon (;) after while (booleanExpression) in do syntax. Following program illustrates the use of do statement. /* DoWhileLoopDemo.java */ //Demonstrates do-while statement public class DoWhileLoopDemo { public static void main(String[] args) { int fib = 0, step = 1, i = 1; System.out.println("Prints counting from 1 - 10"); // demonstrates single statement version of do-while do System.out.print(i++ + " "); while(i <= 10); System.out.println(); // one blank line System.out.println("\nPrints fibonacci series up to 50"); // demonstrates compound statement version of do-while do { System.out.print(fib + " "); fib = fib + step; step = fib - step; }while (fib < 50); } } OUTPUT ====== Prints counting from 1 - 10 1 2 3 4 5 6 7 8 9 10 Prints fibonacci series up to 50 0 1 1 2 3 5 8 13 21 34 If you look at above program you will observe that in second do loop we printed a fibonacci series up to 50 that we had also done via while loop in previous example. It shows that a task you perform by while can also be done by do. But, it may not true vice versa because do loop at least once gets executed, whereas while is not if the test condition is false initially. forLoop Java's for loop has two syntaxes. First is the basic for statement that you might have seen in C and C++ languages also. And, the second is enhanced for loop that is used to iterate through arrays, and iterable collections. However, you can iterate through arrays by using basic for loop also, but enhanced one makes it easier. We will see both variants of Java's for loop. forLoop Java's basic for loop inherits its syntax from C language. It has three sections in parentheses those are initialization, booleanExpression, and UpdateCounter. Here goes the syntax of basic for statement. for (initialization; booleanExpression; UpdateCounter) Statement // single or a block enclosed in { and } In above syntax of basic for statement all three section in parentheses are optional, so some of them or all can be omitted. If a for has empty parentheses like for(;;), it is always true and results into indefinite run cycles. Let's see the following example where all sections of Java's basic for loop are demonstrated. /* BasicForLoopDemo.java */ //Demonstrates basic for statement public class BasicForLoopDemo { public static void main(String[] args) { System.out.println("Prints counting from 1 - 10"); for (int i = 1; i <= 10; i++) { System.out.print(i + " "); //prints counting from 1 - 10 } System.out.println(); // print one blank line System.out.println("\nPrints fibonacci series up to 50"); for(int fib = 0, step = 1; fib < 50; fib = fib + step, step = fib - step) System.out.print(fib + " "); //prints fibonacci numbers up to 50 for (;;) { System.out.println("\n\nAll time true..."); break; } } } OUTPUT ====== Prints counting from 1 - 10 1 2 3 4 5 6 7 8 9 10 Prints fibonacci series up to 50 0 1 1 2 3 5 8 13 21 34 All time true... Above example code demonstrates three flavors of basic for statement. Very first is the typical one which you will see most of the time. The second one has more than one initializations, as well as more than one update variables. This is perfectly legal and acceptable to initialize, and update more than one variable in initialization and update sections. All operations should be comma separated. This also demonstrates a special use of comma operator. Third and last flavor of for loop can run into indefinite cycles, if break is removed from the loop. forLoop or for-each Loop Java's enhanced for loop was introduced in Java 5.0 to facilitate array and collection traversing. It is also referred as the for-each loop. By providing enhanced for statement Java folks simplified the code structure. Following is the syntax the enhanced for follows. for (Type Identifier : Expression) Statement // single or a block enclosed in { and } The Expression should be either of type Iterable or an array. Otherwise, there will be a compile time error. The Identifier is a local variable of a suitable type for the set's contents. The following program illustrates the use of Java's enhanced for loop. /* EnhancedForLoopDemo.java */ //Demonstrates enhanced for statement public class EnhancedForLoopDemo { public static void main(String[] args) { int[] arrOneD = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; int[][] arrTwoD = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println("printing one dimensional array with basic for:"); for(int i = 0; i < arrOneD.length; i++) System.out.print(arrOneD[i] + " "); System.out.println(); //blank line System.out.println("printing one dimensional array with enhanced for:"); for(int i : arrOneD) System.out.print(i + " "); System.out.println(); //blank line System.out.println("\nprinting two dimensional array with basic for:"); for (int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) System.out.print(arrTwoD[i][j] + " "); System.out.println(); } System.out.println(); //blank line System.out.println("\nprinting two dimensional array with enhanced for:"); for (int[] arr : arrTwoD) { for(int elm : arr) System.out.print(elm + " "); System.out.println(); } } } OUTPUT ====== printing one dimensional array contents with basic for: 10 11 12 13 14 15 16 17 18 19 20 printing one dimensional array contents with enhanced for: 10 11 12 13 14 15 16 17 18 19 20 printing two dimensional array contents with basic for: 1 2 3 4 5 6 7 8 9 printing two dimensional array contents with enhanced for: 1 2 3 4 5 6 7 8 9 While printing contents of arrOneD by for-each loop the array arrOneD returns one int value at a time from the array until it reaches to the end. Whereas, in arrTwoD outer for loop returns a one-dimensional array that is stored in arr then in inner for loop array arr is dereferenced to get individual elements printed. forLoop Note that sometimes a variable is only needed to control a for loop. If this is the case, it can be declared and initialized in the first portion of for loop where initialization of loop control variables takes place. A very important point to note that if a variable is declared in initialization section of for loop, its scope is limited up to the body of for loop only. Attempting to use that variable outside the body of for will result into a compile time error. Have a look at the following program to understand the functioning of initialization variable inside Java's for loop. /* LoopControlVarDemo.java: demonstrates declaration and initialization * of loop control variable inside for loop. */ public class LoopControlVarDemo { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.print(i + " "); } System.out.println(i + " "); // Error, i is not visible out of for block } } In above piece of code class LoopControlVarDemo will not compile because variable i is being tried to access outside the for loop's block while i is only visible up to body of for statement. breakStatement Java's break statement is mainly used to break the flow of execution. It has three uses in Java: goto. Java's break statement can be labeled or unlabeled. An unlabeled break is used to terminate the execution of a switch or a loop, whereas the labeled break is used as goto statement. breakStatement Let us first look at Java's unlabeled break statement. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. It is important to note that when a break is used inside nested loops, it only exits from the loop in which it is executed. Here is a simple example: // Using break to exit a loop. class UnlabeledLoopBreak { public static void main(String args[]) { // break exiting from a single loop for(int i = 1; i <= 100; i++) { if(i * i == 121) break; // terminate loop if i is 11 System.out.print(i + " "); } System.out.println("\nDone printing counting."); System.out.println(); // blank line // break exiting from nested loops for(int i = 1; i <= 10; i++) { for(int j = 1; j <= 10; j++) { if(j > i) break; // terminate loop if j is greater than i System.out.print(j + " "); } System.out.println(); } System.out.println("\nDone printing pyramid."); } } OUTPUT ====== 1 2 3 4 5 6 7 8 9 10 Done printing counting. Done printing pyramid. The first for loop in above program exits in two conditions either i is greater than 100 or product of i * i is equal to 121. Latter condition causes this for loop to terminate early by using break statement. Second time while printing the number pyramid there are two nested for loops and the condition if(j > i) when becomes true control exits from the inner loop only. Importantly note that unlabeled break cannot be used outside of a loop or a switch. breakStatement Java's labeled break statement fulfils the purpose of goto in some sense. Java has goto as a reserved word, but it is not used currently. Because goto statements are considered poor style of programming, they lower the spirit of structured programming. It has always been a topic of debate whether goto should be used in a program or not. A bigger fraternity of programmers says that unrestricted use of goto is error prone but an occasional use to get out of a loop is expedient. Java designers agreed to programmers' community and added a labeled break to support this programming style. A labeled break marks a block of code and gets you out of that block when executed within from that block. The condition is that the break statement should be executed within from the same block and properly labeled. The syntax of labeled break statement goes here: break label; Take a look at the following program where we have a named block breakIt, and we want to get out of this block if a particular condition occurs. In that case we will execute break breakIt; statement within from the named block breakIt. The following example program demonstrates the use of labeled break. //Demonstrates labeled break public class LabeledBreakDemo { public static void main(String[] args) { breakIt: { for(int i = 1; i < 5; i++) { for(int j = 1; j < 5; j ++) { for(int k = 1; k < 5; k ++) { if (j == 3) { //gets out of breakIt block break breakIt; } System.out.print(j + " "); } System.out.println(); } System.out.println(); } } System.out.println("Out of breakIt block"); } } OUTPUT ====== 1 1 1 1 2 2 2 2 Out of breakIt block If you look at the body of inner most for statement in above program, you will see a break breakIt; statement controlled by if (j == 3). As soon as this condition returns true the statement break breakIt; will be executed and control will be moved out of the block breakIt. continueStatement Java's continue statement can only be placed in iterative (loop) statements ( while, do, and for) to cause an early iteration. It means that during certain situations if you do not want to process complete body of the loop and wish to pass the control to the loop-continuation point then you can place a continue statement at that point. The continue statement of Java can also be used with or without label. It has the following syntax in a Java program: continue optional-label; Java's continue statement without label transfers control to the immediate enclosing while, do, or for loop. Whereas, a continue statement with label transfers control to the labeled loop statement. The following program illustrates the use of both unlabeled, and labeled continue statements. /* ContinueDemo.java */ //Demonstrates unlabeled, and labeled continue public class ContinueDemo { public static void main(String[] args) { // demonstrating unlabelled break System.out.println("Demonstration of unlabeled continue:"); for (int i =1; i <= 50; i++) { if (i % 5 != 0) continue; System.out.format("%5d", i); } System.out.println("\n"); System.out.println("Demonstration of labeled continue:"); outer: for (int i =1; i <= 50; i++) { for(int j = 1; j <= 10; j++) { if (i % 5 != 0) continue outer; System.out.format("%5d", i*j); } System.out.println(); } } } OUTPUT ====== Demonstration of unlabeled continue: 5 10 15 20 25 30 35 40 45 50 Demonstration of labeled continue: 5 10 15 20 25 30 35 40 45 50 10 20 30 40 50 60 70 80 90 100 15 30 45 60 75 90 105 120 135 150 20 40 60 80 100 120 140 160 180 200 25 50 75 100 125 150 175 200 225 250 30 60 90 120 150 180 210 240 270 300 35 70 105 140 175 210 245 280 315 350 40 80 120 160 200 240 280 320 360 400 45 90 135 180 225 270 315 360 405 450 50 100 150 200 250 300 350 400 450 500 The labeled continue in above example takes program control to the label outer from where outer for loop starts. However, there are many easy ways to print vertical and horizontal tables from 5 to 50, we did this way to just demonstrate the use of labeled continue. In this tutorial we talked of Java's iterative (loop) statements such as while, do, and for. Java provides two variants of for loop those are basic for and enhanced for or for-each. Java's enhanced for loop is useful when we have to iterate through a list. To control loop execution Java provides break and continue statements. Both break and continue can be used with and without
http://cs-fundamentals.com/java-programming/java-control-flow-loops-do-while-enhanced-for.php
CC-MAIN-2017-17
refinedweb
2,720
61.16
You may well have heard of Firebase, Google’s serverless back-end platform. With Firebase, iOS (and other platform) developers can cut down on early development costs by not worrying about building server architecture for their apps. Firebase has a real-time database (Firestore), cloud storage, notifications, analytics, and other services that many of our apps need. And without the need for DevOps and dedicated server developers, we can start our iOS app with smaller teams and move faster. And of course, we’ll want to internationalize our iOS/Firebase apps as we build them so we can reach as many people as possible and maximize our revenue. In this two-part series, we’ll take an iOS app with Firebase and internationalize it so that it can work in multiple languages. We’ll start with the user interface in this article, and move on to the Firebase back-end in the next instalment. Our App: Discounter Here’s what we’ll build: The app we’ll have by the end of this article Our demo app, Discounter, targets price-conscious retail consumers and aggregates city’s coupons, flyers, and sale information for these users in one place. Our users can then browse and search for their favourite products to see if they’ve been discounted. In this series, we’ll focus on the Feed screen, which lists recently discounted products in a user’s city. Note » The design of our demo app was established in our article, Designing Apps in Sketch for iOS Internationalization, so be sure to check that article out if you’re more into the design side of things. We’ll internationalize the app so it can work with both English and Arabic. You can choose any languages to work with, of course. But let’s start at the start. We’ll assume we’ve built out one of the screens of our app without internationalization. Something like this: Our starting point Note » If you want to code along with us you can grab the starter project on Github. We’re using the starter project as our launching point here. Photo & Icon Credits Some photos and icons used in the app were sourced. Photo by Fachry Zella Devandra on Unsplash - PlayStation 4 Photo by JESHOOTS.COM on Unsplash The colour palette used in the app was largely derived from the Smashing Magazine Wallpaper, Let’s Get Outside, by Lívia Lénárt. A Quick Tour of the Code Let’s briefly take a look at the app architecture as it stands. Our Main.storyboard The bulk of our UI is defined in the usual Main.storyboard. Here we have a UITabBarController for our root navigation and segues to other, simple controllers that make up our app screens. Our main focus will be on the FeedViewController. It’s a very simple UIViewController that acts as the data source for our feed’s UITableview. import UIKit class FeedViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var feedTableView: UITableView! fileprivate var productListener: Product.Listener? fileprivate var products: [Product] = [] { didSet { feedTableView.reloadData() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) productListener = Product.listenToFeed { [unowned self] in self.products = $0 } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) productListener?.remove() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return products.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CELL") as! FeedTableViewCell cell.updateUI(with: products[indexPath.row]) return cell } } Note » I’ve been writing a lot of C# lately, so I’ve gotten used to placing my {on their own lines. Forgive me if my less than idiomatic Swift looks odd to you. We use Product, our main model, to register a listener to our product feed in our viewWillAppear(_:). We do this so we can see changes to our feed in real-time. Product is just using the Firebase Firestore SDK underneath the hood. We deregister our listener in viewWillDisappear(_:) to avoid memory leaks and unnecessary Firebase database costs. We’ll be getting a bit deeper into the Product model in our next article. Suffice it to say for the time being that our Products have simple String fields like productName and priceAfterDiscount, which serve to populate our UI. Now let’s take a look at the custom UITableViewCell that we’re using with our FeedViewController. Note » You can check out the code for the Productmodel, as well as the entire starter XCode project on Github. import UIKit import SDWebImage class FeedTableViewCell: UITableViewCell { @IBOutlet weak var productNameLabel: UILabel! @IBOutlet weak var storeNameLabel: UILabel! @IBOutlet weak var discountLabel: UILabel! @IBOutlet weak var expiryLabel: UILabel! @IBOutlet weak var priceAfterDiscountLabel: UILabel! @IBOutlet weak var priceBeforeDiscountLabel: UILabel! @IBOutlet weak var productImageView: UIImageView! func updateUI(with product: Product) { productNameLabel.text = product.name storeNameLabel.text = product.store.uppercased() discountLabel.text = product.discount.uppercased() expiryLabel.text = "Expires \(product.expires)".uppercased() priceAfterDiscountLabel.text = product.priceAfterDiscount priceBeforeDiscountLabel.attributedText = strikeThrough(product.priceBeforeDiscount) productImageView.sd_setImage(with: URL(string: product.imageUrl)) } } Again, this is a pretty bread-and-butter iOS code. We take a Product object in updateUI(with:), do some light transformation to its fields, and connect the resulting values with our cell’s views. We’re using the popular SDWebImage library for loading our products’ network images. Note » We’re using a helper function, strikeThrough(_:), to convert a string into an attributed string with a line through it. You can see its code on Github. That’s generally it for our feed’s MVC. We’ll get to more of the code that pertains to our UI as we delve deeper into our internationalization work. Speaking of which, let’s get started on internationalizing this puppy. The Firestore Model If you’re working along and you have a Firebase project setup and connected to your iOS app, here’s a quick look at the Firebase Firestore database structure in case you want to replicate it. Our Firestore product feed model Beginning Our iOS/Firebase Internationalization: Adding a Language To begin internationalizing our UI we just need to add a language to our project in XCode. We select our project in our navigator, select our project again (not a specific target) in our project window, and click the ➕ button under Localizations. We start our i18n by adding a language We then select the language we want to add, and select Localizable Strings when asked how to internationalize our current files. In my case, I’ve selected Arabic. Note » We go into language settings and storyboard localization in much more detail in our article, iOS i18n: Internationalizing Storyboards in XCode. Localizing Storyboard Text Since we opted for localizable strings when we added our language, translating our storyboard strings is pretty straightforward. We just need to unfold Main.storyboard in the project navigator and select the Main.strings (Arabic) file. With the .strings file open, we can add our Arabic translations. Here’s an excerpt of the translated Main.strings: /* Class = "UIButton"; normalTitle = "Sort & Filter"; ObjectID = "2Sk-5H-KF9"; */ "2Sk-5H-KF9.normalTitle" = "فرز وتصفية"; /* Class = "UILabel"; text = "Search"; ObjectID = "448-81-bRb"; */ "448-81-bRb.text" = "بحث"; Testing Our Localized App Now that we have our storyboard strings translated, we can preview our app in Arabic by opening Main.storyboard. We then open the Assistant Editor, and select Preview > Main.storyboard (Preview) Previewing our FeedController in Arabic using the Assistant Editor This will show us the translated strings, but won’t reflow our layout to match Arabic’s right-to-left direction. To see how our app will look to real users reading in Arabic, we can edit our Run scheme. We go to Product > Scheme > Edit Scheme in XCode’s menu, and change the Application Language to Arabic. We can select a runtime language for our Run Scheme After we make this change and run the app in our simulator, we can see our Arabic text and the app’s right-to-left layout. We’re getting there: our Arabic strings are showing up in the app Fixing Layout using Stack Views Our app looks a bit odd in Arabic: buttons with images look broken. Let’s take a closer look at each button one by one. Our Sort & Filter button has its icon on the wrong side of the text. Well that looks broken It’s currently laid out using good old Auto Layout constraints, with trailing and leading edges pinned to the button’s superview and adjacent title label, respectively. This should automatically take care of the button when our layout changes to right-to-left, but for some reason—and for the life of me I couldn’t figure out what it is—it does not. However, we can fix this by embedding our button and the app’s title label in a Stack View. We take the label and the button out of the View they’re in and embed them in a Stack View. We then set the Stack View’s properties so that we get its two children horizontally aligned. We make sure that our Stack View is horizontally aligned This gets us part of the way there. We also need to make sure our button’s subview alignment is to the button’s trailing edge in the Attributes Inspector. Aligning our button’s content to the trailing edge Now we need to add some spacing between the edges of the screen and our content. One way to do this is to embed the Stack View itself in another View. This is because our Stack View itself is inside a parent Stack View, and Stack View’s children generally don’t respect explicit Auto Layout constraints. After all, the Stack View’s job is to lay out its children automatically. We can get around this problem by wrapping the child Stack View in a plain old View and setting our spacing constraints on the inner Stack View. We can now add spacing by constraining the Stack View to its parent View After we make these changes and run our app, we see that the Sort & Filter button has its image on the correct side of the text. The button’s image is beginning to behave itself Flipping Edge Insets The image in our Sort & Filter button is now rendering on the correct side of the button. However, the image is flush with the button’s title, which isn’t what we want. We’d like a bit of spacing between the button’s image and its title. This is currently set up through the button’s UIEdgeInsets settings in the Size Inspector. Our button’s edge inset settings We want these to flip for right-to-left layouts, and we might as well generalize this flip for a button’s three inset types: content, title, and image. A UIButton subclass can do the trick for us here. import UIKit class FlippableUIButton: UIButton { override func awakeFromNib() { if (Locale.current.isRightToLeft) { flipAllEdgeInsets() } } fileprivate func flipAllEdgeInsets() -> Void { flip(edgeInsets: &contentEdgeInsets) flip(edgeInsets: &titleEdgeInsets) flip(edgeInsets: &imageEdgeInsets) } fileprivate func flip(edgeInsets: inout UIEdgeInsets) -> Void { let leftEdgeInset = edgeInsets.left edgeInsets.left = edgeInsets.right edgeInsets.right = leftEdgeInset } } We simply swap all of our button’s right and left UIEdgeInsets on awakeFromNib() when our current Locale‘s language direction is right-to-left. To facilitate this, we have a simple extension to Swift’s Locale class. import Foundation extension Locale { var isRightToLeft: Bool { get { if let languageCode = self.languageCode { return Locale.characterDirection(forLanguage: languageCode) == .rightToLeft } return false } } } isRightToLeft is a simple computed Bool that allows us to avoid the verbose characterDirection(forLanguage:) call every time we want to know if the current locale’s language has a right-to-left direction. With this code in place, we can change our button’s class to FlippableUIButton in its Identity Inspector in Main.storyboard. In fact, we can do so for our sorting indicator button as well, which you may have noticed was also broken in right-to-left orientation. Once we do that and re-run our app, we can see that our two buttons have the correct spacing in Arabic. Two birds with one stone: our FlippableUIButton can be applied to multiple buttons to handle right-to-left layouts automatically Flipping Images OK, our buttons’ edge insets are largely taken care of. However, our Sort & Filter button’s icon looks weird in Arabic. It should be horizontally flipped. We can add this behaviour to our FlippableUIButton class. However, we don’t want to flip all button images. Sometimes it makes sense to have the same image orientation for both left-to-right and right-to-left layouts. So we can make our FlippableUIButton editable in our inspectors and add a flag that indicates whether to flip a button’s image or not. import UIKit @IBDesignable class FlippableUIButton: UIButton { var _flipImageForRTL: Bool = false @IBInspectable var flipImageForRightToLeftLanguages: Bool { get { return _flipImageForRTL } set { _flipImageForRTL = newValue } } override func awakeFromNib() { if (Locale.current.isRightToLeft) { flipAllEdgeInsets() if (flipImageForRightToLeftLanguages) { flipImage() } } } // ... fileprivate func flipImage() -> Void { if let image = imageView?.image { let flippedImage = UIImage( cgImage: image.cgImage!, scale: image.scale, orientation: .upMirrored) setImage(flippedImage, for: .normal) } } } We opt not to flip a button’s image by default and provide an @IBInspectable flag that can force the flip in a storyboard’s Attribute Inspector. If the flag is set to true, we flip the button’s image by making a copy of it and setting the copy’s orientation to UIImage.Orientation.upMirrored (which flips it horizontally). We then set the flipped copy as the button’s image via UIButton‘s setImage(_:for:). With this in place, we can pick which of our FlippableUIButtons should have flipped images in our Main.storyboard. Our setting to flip a button’s image is available in the Attribute Inspector Avoid Adding Text to Image-Only Buttons Notice that in right-to-left orientation our “favourite” (thumbs up) button has too much space to its left. That’s way too much space This seems to be happening because even though this is an image-only button, we have default text set in its title. The button’s default title text is breaking our layout While this didn’t cause problems in English, probably because the text was clipping to the right of the image, it seems to be breaking our layout in Arabic. The quick fix is just to remove the title text, setting it to an empty string. Once we do that, all is right with the world again. Our app in Arabic with all the UI fixes Adios for Now That takes care of most of the UI internationalization work for our FeedViewController. Next time, we’ll round out our internationalization and localization work for the app, looking at how to work with multiple locales in the Firebase Firestore and sending push notifications per language. Note » You can get the complete code for this article on Github. Are you working on an iOS app and internationalizing and localizing it for audiences in multiple locales? Well, if you’re looking for a feature-rich, professional localization solution, Phrase has got you covered. Phrase. I hope you’ve enjoyed this foray into internationalizing a full-stack iOS app. We started with the front-end here, and in the next part of this series, we’ll turn our attention to the Firebase back-end. Stay tuned 📻
https://phrase.com/blog/posts/internationalizing-a-full-stack-ios-app-firebase-part-1-user-interface/
CC-MAIN-2020-50
refinedweb
2,558
54.93
Kevin Marsh 2009-04-11T13:39:42-07:00 Kevin Marsh kevin.marsh@gmail.com Jekyll 2009-02-12T00:00:00-08:00 <h3>Source Code</h3> <p>First up, feel free to check out the full source code that Jekyll uses to build all this html:</p> <h3>Importing from Mephisto</h3> <p>Here’s a hacky, super-simple, one-liner script that I threw together at the Mephisto Rails console:</p> <pre> Content.find_by_sql("SELECT id, permalink, body, published_at, title FROM contents WHERE type = 'Article' AND published_at IS NOT NULL ORDER BY published_at").each {|c| File.open("#{c.published_at.strftime('%Y-%m-%d')}-#{c.permalink}.textile", "w+"){|f| f.puts "---\nlayout: post\ntitle: #{c.title}\n---\n\n"; f.puts c.body }} </pre> <p>This will not work 100%, though. It doesn’t do anything fancy like output real <span class="caps">YAML</span>, with escaped characters. So if you have funky characters in your titles, things could blow up.</p> <h3><code>uninitialized constant Classifier::LSI::Matrix (NameError)</code> when running with <code>--lsi</code> option</h3> <p>Applying <a href="">this patch</a> to Classifier’s lsi.rb file seemed to do the trick.</p> <p>As an aside: I’m truly impressed with the Classifier gem. I’ve seen its Bayesian stuff before, but Jekyll was my first exposure to <a href=""><span class="caps">LSI</span></a>.</p> <h3>Categories</h3> <p>I was thinking about adding other “types” of posts to my site, something along the lines of books I’m reading, music I’m enjoying, etc.</p> <p>I decided I could use Categories to pull this off, so my structure looks something like this:</p> <pre> |-- CNAME |-- _layouts | |-- book.html | |-- master.html | |-- music.html | `-- post.html |-- about.textile |-- articles | `-- _posts | |-- 2009-02-10-reducing-the-noise.textile | `-- 2009-02-12-jekyll.textile |-- atom.xml |-- books | `-- _posts | `-- 2009-02-12-click.textile |-- images | `-- feed.png |-- index.html |-- movies | `-- _posts |-- music | `-- _posts | `-- 2009-02-12-ray-lamontagne-gossip-in-the-grain.textile `-- stylesheets `-- styles.css </pre> <p>Then on my homepage, for example, I can pull all the music entries with album art from Amazon by doing:</p> <pre> { % for music in site.categories.music % } <a href=""><img alt="" src=""></a> { % endfor % } </pre> <p>(I added an <code>asin</code> key to the post’s metadata header.) Slick!</p> <h3>Excerpts</h3> <p>Thankfully thanks to Jekyll’s slick metadata feature for posts, all I had to do was add a <code>excerpt</code> key to the header of a post and throw my excerpt there:</p> <pre> --- layout: post title: Jekyll excerpt: |- I've taken the plunge to a static-HTML blog with Jekyll. I'm impressed so far. I love having the whole she-bang in git, but then again the whole idea of a "datastore in git":/2008/04/13/git-as-a-data-store.html. Big ups to "Michael Bleigh": for making his whole blog available on "GitHub":. I didn't take much design-wise, but seeing how things were structured was a huge help. I did nick his Atom feed template. --- h3. Importing from Mephisto Here's a hacky, super-simple, one-liner script that I threw together at the Mephisto Rails console: </pre> <p>The next gotcha was that I couldn’t get Jekyll to Textilize anything other than the content, and since my excerpt needed to be rendered as Textile, this was a problem.</p> <p>So I submitted <a href="">a patch</a> that creates a filter called <code>textilize</code> that I can pass my excerpt into for formatting. Hopefully it gets applied to the master branch that GitHub Pages uses.</p> <h3>Inspiration</h3> <p>Big ups to <a href="tom.preston-werner.com/">Tom Preston-Werner</a> for writing Jekyll and <a href="">Michael Bleigh</a> for making his whole blog’s source available on <a href="">GitHub</a>. I didn’t take much design-wise, but seeing how things were structured was a huge help. (I did nick his Atom feed template.)</p><img src="" height="1" width="1"/> Reducing the Noise 2009-02-10T00:00:00-08:00 <p>I’m spending some time tonight to try and reduce some of the noise in my life. From a practical standpoint, this means I’m:</p> <ul> <li>Unsubscribing from a few <span class="caps">RSS</span> feeds that I end up just reading past anyway</li> <li>Deleting some iTunes tracks that I usually end skipping, both at my desk and in my car (the Skip Count in iTunes is great for this)</li> <li>Unsubscribing from a few mailing lists I rarely read, are definitely not active in, and end up just Google searching when I need a topical answer</li> <li>Taking steps to reduce blog spam</li> <li>Creating server-side and client-side rules to move bulk e-mail from companies like Dell to their own folder or tag, and skipping the inbox altogether. Even better, unsubscribing from most of these completely.</li> <li>Deleting rarely used Apps</li> </ul> <p>While these minor things seem really trivial piece-by-piece, I think the sum of them cause a lot of distraction and cloud meaningful activities. As such, I plan to do this de-lousing on a periodic basis.</p><img src="" height="1" width="1"/> Your Rails Apps Changelog in git 2008-05-19T00:00:00-07:00 <p>OK, this one is almost too hacky and simple to share, but I wanted to get it out there. Want to show your site’s users what’s changed? Just show them your git changelog:</p> <p style="text-align:center;"><img src="" alt="" /></p> <p>It’s a bit dorky, and definately not as pretty as a <a href="">properly parsed and formatted changelog</a>, but for showing stakeholders what’s changed it’s been useful.</p> <p>Here’s how it’s done (again, kind of a hack):</p> <h3>Controller</h3> <pre> @code = `cd /var/www/vintageaerial.com/htdocs/shared/cached-copy && git-log --max-count=20 --no-merges` </pre> <h3>View</h3> <pre> <pre class="changelog"><%= @changes %></pre> </pre> <h3>Stylesheet</h3> <pre> pre.changelog { overflow: scroll; } </pre> <p>I definitely wouldn’t use this in high-traffic production areas without some caching. It’s also enforcing me to write better, more communicative changeset descriptions, because I know someone can read them.</p><img src="" height="1" width="1"/> rake db:production:clone 2008-04-17T00:00:00-07:00 <p>I’ve been using this little <code>rake</code> ditty for awhile, to refresh my current development database with data from the production server:</p> <pre> namespace :db do namespace :production do desc "Recreate the local development database as a clone of the remote production database" task :clone do system %Q(ssh [db_host] "rm /tmp/out.sql.bz2; mysqldump -uroot -p [production_database_name] > /tmp/out.sql; bzip2 /tmp/out.sql") system %Q(scp [db_host]:/tmp/out.sql.bz2 .) system %Q(bzcat out.sql.bz2 | mysql -uroot -D[development_database_name]) system %Q(rm out.sql.bz2) end end end </pre> <p>Of course, you’ll have to change the bits in brackets to fit your particular situation.</p> <p>Now, this obviously isn’t for everyone, but for small-to-medium sized databases it works pretty well and helps you work with real data.</p><img src="" height="1" width="1"/> Git as a Data Store 2008-04-13T00:00:00-07:00 <p>I’m fascinated with the idea of git not just as a version control system for source code, but a redundant, version controlled filesystem for <strong>anything</strong>.</p> <p>Take <a href="">git-wiki</a> for example. It uses plain text Textile/Markdown files in a git repository as its database. You get all the benefits git users have for source code, but for wiki content. <a href="">I’ve written a little scenario</a> demonstrating some of the strengths of the platform.</p> <p>Just by using git, you get:</p> <ul> <li><strong>version control</strong>: with past revision rollbacks, diffs, the whole lot</li> <li><strong>redundancy</strong>: you can push up your entire wiki, with all changeset history, in seconds to multiple locations for backup</li> <li><strong>security</strong>: since each blob is referenced by a cryptographically-secure SHA1 hash, as is each commit, you can be sure your wiki hasn’t been tampered with</li> <li><strong>offline access</strong>: you can pull your entire wiki, again with all changeset history, to edit and interact with offline</li> <li><strong>branching</strong>: make radical changes without affecting the mainline</li> </ul> <p>The concept seems to apply well to a wiki, but I think they’d work as well in a <span class="caps">CMS</span>. Imagine being able to pull down an entire site’s content, create an experimental branch of content, refine it, then push it back up to your site: all while having the freedom to go back to any point in time in seconds.</p> <p>The <span class="caps">CMS</span> backend (<em>if there even is one</em>) would still allow you to make changes online, but would check them in the git repository to be tracked. Stylesheets, images, original assets, and so on could be versioned along with the text, since git is so efficient even with binary files.</p><img src="" height="1" width="1"/> sitesmetric Progress 2008-01-24T00:00:00-08:00 <p>I’ve gotten a respectable amount of work done on sitesmetric, insofar that it actually downloads data (intelligently) and displays it (somewhere intelligently)</p> <p>Sneak a peek:</p> <p style="text-align:center;"><a href=""><img src="" alt="" /></a></p> <p>Head on over to <a href="">sitesmetric</a> to signup and be notified of the beta program, opening soon!</p><img src="" height="1" width="1"/> Another Project, or, Introducing sitesmetric 2008-01-22T00:00:00-08:00 <p>Yes, I’ve started yet another project. I’ve got tons of cycles spent on this, so I hope to be able to execute a really simple v1.0 and get it launched <span class="caps">ASAP</span>. The splash page is up. <a href="">Go check it out in another tab</a>… I’ll wait.</p> <p>One interesting aspect of this project has been the planning. The really early conceptual stuff I did on <a href="">MindMeister</a>. What a great way to hammer out all the aspects of an idea you have kicking around your head. MindMeister allows you to be as broad (I started with a quick elevator pitch) or as deep (schema, models, controllers) as you want.</p> <p style="float:right;"><img src="" alt="" /></p> <p>After this step, I used Fireworks CS3 to mockup some screens. Now, I thought Fireworks was just Macromedia’s wimpy Photoshop clone but since Adobe swallowed it, I think it’s trying to be a rapid prototyping tool. Which is fine by be, it worked great. I’ve never really worked with anything at this stage that let me mold pixels as easily as putty:</p> <p style="text-align:center;"><img src="" alt="" /></p> <p>Without divulging too much, of course, here’s the pitch. (There are still some legal issues I’m working out with the largest search engine company.) It grew out of my frustration of trying to keep track of all the loose ends of various sites. dotfiles, lifemetric, taglol, this blog; they go on and on. All the information I needed wasn’t all together, so stuff randomly fell through the cracks and I didn’t know about some of the things I probably should have. I hope sitesmetric will fill this gap.</p> <p>So imagine sitesmetric as being the one place you can go to see the latest traffic trends; mentions on sites like Digg, Slashdot, reddit, etc.; keyword positions; domain registrations; hosting details; and so on.</p> <p>In the coming days I hope to share some more mock ups and comps.</p><img src="" height="1" width="1"/> Merb Asset Helpers 2008-01-15T00:00:00-08:00 <p><a href="">Merb</a>, like Rails 2.0, sports some very flexible asset helpers. But Merb’s asset helpers bring a whole lot more to the table in terms of flexibility, speed, and features. Kinda like Merb itself.</p> <p>Take <code>js_include_tag</code>. Sure, you can just throw it in your application layout and include some Javascript on every page like you would with Rails. You can even “bundle” all your Javascript assets. No, not manually. Merb is smart enough to give you the flexibility of separate files in development mode, but give you the extra speed boost in production mode. This is probably old news to a lot of Rails developers that haven’t been under rocks for the past year.</p> <p>But, Merb gives us even more flexibility. What if you want to minify your Javascript? Merb supports asset bundler callbacks, which let you run some code after a bundle is created:</p> <pre> Merb::Assets::JavascriptAssetBundler.add_callback do |filename| system("/usr/local/bin/yui-compress #{filename}") end </pre> <p>Pretty cool huh? Now, you could come close to this in Rails with something like <a href="">PackR</a> but it gets better:</p> <p>If you’re the kind of web ninja who keeps their Javascript or <span class="caps">CSS</span> separated, it may be kind of cumbersome to figure out which assets you should be including and when. Not with Merb. Enter <code>include_required_js</code> and <code>include_required_css</code>. Throw these two methods in your application layout and you now have the flexibility to specify what Javascript or <span class="caps">CSS</span> files to include for what view. In the view. Where it makes the most sense:</p> <pre> <!-- application.html.erb --> <html> <head> <%= include_required_js %> <%= include_required_css %> </head> <body> <!-- SNIP! --> </body> </html> </pre> <pre> <!-- list.html.erb (or any view or partial, really) --> <% require_js 'auto-complete' -%> </pre> <p>I can see this making a lot of sense for including something like Javascript auto-completion or calendar popups <em>only on pages that actually require them</em>. Which is a huge win for the other, say 90%, of your pages that don’t require the Javascript file to be present.</p> <p>P.S. Props to the Merb team for creating clean and well-documented code that makes finding gems like this easy (and maybe even a little fun) to find.</p><img src="" height="1" width="1"/> Minor Leopard Rails Wrinkle 2007-10-30T00:00:00-07:00 <p>If you encounter this issue booting up a Mongrel:</p> <pre> $ ./script/server /Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `gem_original_require': no such file to load -- builder/blankslate (LoadError) from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `require' from /Users/kmarsh/Sites/sampleboardportal/vendor/rails/activesupport/lib/active_support/basic_object.rb:3 from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `gem_original_require' from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `require' from /Users/kmarsh/Sites/sampleboardportal/vendor/rails/activesupport/lib/active_support.rb:29 from /Users/kmarsh/Sites/sampleboardportal/vendor/rails/railties/lib/commands/server.rb:1:in `require' from /Users/kmarsh/Sites/sampleboardportal/vendor/rails/railties/lib/commands/server.rb:1 from ./script/server:3:in `require' from ./script/server:3 </pre> <p>…it’s because you’re missing Builder. Try <code>sudo gem install builder</code>. Fixed the issue for me!</p><img src="" height="1" width="1"/> My Rails Stack Setup Notes 2007-10-02T00:00:00-07:00 <p>It really is a no brainer to setup Linux, MySQL, Ruby, RubyGems, RMagick, Rails, etc. the 45th time you’ve done it. But it takes a bit of time to go through those 44 other times. So I decided to write down all my steps so I can consistently setup a box at will with little fuss. Take a look, it probably is very close to what you’re looking for:</p> <p style="text-align:center;"><a href="">Ubuntu / MySQL / Rails Stack Install Guide</a></p><img src="" height="1" width="1"/> The Only Way Digg Can Redeem Itself 2007-05-02T00:00:00-07:00 <p>Kevin Rose <a href="">has stated</a> he intends to stop the censorship of the <a href="">posting</a> of the (now) infamous <span class="caps">AACS</span> code.</p> <p>The only way Digg can redeem itself now in the minds of its followers is to be sued by the <span class="caps">MPAA</span>, fight it, take the case all the way to the Supreme Court, and have the <span class="caps">DMCA</span> deemed unconstitutional and overturned.</p><img src="" height="1" width="1"/> Coda 2007-04-24T00:00:00-07:00 <p style="float:right;"><img src="" alt="" /></p> <p>So, <a href="">Coda</a> is out and it has been pretty well received. For good reason. It’s a very elegant-looking app, with nice touches all over the place. Panic really knows how to exploit the look and feel of OS X and the core technologies beneath. Put simply: it oozes Mac goodness from every corner.</p> <p>I want to use it, I really do. However. I don’t need it.</p> <p>You see, ever since I switched from <span class="caps">PHP</span> to Rails I only touch the server for <a href="">little increments</a> at a time, and no longer work directly on it (man, those were[n’t] the days!) Even when developing comps from Photoshop to <span class="caps">XHTML</span>/<span class="caps">CSS</span>, I mainly stay within my <a href="">current editor</a> and switch back and forth between <a href="">Webkit</a>.</p> <p>(As an aside, I really like the bundled Panic Sans font. Appears to be some variation of Bitstream Vera Mono, possibly with the underscores tweaked.)</p><img src="" height="1" width="1"/> Rails Scalability Problems Solved 2007-04-23T00:00:00-07:00 <p>So all <a href="">this</a> <a href="">talk</a> about Rails (not) <a href="">scaling</a> got me thinking. If the database is the next bottleneck after you’ve beefed up your pack of Mongrels, just remove it—and replace it with Twitter!</p> <p>That’s right. A Twitter-based ActiveRecord store.</p> <p>I expect the plugin to work something like this:</p> <pre> development: adapter: mysql database: sockr_development username: root password: host: localhost test: adapter: mysql database: sockr_test username: root password: host: localhost production: adapter: twitter username: sockr_production password: web2point0h </pre> <p>(Note here how I’m still using a traditional <span class="caps">RDBMS</span> for development and test environments. Kicking in Twitter here would be quite silly, as we don’t need the scalability for just our local user as we’re developing. We really need it for production!)</p> <p>That’s it! The plugin would take care of marshaling your ActiveRecord objects into 140 byte chunks and sending it off to Twitter HQ for cold storage.</p> <p>Keep your eyes peeled for the plugin, coming soon!</p><img src="" height="1" width="1"/> When To Say Yes to Feature Requests 2007-03-19T00:00:00-07:00 <p>As the only web developer for a small company, I get a lot feature requests for our apps and because time is limited (for everyone) I have to prioritize these requests. My job sure would be easier if I could <a href="">just say no to everyone</a> but management probably wouldn’t have much of a use for me after awhile. So we need some rationale for turning one down and giving the other the thumbs up.</p> <p>Here’s my little rule of thumb:</p> <pre> (time savings per day/time to implement) * number of users </pre> <p>or if you like terse variable names,</p> <pre> s/i * u </pre> <h3>Case I: The Quick Win</h3> <p>Bob spends about 30 minutes a day sorting through a list of orders, paginating through and selecting ones that match a given range. He submits a request:</p> <blockquote> <p>“Kevin, it’d be great if I could use the existing search tool to search for a range of order numbers.”</p> </blockquote> <p>A quick estimate yields about 15 minutes for writing a few test cases, and coding up the feature. We have all the variables we need, so lets fill in our equation, sticking to hours:</p> <pre> (.5/0.25) * 1 = 2 </pre> <p>Hmm, seems sort of arbitrary. We’ll leave this on the whiteboard, and tell Bob we’ll get back to him.</p> <h3>Case II: Productivity, Multiplied (or divided)</h3> <p>Just then, Sue comes in:</p> <blockquote> <p>“Kevin, the other 4 customer service representatives and I are spending about 2 hours every day handling orders with invalid credit card numbers. Could we give our customers some more information during checkout if their card was rejected? It sure would reduce our call volume.”</p> </blockquote> <p>Adding some more validation and error handling to the order processing steps would take a couple hours, but it looks like it would save 5 CSR’s 2 hours every day. How does this fill into our equation?</p> <pre> (2/2) * 5 = 5 </pre> <p>We can see right away this looks like a huge difference, keeping in mind of course that it’s just a rule of thumb.</p> <p>While it isn’t a hard and fast rule (I don’t think you could come up rules like “< x = no” and “> y = yes”) I’ve found this technique can help prioritize requests in a way that your users can appreciate. It also forces your users to think a little about how much time they really spend doing things, and how much time it takes you to do your job.</p><img src="" height="1" width="1"/> dotfiles.org Now Has Search 2007-02-06T00:00:00-08:00 <p>I’m pleased to announce <a href="">dotfiles.org</a> now has search capabilities. This feature was born out of my desire to quickly see common features in everyone’s dotfiles, specifically <a href="">shell aliases</a>. That being said, matching lines from each dotfile will be displayed one right after the other.</p> <p>Give it a try and if you haven’t yet signed up, <a href="">go ahead and do so</a>. It’s free!</p><img src="" height="1" width="1"/> reddit, digg, and Slashdot 2007-01-30T00:00:00-08:00 <ul> <li>reddit: for computer science students</li> <li>digg: for computer science drop-outs</li> <li>Slashdot: for computer science graduates, circa 1980</li> </ul><img src="" height="1" width="1"/> Best of 2006 Playlist 2006-12-31T00:00:00-08:00 <p>I had a great time listening to my favorite releases of 2006, as defined by this smart playlist:</p> <pre> Match [all]: * Year is 2006 * My Rating is > 2 </pre> <ol> <li>John Mayer – Stop This Train</li> <li>John Mayer – The Heart Of Life</li> <li>John Mayer – Vultures</li> <li>John Mayer – Gravity</li> <li>Teddy Geiger – Look Where We Are Now</li> <li>Teddy Geiger – Thinking Underage</li> <li>Daniel Powter – Bad Day</li> <li>Jewel – Again And Again</li> <li>Guster – Empire State</li> <li>Corinne Bailey Rae – Put Your Records On</li> <li>John Mayer – Waiting On The World To Change</li> <li>John Mayer – In Repair</li> <li>John Mayer – Slow Dancing In A Burning Room</li> <li>John Mayer – Belief</li> <li>John Mayer – I’m Gonna Find Another You</li> <li>John Mayer – I Don’t Trust Myself (With Loving You)</li> <li>Teddy Geiger – For You I Will (Confidence)</li> <li>Teddy Geiger – Love Is A Marathon</li> <li>Teddy Geiger – Try Too Hard</li> <li>Gnarls Barkley – Crazy</li> <li>Jewel – Good Day</li> <li>Chris Thile – Wayside Back In Time</li> <li>Daniel Powter – Song 6</li> <li>Jewel – Goodbye Alice In Wonderland</li> <li>Amos Lee – supply and demand</li> <li>The Click Five – Just The Girl</li> <li>Guster – Lightning Rod</li> <li>Jewel – Stephenville, TX</li> <li>Sanctus Real – Fly</li> <li>Sheryl Crow – Real Gone</li> <li>Train – Explanation</li> <li>Chris Thile – You’re An Angel, And I’m Gonna Cry</li> <li>Katharine McPhee – Somewhere Over The Rainbow</li> <li>Keane – Nothing In My Way</li> <li>Train – Cab</li> <li>Daniel Powter – Lie To Me</li> <li>Guster – Dear Valentine</li> <li>Thom Yorke – The Eraser</li> <li>Train – Always Remember</li> <li>Ben Kweller – Thirteen</li> <li>Ben Kweller – This Is War</li> <li>Kate Havnevik – New Day</li> <li>Train – Shelter Me</li> <li>Ben Folds – Still</li> <li>Hellogoodbye – Here (In Your Arms)</li> <li>The Knife – Silent Shout</li> <li>Ray LaMontagne – Empty</li> <li>James Taylor – Jingle Bells</li> </ol> <p>I think I’ll make it a New Years Eve tradition!</p><img src="" height="1" width="1"/> My Dream App 2006-12-28T00:00:00-08:00 <p>No, not <a href="">that</a> dream app, but <em>mine</em>.</p> <p>I’d like an app that I can use to document my computing experiences. You know, like when I’m on a <a href="">Safari</a>.</p> <p>I currently do this with screenshots that automatically get uploaded to Flickr and tagged ‘screenshot’ and/or del.icio.us. However, I’d just like one button that I push, and a svelte <span class="caps">HUD</span> pops up, asks me for some tags and maybe a description, then pushes it up on the web somewhere. If I’m on a webpage, it’ll cache the site’s text (which I can then search), take a screenshot and then get out of the way.</p> <p>Paul uses screenshots and Keynote, but that doesn’t work so well with multiple computers… and I don’t like the idea of accumulating 200 MiB files.</p> <p>(Hmmm, maybe this is <a href="">rediscovr</a>?)</p> <p><strong>Update:</strong></p> <p style="text-align:center;"><img src="" alt="" /></p><img src="" height="1" width="1"/> Junebug and Nginx 2006-11-15T00:00:00-08:00 <p>So I came across <a href="">Junebug</a> today, which is a slick wiki engine that harnesses the power of <a href="">Camping</a> and gives you a nice-looking wiki that’s contained in one directory.</p> <p>Here’s what I did to get it setup and running and proxied through nginx:</p> <p>1. Install <a href="">Junebug</a> (you’ll need Ruby Gems for this to work):<br /> <br /> <pre>$ sudo gem install junebug</pre></p> <p>2. Create the wiki:<br /> <br /> <pre>$ junebug wiki</pre></p> <p>3. Edit the config.yml file’s <code>url</code> and <code>feed</code> parameters to the location we’ll proxy it to, say <code></code></p> <p>4. Edit your nginx.conf and add the following entries:<br /> <pre><br /> upstream junebug {<br /> server 127.0.0.1:3301;<br /> }</p> <p>location /wiki {<br /> proxy_pass;<br /> proxy_redirect off;<br /> proxy_set_header Host $host;<br /> }</p> <p>location /wiki/static { <br /> root /home/kmarsh;<br /> }</pre></p> <p>5. Fire it up!: <code>./wiki start</code> (this daemonizes automatically)</p> <p>6. Restart nginx (send it <span class="caps">HUP</span> <code>kill -HUP [nginx pid]</code>)</p> <p>7. Visit your wiki at the <span class="caps">URL</span> you specified above, maybe</p><img src="" height="1" width="1"/> Toward a more Republic Democracy 2006-10-25T00:00:00-07:00 <p>The House of Representatives (and to a lesser extent, the Senate) were established out of the desire for the nation to be led by the people; realizing that not everyone could travel to the capital on a regular basis and voice their opinions.</p> <p>So the founding fathers setup a republic, where citizens vote once a year for representatives that share the same ideals as them. Which is usually (poorly) determined by party affiliation.</p> <p>However, how do we know that who we elect are actually voting in our favor? And, more importantly, how do our elected representatives know how their constituents would vote?</p> <p>As a web developer, I am always looking for ways in which the web can be used to improve our lives. Here is one such way:</p> <ul> <li>A list of upcoming issues before the House could be put on the Representative’s website;</li> <li>constituents could log in and cast a vote for each issue as if they were before the House themselves;</li> <li>a Representative could log in and see a tally of the votes so far for each issue. They would then take this to Congress, armed with the opinions of their constituents.</li> </ul> <p>This also makes election time much easier. Rather than listening to party-incited backbiting and dirt-digging, you would know that you differ on, for example, 89% of the issues in the previous term and, in this case, it might be time to vote for a candidate whose opinions are more aligned with yours.</p> <p>Because after all, shouldn’t a government <a href="">“of the people, by the people, and for the people”</a> include more of the peoples’ opinions?</p><img src="" height="1" width="1"/> Dotfiles 2006-10-21T00:00:00-07:00 <p>I’m proud to announce the grand opening of <a href="">dotfiles.org</a>!</p> <p>From the site’s homepage:</p> <blockquote> <p>dotfiles.org is a place to upload, share, and synchronize your dotfiles.</p> </blockquote> <p>If you don’t know what a dotfile is, you probably don’t need it. And if you don’t know, <a href="">learn up</a>!</p> <p>It’s my first app written in <a href="">Camping</a>, which has been a trip I’m confident to say I hope I’ll take again.</p><img src="" height="1" width="1"/> Mephisto 2006-10-16T00:00:00-07:00 <p>It’s official, this blog is now running <a href="">Mephisto</a>!</p> <p>There a few bugs and things missing, which’ll get cleaned up in due time.</p> <p>Also, feeds have now been moved to FeedBurner:</p> <pre></pre> <p>Update (or subscribe!) today!</p><img src="" height="1" width="1"/> Tab-completion for Ruby Cheat Sheets 2006-10-15T00:00:00-07:00 <p>Add this to your <code>.bashrc</code> or <code>.bash_profile</code> file:</p> <pre>complete -W "$(cheat sheets | egrep '^ ' | awk {'print $1'})" cheat</pre><img src="" height="1" width="1"/> Bracket accessors for your Rails models 2006-10-11T00:00:00-07:00 <p>Here’s an interesting hack. Tag this on the end of <code>environment.rb</code>:</p> <pre> module ActiveRecord class Base def self.[](id) self.find(id) end end end </pre> <p>Now you can do fun things like:</p> <pre>>> Person[1] => #<Person:0x23c7a00 @attributes={"name"=>"Alice", "id"=>"1"}> >> Person[1].name => "Alice"</pre> <p>Which is equivalent to:</p> <pre>>> Person.find(1) => #<Person:0x23c7a00 @attributes={"name"=>"Alice", "id"=>"1"}> >> Person.find(1).name => "Alice"</pre> <p>…but far cooler.</p> <p>In other news, I really need to upgrade to Mephisto – just as soon as they add <span class="caps">XML</span>-<span class="caps">RPC</span> support.</p><img src="" height="1" width="1"/> iTunes Visual Refresh 2006-09-12T00:00:00-07:00 <p>iTunes 7, released today, sports some new UI tweaks (cf. <a href="">source list preview</a>). Now, being one for consistency, I have to believe the rest of Aqua will change along with it (right? right!?), but it’s odd we didn’t see anything different in the latest Leopard preview. Although, iTunes has consistently been the earliest adopter of most UI trends.</p> <p>While I haven’t seen the new UI enough yet to gauge whether or not I like it, I hope this isn’t just another “visual fork” but rather a preview of a new, consistent look for OS X.</p> <p>(Oh, and I hope Apple hired or gave the author of <a href="">CoverFlow</a> some cash for integrating his app—including the name—into iTunes proper.)</p><img src="" height="1" width="1"/> Ruby Web Fetching Options Benchmarked 2006-08-19T00:00:00-07:00 <p>My latest project requires a web crawler of sorts (technically, it just needs to grab the <span class="caps">HTML</span> and index it, not following any links), so fetching web pages very fast will be important. I’ve whipped up a quick script using stdlib’s <a href="">Benchmark</a> to pit several options against each other: <a href="">open-uri</a>, <a href="">rio</a>, <a href="">net/http</a>, and Zed Shaw’s <a href="">RFuzz</a>. (If I’m leaving any out, please let me know.)</p> <h3>The Test</h3> <p>Briefly, the test fetches the Google search results for <a href="">testing</a> 5 times each.</p> <h3>The Results</h3> <pre> user system total real RFuzz 0.010000 0.000000 0.010000 ( 2.486962) net/http 0.040000 0.020000 0.060000 ( 2.880106) open-uri 0.070000 0.040000 0.110000 ( 3.203510) rio 0.140000 0.060000 0.200000 ( 3.674174)</pre> <h3>Conclusion</h3> <p>It appears as though RFuzz cranks through <span class="caps">HTTP</span> the fastest, with net/http coming in a close second. It appears as through both open-uri’s and rio’s prettiness in syntax also slows them down quite a bit earning them 3rd and 4th place, respectively.</p><img src="" height="1" width="1"/> Terra got the bat! 2006-07-31T00:00:00-07:00 <div style="text-align: center;"><a href=""><img src="" /></a></div> <p>(The photo not mine, but found on Flickr. It pretty much looked like that, though.)</p><img src="" height="1" width="1"/> Wireless Mighty Mouse Observations 2006-07-28T00:00:00-07:00 <div style="float: right; padding-left: 5px; padding-bottom: 5px;"><a href="" title="Photo Sharing"><img src="" width="240" height="164" alt="Wireless Mighty Mouse Shut-eye" /></a></div> <p>The <span class="caps">UPS</span> man just came today and delivered my new Wireless Mighty Mouse (I know, I know… it’s pricey for a mouse but I still had the $50 iPod Settlement promo code kicking around). Here are some observations:</p> <ul> <li>The On-Off switch is merely a shutter to the laser, pretty clever!</li> <li>Two AA batteries are included</li> <li>The included software was a required install, even on Mac OS X 10.4.7</li> <li>It’s quite a bit heavier than the wired Mighty Mouse, due to the batteries (duh)</li> <li>You can choose to include one or two batteries at a time</li> <li>There is a nice battery level gauge in the Bluetooth tab of the Keyboard and Mouse System Preferences panel</li> <li>I think it samples less frequently than the wired version, as mousing seems to stutter ever-so-slightly. This has the potential to get very annoying!</li> <li>The new software adds a slick Zoom feature, wherein holding a modifier key while scrolling with the ball will actually zoom the screen in. Problem is, it’s pretty disorienting and doesn’t really work all that well, but it just might take some practice.</li> <li>The two side buttons are equally as annoying as the original Mighty Mouse. Their hard pressing requirement coupled with little tactile feedback render them practically unusable.</li> <li>It’s nice not having to deal with the (too) short cord, especially with my MacBook</li> <li>The laser will track on my glass-topped wooden desk, unlike the optical</li> <li>No more <span class="caps">LED</span> means no more <a href="">weird mouse-like projection</a></li> </ul><img src="" height="1" width="1"/> Dead Simple Full-text Searching with Rails 2006-07-17T00:00:00-07:00 <p>Using MySQL’s built-in <span class="caps">FULLTEXT</span> searching capabilities, you can add full-text searching to your Rails app’s pretty easily. It’s not quite as sexy as <a href="">acts_as_searchable</a> but implementation is pretty trivial and no dependencies are required. One caveat: your tables need to be MyISAM.</p> <p>First, make sure you add a <span class="caps">FULLTEXT</span> index to your MySQL table like so:</p> <pre>ALTER TABLE articles ADD FULLTEXT (title, content);</pre> <p>Then, just use ActiveRecord’s <code>find()</code> method, but pass in a <code>:conditions</code> parameter:</p> <pre>@articles = Article.find(:all, :conditions => ['MATCH(title, content) AGAINST (?)', params[:query]])</pre><img src="" height="1" width="1"/> Clickity Clack--whine--Clickity Clack 2006-07-13T00:00:00-07:00 <p>So I’ve just confirmed that my MacBook exudes similar whining problems as the MacBook Pro. The whine’s pitch varies with <span class="caps">CPU</span> usage, such as scrolling or dragging windows.</p> <p><del>Solution</del> Hack: Turn off the second core using the Processor System Preference panel.</p> <p>Now I just have the clickity-clack sound of my vintage Apple Extended II keyboard (oh, and only one core).</p><img src="" height="1" width="1"/> BarnRaisr and Knowledge Markets 2006-06-26T00:00:00-07:00 <p>This idea comes from two separate events at <a href="">RailsConf</a>: a conversation and a keynote.</p> <p>A conversation at <a href="">RailsConf</a> started up between a group sitting at a table, some of which turned out to be pretty knowledgeable on the subject of <a href="">knowledge markets</a>. The gentleman sitting next to me (forgive me, I didn’t catch your name!) brought up a good point about the idea of collective knowledge markets and the opportunity for people to “game the system” if there was any personal benefit involved.</p> <p>Another RailsConf extraction, if you will, is <a href="">BarnRaisr</a> (which is another testament to this community: a call to action was made during <a href="">Nathaniel Talbott</a> ‘s RailsConf 2006 talk _Homesteading: A Thriver’s Guide_ and someone came up with a name and site less than a day later). The basic idea is this: present a project and have members of the community help it along by contributing testing, coding, design, and time to help this idea along.</p> <p>On the ride home, these two separate ideas came together: when enough code and hours start to be volunteered on projects you suddenly have a decent indicator of the merit of a particular idea. People “game” the system by committing hours and hard work to the project, which I think anyone would agree is a pretty good thing.</p><img src="" height="1" width="1"/> RailsConf 2006-06-23T00:00:00-07:00 <p>Live from RailsConf… no real content to offer, just bragging.</p><img src="" height="1" width="1"/> RSS Aggregation 2006-06-20T00:00:00-07:00 <p>After years and years of manually checking each of my 75 or so favorite websites for updates I’ve decided to give an <span class="caps">RSS</span> aggregator a shot.</p> <p>I’ve tried several in the past, namely <a href="">NewsFire</a> and NetNewsWire, but I’ve always felt like they robbed me of the ‘experience’ of visiting a website.</p> <p>A lot of the sites I frequent are design related and naturally have quite exquisite designs (cf. <a href="">Bartelme Design</a> and <a href="">Maniacal Rage</a>, among others). Why would I want to forgo this pleasant viewing experience and have all the updates shown to me in a homogenized container? Mostly ’cause its easier.</p> <p>I’m currently using <a href="">NetNewsWire Lite</a> to track about 100 feeds which is, so far, working well. I credit most of my pleasant experience to its NewsGator synchronization (which actually works!), which is a must-have feature for someone with a home and work Mac or desktop and portable Mac.</p><img src="" height="1" width="1"/> TextMate and WordPress 2006-06-20T00:00:00-07:00 <p><a href="'s">TextMate</a> latest new feature, the Blogging bundle, has prompted me to (finally) ditch TextPattern and switch to a blogging package with better <span class="caps">XML</span>-<span class="caps">RPC</span> support. So here we are: Kevin Marsh on <a href="">WordPress</a>!</p> <p>Stuff is still a bit… <em>broken</em>. But on the plus side, comments now work! And we have search.</p><img src="" height="1" width="1"/> January!? 2006-05-08T00:00:00-07:00 <p>That can’t be right…</p><img src="" height="1" width="1"/> Everything old is new again, or, Embrace and extend 2006-01-06T00:00:00-08:00 <p>So, Microsoft has released some more details of what they have in store for Vista. Let’s do a quick rundown of the features, shall we? I think I’ve seen them somewhere before…</p> <p>Let’s start off with the major features, <a href="">as listed here</a>, and work our way down (because of some lame Javascript on the page, I can’t directly link to each section.)</p> <ul> <li><strong>Virtual Folders</strong>, looks like a Smart Folder to me</li> <li><strong>Quick Search</strong>, find anything right from a unified search bar! Oh yeah… Apple did something like this in Tiger… I think it was called Spotlight. Next!</li> <li><strong>Aero</strong>, use the <span class="caps">GPU</span> to render fancy graphical <span class="caps">GUI</span> elements! Oh yeah… Apple did something like this in Tiger… pretty sure it was called Quartz (Extreme)</li> <li><strong>Live taskbar thumbnails</strong>, previews of minimized windows while hovering over their icon in the taskbar. Looks pretty similar to the Dock’s minimized windows to me, but the Dock’s are visible even if you don’t hover over them (read: more than one at a time)</li> <li><strong>Windows Flip</strong> and <strong>Windows Flip 3D</strong>… use the awesome power of Aero to show each window all at once, so you can pick from a miniaturized version rather than just an icon. Hey! I know this one. Exposé!</li> </ul> <p>Let’s move on to Security, surely Microsoft has done something innovative here, I mean… Microsoft is known for great security, right? Right?</p> <ul> <li><strong>User Account Control (<span class="caps">UAC</span>)</strong>, so basically while using a “normal” account and doing something that requires administrative privileges, a box will pop up asking for the administrator password. Uuuh, OS X has been doing this forever.</li> <li>Better protection from malware, ok… so we got <strong>Automatic Updates</strong> (should be standard for any operating environment), <strong>firewall</strong>, <strong>Windows Defender</strong> and the <strong>Malicious Software Removal Tool</strong> (OK, I’ll admit… OS X does not have the Malicious Software Removal Tool. But, in its defense, it does not require it either.)</li> </ul> <p>How about Internet Explorer? Surely there is some room for some innovative improvements, no? Hey, where ya going? Come back…</p> <ul> <li><strong>Tabbed browsing</strong>, just like we’ve seen in Firefox and Safari for years</li> <li><strong>Built-in <span class="caps">RSS</span> reader</strong>, more catching up to Firefox and Safari…</li> <li><strong>Live Preview</strong> view tab’s contents in a thumbnail preview, just like <a href="">Omniweb</a>!</li> </ul> <p>At this point, it’s getting pretty ridiculous, but I trudge on…</p> <ul> <li><strong>Gadgets and Sidebar</strong>, ya know… small applications that connect to the web and a place to put said apps. Just like Widgets and Dashboard… But—the Sidebar <em>will</em> take up about 20% of the side of your screen! Even when you don’t want it…</li> <li><strong>Windows Calendar</strong>, ok… the thing that gets me about this one is the rounded event box. Totally screams iCal ripoff. But you can share calendars! Ya know, like iCal.</li> <li><strong>Windows Photo Gallery</strong> iPhoto.</li> <li><strong>Windows Movie Maker</strong> iMovie.</li> </ul> <p>Performance is an area where I’m sure we having something of merit… Really.</p> <ul> <li><strong>Sleep</strong> Damnit. Guess not.</li> <li><strong>SuperFetch</strong>, ya know. Memory caching. Like any modern operating system has done for the past, 10 years.</li> <li><strong>External memory devices</strong>, cool! Now I can connect a <span class="caps">USB</span> flash drive and have it add to my system memory! Except it will be about 15% of the speed…</li> </ul> <p><strong>Windows Backup</strong> and <strong>System Restore</strong>… nothing new to see here, either.</p> <p>In short, Vista is nothing but a late facsimile of Tiger. Some features are a bit more obscure, while others are glaring and its really unnerving how Microsoft can get away with it.</p> <p>Embrace, yes. Extend? Not so much.</p><img src="" height="1" width="1"/> New Features Galore! 2006-01-05T00:00:00-08:00 <p>After realizing I spend entirely too much time neglecting this site, I’ve worked a bit over the past couple days to add:</p> <ul> <li><a href="">Flickr</a> integration, in the <a href="gallery/">Gallery</a> (which prompted me to become a Flickr pro member, too)</li> <li>Last 3 pictures from the Treo on the right (it’s pretty amazing that in 1 minute and 20 seconds I can snap a picture and have it show up here!)</li> <li>del.icio.us integration, in the <a href="links/">Links</a> section</li> <li>Updated <a href="resume/">résumé</a> to reflect my new job and to sound not as needy</li> <li>Updated the <a href="portfolio/">Portfolio</a></li> <li>Various markup changes to make the site plumb with <span class="caps">XHTML</span> standards (what a shame to link to the validator and have it not even give you the green light!)</li> <li>Updated the <span class="caps">RSS</span> feed icon to the new <a href="">standard</a></li> <li>Re-discovered love for <a href="">TextPattern</a></li> </ul><img src="" height="1" width="1"/> Commenting Fixed 2006-01-02T00:00:00-08:00 <p>D’oh! So <em>that’s</em> why I haven’t been getting many comments lately. Here I thought it was just because no one visited me…</p><img src="" height="1" width="1"/> Creating Mobile or Lite Versions of Rails Apps 2005-11-05T00:00:00-08:00 <p>For my latest web project using Ruby on Rails, the idea of a mobile version arose.</p> <p>Is it worth it? Well, how much more code would I have to write? 1,000 lines? Pages? Try 10. That’s right: 10.</p> <p>Here’s the magic, first add the lines around the Mobile/lite version bit to <code>config/routes.rb</code>:</p> <pre> ActionController::Routing::Routes.draw do |map| # Default page is the dashboard map.connect '', :controller => "dashboard", :action => 'show' # Mobile/lite version map.connect ':mobile/', :controller => "dashboard", :action => 'show' map.connect ':mobile/:controller/:action/:id' # Install the default route as the lowest priority. map.connect ':controller/:action/:id' end </pre> <p>Then edit <code>app/controllers/application.rb</code>:</p> <pre> require_dependency "login_system" class ApplicationController < ActionController::Base include LoginSystem helper :debug helper :date_picker layout :determine_layout private def determine_layout if @params[:mobile] "mobile" else "application" end end end </pre> <p>And finally, create <code>app/views/layouts/mobile.rhtml</code></p> <pre> <%= yield %> </pre> <p>Surf on over to <code>yourserver/yourapp/mobile/</code> And voila! You have a lite version of your site perfect for viewing on a smartphone or <span class="caps">PDA</span>. As a bonus, when you start using a mobile page, your preference will “stick” and follow you, thanks to Rail’s routing.</p><img src="" height="1" width="1"/> How to Succeed In The Web 2.0 Days 2005-08-18T00:00:00-07:00 <p>It’s easy, <em>really</em>, to have a successful web app these days. Just follow these easy steps* and you too will be on your way to fame and fortune:</p> <ol> <li>Think of <strong>one</strong> function that doesn’t already have a web interface. Anything. How about a web inventory of your socks?</li> <li>Register a hip <a href="">ccTLD</a> from another country in combination with a subdomain., for instance?</li> <li>Write your app using Ruby on Rails</li> <li>Have a clean, efficient design, don’t forget huge text input boxes</li> <li>Don’t forget Ajax! You’ll need lots of script.aculo.us effects all over. Drag and drop icons of socks to a laundry bin perhaps?</li> <li>Weeks, nay, months before your app launches, offer a teaser page that allows folks to enter their e-mail address to be notified when the app launches. Don’t forget to remind them that you won’t tell their info, cause you’re a nice company ;)</li> <li>Weeks before your app ships, pick a few e-mails from the list and invite them to beta test. If they provide useful feedback, give them a discount when you launch</li> <li>Offer a tiered subscription model, but it is imperative that the first tier be a free trial. For free you can track 20 socks (10 pair), but pay just $4 a month and track 100 socks (50 pair), $7 a month will let you inventory 1000 socks (500 pair)… what a great value!</li> </ol> <p>*Dramatization: Individual results may vary.</p><img src="" height="1" width="1"/> Ajax on the Desktop 2005-08-14T00:00:00-07:00 <p>Ajax is making great strides in bringing desktop-like, low latency apps to the browser. What if we take it all the way and bring Ajax to the desktop? Nay, <em>make it the desktop</em>. The next logical step for Ajax, the Web, and computing is the so-called “Web OS.”</p> <p>The Web OS would be an extremely stripped down kernel (i.e., Linux) simply running a web browser (i.e., Firefox) in full screen mode.</p> <p>The traditional “start page” is becomes your desktop. The web page would be customized much like your Start or Apple menu to load pre-defined shortcuts (i.e., Webmail, or even another browser). You could even run things like word processors or <a href="">spreadsheets</a>, without the fear of being without your data when you travel.</p> <p>Think about it: all of your “desktop’s” settings are stored on a central server (ahem, Google), making data accessible from anywhere. If you are using a machine without the OS, a web browser would suffice to access the same data in the same way (ala <span class="caps">VNC</span>.)</p> <p>From a development standpoint, it gets even better. You no longer have to worry about users performing (or not performing) software updates because updates to the code are seen in real time. Versions are thrown out the window because everyone is using the latest version (no more “Have you updated to 2.0 yet?”) Simple bug fixes can be performed with no hassle in shipping another product.</p> <p>So who wants to start?</p> <p><strong>10/2/2005: Update:</strong> It’s <a href="">here</a>.</p><img src="" height="1" width="1"/> Don't Compare Ruby on Rails with PHP 2005-08-03T00:00:00-07:00 <p>I’ve made this mistake myself on many occasions but it recently dawned on me: comparing Ruby on Rails with <span class="caps">PHP</span> is impossible, because <span class="caps">PHP</span> is not an <em>application framework</em> but a <em>scripting language</em>. If you want to compare anything to <span class="caps">PHP</span>, compare it to Ruby.</p> <p>With Rails you have Active Record, Action View and all these other cool technologies and with <span class="caps">PHP</span> you have <code>mysql_connect()</code> and <code>echo</code>. With <span class="caps">PHP</span>, you have to write code for all the heavy lifting yourself. Rails does it for you.</p> <p>That was a big draw for me coming from <span class="caps">PHP</span> where for each app you have to write <em>another</em> form-verification script or try to integrate a previous one with your new app. This stuff tends to get tedius after awhile and draws you away from more important stuff like, you know, UI design, usability, thinking about your data, and <em>actually creating the app</em>.</p><img src="" height="1" width="1"/> On Presenting Software 2005-07-29T00:00:00-07:00 <p>Today, I had my first ‘Steve Jobs’ moment: I presented software I wrote to an actual audience, keynote-style, complete with water bottle (but sans black turtleneck.)</p> <p>It was an awesome experience and I learned a lot about presenting.</p> <p>You have to take a real sense of pride in your work when you present it, but not too much so you don’t come off as being full of yourself. It also takes a lot of faith working with a <em>live</em> copy, hoping everything works as it should. But everything went smoothly and I think I impressed a few in the audience (one of which requested I present to a larger group soon.)</p><img src="" height="1" width="1"/> Site Fixes 2005-07-19T00:00:00-07:00 <p>Well, it’s been a long time since I’ve given this any attention. I finally fixed some nagging issues with this blog related to a Textpattern upgrade, so you can go back to viewing nothing (relatively) bug free. :x</p><img src="" height="1" width="1"/> Unix Geeks Wanted! 2005-04-20T00:00:00-07:00 <p>I’m excited to announce I am starting a new project. It’s still in the early phases but I need your help! If you would consider yourself a “Unix-geek” (this includes Mac OS X users) and would like to help beta test, please either comment here or <a href="mailto:kevin@kevinmarsh.com">e-mail me</a>. Thanks.</p><img src="" height="1" width="1"/> Tiger: April 29th 2005-04-12T00:00:00-07:00 <p>Apple officially announced Tiger’s release date: April 29, 2005. Yay!</p> <p>They’ve also updated their <a href="">Mac OS X</a> page with spiffy Tiger graphics and content.</p> <p>From the <a href="">new features</a> page, things I’m most looking forward to:</p> <ul> <li>Spotlight (even across network shares!, <span class="caps">CLI</span> tools)</li> <li>Dashboard</li> <li>Quartz Composer</li> <li>Xcode 2</li> <li>Finder Slideshow (slideshows from selected images directly within Finder)</li> <li>Smart Folders, Smart Contacts, Smart Mailboxes (Smart-anything, really)</li> <li>Birthday Calendar</li> <li>iChat (Buddy Groups, multiple accounts)</li> <li>WebDAV improvements (Kerberos-enabled)</li> <li>Preview (<span class="caps">PDF</span> forms, slideshow)</li> <li>Quicktime 7</li> <li>Safari <span class="caps">RSS</span> (<span class="caps">RSS</span> reader, web-page archiving, inline <span class="caps">PDF</span> viewing</li> <li>Safe Launch (re-launch after a crash)</li> <li>Automator</li> <li><span class="caps">RSS</span> Visualizer Screen Saver</li> <li>New default desktop (looks very similiar to Panther’s, which isn’t all bad)</li> <li>Access Control Lists (<span class="caps">ACL</span>)</li> <li>Remappable Modifier Keys (“Remap modifiers such as control and caps lock to be super elite.”)</li> </ul> <p>In short, a lot.</p><img src="" height="1" width="1"/> Rails Tip: Plan your Database 2005-04-11T00:00:00-07:00 <p>This is probably obvious to most of you, but if you’re coming from a <span class="caps">PHP</span> background to Rails, you probably don’t know much about database structure (or think its something you can make up on the fly).</p> <p>With Rails, its extremely important to plan out your database structure before you start coding. But the good thing about Rails is its language is simple to understand. <code>has_one</code>, <code>belongs_to</code> and such.</p> <p>Taking time to think about your data models will save you tons of time down the road.</p><img src="" height="1" width="1"/> RubyOnRails 2005-04-09T00:00:00-07:00 <p>I’ve jumped on the RubyOnRails bandwagon by starting to write a simple app.</p> <p>I’m just getting started, but it seems very nice thus far. It solves some of the problems (ok, not really problems… pet peeves) I have with web development using <span class="caps">PHP</span>.</p> <p>The big one is forms. They are essential to any web app and they are such a <span class="caps">PITA</span> to code properly. Especially validation. The great thing about Rails is this is all done for you, so setting up a validation rule in your data model scales all the way down to form submission. Its smooth.</p> <p>Updates forthcoming.</p><img src="" height="1" width="1"/> Frustration 2005-03-16T00:00:00-08:00 <p>I don’t know how all the beer-guzzling, pot-smoking frat boys do it.</p><img src="" height="1" width="1"/> Free Cheat Sheets 2005-02-01T00:00:00-08:00 <p>While searching for a good LaTeX cheat sheet I came across <a href="">this gem</a> made in, you guessed it, LaTeX and available in <span class="caps">PDF</span> format. It is 3-column, and meant to be printed double-sided.</p> <p>When I needed to make cheat sheets for my <a href="pdf/cheat-sheet-physics.pdf">Physics</a> and <a href="pdf/cheat-sheet-algorithms.pdf">Algorithms</a> exams, I used <a href="">Mr. Chang’s LaTeX sourcecode</a> with, what I think are pretty good results.</p> <p>Then I stumbled upon even more cheat sheets in a similar style, for topics varying from <a href="">C</a> to <a href="">Vim</a> and even <a href="">LaTeX</a> itself.</p> <p>A great exercise in information density. I wish I had the time to do one of these for every course I take. They’re also a great alternative to the <a href="">expensive sheets</a> you can find in your college’s bookstore.</p> <p>In the spirit of open source, I plan to release the source to my humble cheat sheets and see what others can do.</p> <p><strong>Update:</strong> After posting this, I discovered <a href="">refcards.com</a> and <a href="">this site</a>, two great resources for these so-called cheat sheets.</p><img src="" height="1" width="1"/> Waiting for the Bus 2005-01-24T00:00:00-08:00 <p>At 1:30, a half-an-hour before my circuits class starts at Nitschke Hall, I head over to the Student Union bus loop to catch the Blue Loop to Engineering as I’ve done for the past two weeks now. The wait is longer than normal, but I am marginally earlier. Fifteen minutes later, no bus. The waiting area is filling up. In The Waiting Line by Zero 7 plays on the iPod, how apropos. Another 10 minutes passes.</p> <p>Now 1:55, five minutes before class, the bus arrives. I venture into the blistering cold to join the ranks waiting to board the bus. I’m toward the end of the line and after a quick gauge of the line it appears as though I’ll be lucky to get a seat. The riders get off the bus and the line starts to move.</p> <p>The bus quickly fills and by the time I’m on it, there are 5 or so people standing, holding onto the rails for stability. I join them and find a spot to grip the bars. The bus departs and I try hard to keep holding on and not hit anyone sitting around me. How easy the ride seems for them.</p> <p>Several stops pass, the load getting smaller each time as people get off. We get to the Transportation Center and everyone except for me gets off. I take a seat.</p> <p>The bus loops around the Transportation Center and instead of heading left for Nitschke, it turns right. Right back to the path we just traveled, back to the Student Union. Back to where I had been waiting to leave from. 2:05: I am late to class.</p> <p>2:15, the bus finally arrives back at the Union. I get up to leave, acknowledge the odd look from the driver who is wondering why I took a joyride around campus, and get off. I forget about showing up late to class and just don’t show up at all.</p> <p>Then it hits me. What if, after waiting all this time for the bus I was so sure was going where I wanted it to, doesn’t? Even worse, what if it just takes me back to where I started?</p><img src="" height="1" width="1"/> Slacking 2005-01-21T00:00:00-08:00 <p>Another year begins, and its been almost 2 months since this has been updated. I’m such a slacker.</p> <p>I guess I don’t have anything interesting to say… I don’t want to bore you with self-serving “I did this, then that, then this”-type of thing so I’ll let you take solitude in the quiet.</p><img src="" height="1" width="1"/> Vim Tips 2004-11-23T00:00:00-08:00 <table> <tr> <td><kbd><span class="caps">CTRL</span></kbd> + <kbd>A</kbd></td> <td>Increment number under cursor</td> </tr> <tr> <td><kbd><span class="caps">CTRL</span></kbd> + <kbd>X</kbd></td> <td>Decrement number under cursor</td> </tr> <tr> <td><kbd><span class="caps">CTRL</span></kbd> + <kbd>Y</kbd></td> <td>Duplicate character above cursor</td> </tr> <tr> <td><kbd><span class="caps">CTRL</span></kbd> + <kbd>X</kbd> <kbd><span class="caps">CTRL</span></kbd> + <kbd>L</kbd></td> <td>Complete line</td> </tr> <tr> <td><kbd>'</kbd> <kbd>.</kbd></td> <td>Jump to last modified line</td> </tr> <tr> <td><kbd>`</kbd> <kbd>.</kbd></td> <td>Jump to last modified character</td> </tr> </table><img src="" height="1" width="1"/> Speeding up Textpattern 2004-11-17T00:00:00-08:00 <p>To speed up Textpattern’s loading of pages, edit the file</p> <p>Replace:</p> <pre>$out['ip'] = @gethostbyaddr($_SERVER['REMOTE_ADDR']);</pre> <p>With:</p> <pre>$out['ip'] = ($_SERVER['REMOTE_ADDR']);</pre> <p>On line 18 of <code>textpattern/publish/log.php</code></p> <p><strong>Note:</strong> Log entries will only display an IP now, instead of a hostname. But if you use another package to generate statistics (i.e., Urchin on <a href="">Textdrive</a>) you can still view that information there.</p> <p>(This disables a <span class="caps">DNS</span> lookup for every IP that hits your site. Seems to work pretty well here… pages load up much quicker, for me anyways.)</p><img src="" height="1" width="1"/> SongMeanings Improvements 2004-11-13T00:00:00-08:00 <p>I’m not sure how active <a href="">the guys</a> are with development, but now that <a href="">SongMeanings</a> is back and (relatively) stable, I got to some solo-brainstorming about some things. Mostly ideas of features, but also some improvements and suggestions.</p> <ul> <li>An open, <span class="caps">XML</span>-based <span class="caps">API</span></li> <li>Artist/lyric recommendations</li> <li>Collaborative discography</li> <li>Better commenting <ul> <li>How useful is a page with 600 comments?</li> <li>Separate ‘meaning’-comments from ‘I like this song’-comments</li> </ul></li> <li>More schemes <ul> <li>Collaborative</li> </ul></li> <li>Push journals more</li> <li>Clean URLs</li> <li>Better user ‘homepages’ <ul> <li>Incorporate journal</li> <li> could work</li> </ul></li> </ul><img src="" height="1" width="1"/> Ben Folds 2004-10-31T00:00:00-07:00 <p>I’m pretty excited to be going to see Ben Folds live, in concert, next Saturday. Even though he’ll be performing at <a href="">our rival’s</a> auditorium, it still should be a pretty good show. This will only be the second concert I’ve been to, and I couldn’t think of anyone else I’d rather see.</p> <p>Ben Folds is one of my favorite performers. I think his lyrics are what draws me most to his music (and incidentally, is what led me to start <a href="">SongMeanings</a>.)</p> <p>Maybe after the show I can go talk to him, then mention SongMeanings. Upon immediate recognition of the name, he will proceed to tell me that he is a big fan and regale me with tales of how SongMeanings inspired his solo-music career.</p> <p>OK, enough of the annoying fan-girl crap, already. ::faints::</p> <p><strong>Update:</strong> Ben hospitalized for respiratory infection. Show cancelled. Sucks.</p><img src="" height="1" width="1"/> FreeBSD r0x 2004-10-20T00:00:00-07:00 <p>Coming from someone who runs a Debian <span class="caps">GNU</span>/Linux server at home: “FreeBSD r0x!”</p> <p>I’m diving into the world of FreeBSD. I installed 5.2.1-<span class="caps">RELEASE</span> on an old Dell GX1 at work and am playing around configuring and whatnot.</p> <p>The concept of ports are pretty impressive, and they seem to work well. I am continually impressed at the ease-of-use of the system as a whole.</p> <p>(Going to be replacing that Debian install with a FreeBSD one soon.)</p><img src="" height="1" width="1"/> Why Less is More, and Simple is Complex (Draft) 2004-09-29T00:00:00-07:00 <p style="text-align:center;"><em>I’ve been doing a bit of “solo brainstorming” about my philosophy/theory of minimalist web design. It is by no means final and still has a lot of work to be done before it can be considered a final document. I just wanted to post it to see what people thought.</em></p> <p style="text-align:center;"><strong>Why Less is More, and Simple is Complex</strong><br /> a web development theory</p> <p style="text-align:center;">by Kevin Marsh</p> <p>Abstract: Presenting content in a simple and elegant way is complex.</p> <p>Main Ideas:</p> <ul> <li>The term “web design” is misleading. There are really more facets to producing an effective web site.</li> <li>Two elements to web “design”: content and presentation (design).</li> <li>Content and presentation as two separate entities are not necessarily difficult.</li> <li>The fusion of the two is more complicated than both combined.</li> <li>When creating one or the other, they both must be kept in mind.</li> <li>Presenting accessible (navigable) content without distraction is crucial.</li> <li>Sometimes some of the most complex solutions are the easiest.</li> <li>Presenting content in a simple, easy-to-understand way is complex.</li> <li>A static web site presents content (content/presentation)</li> <li>A dynamic web site presents content and provides interaction (content/presentation/logic)</li> <li>Simple does not have to be boring.</li> </ul> <p><strong>Web Applications</strong><br /> Content (text/images) – database<br /> Presentation (<span class="caps">HTML</span>, <span class="caps">CSS</span>)<br /> Logic (<span class="caps">PHP</span>/Perl/<span class="caps">ASP</span>)</p> <p><strong>What is Distracting? (a.k.a. Worst Practices or “1999 Design”)</strong><br /> Large, superfluous images (i.e., animated GIFs of chrome @ signs)<br /> Annoying tags (blink, marquee)<br /> Too many colors<br /> Slow-loading<br /> Poor typography (i.e., too many different typefaces, unreadable typefaces, poor contrast)<br /> Ungraceful degradation/browser bugs<br /> Poor navigation<br /> “Messy” URLs (i.e.,…)<br /> Proprietary plugins (Flash, Java…)</p> <p><strong>What is Elegant? (a.k.a. Best Practices)</strong><br /> Good typography (one or two readable fonts)<br /> A few, solid (or gradient) colors that go well together<br /> Straight-forward navigation<br /> Quick-loading<br /> Few (or no) images, efficiently compressed<br /> Clean, semantic markup<br /> Clean URLs (i.e.,)<br /> No proprietary plugins (i.e., no Flash or Java)<br /> Adheres and validates to web standards (<span class="caps">XHTML</span> and <span class="caps">CSS</span>)</p><img src="" height="1" width="1"/> FavoriteSearch 2004-09-27T00:00:00-07:00 <p>A bookmark management service (ala <a href="">del.icio.us</a>) meets a search engine (ala <a href="">Google</a>) to form—FavoriteSearch (name subject to change).</p> <p>Details forthcoming. Beta testers inquire within.</p><img src="" height="1" width="1"/> Odds and Ends 2004-09-23T00:00:00-07:00 <p>In case you’re interested, here’s what I’ve been up to for the past few weeks:</p> <ul> <li>Learning Objective-C and Cocoa</li> <li>Learning x86 Assembly language</li> <li>Learning Ruby</li> <li>Brushing up on my LaTeX skills</li> <li>Doing Physics and Calculus homework</li> <li>Learning more and more about Mac OS X every day</li> <li>Learning about algorithms</li> <li>Troubleshooting printer/Windows/user errors</li> <li>Spending time with my lovely girlfriend. (I’ve realized that I probably don’t mention her much here, but I really should. She is the most important thing in my life and she rarely gets a mention beside all the geekery here.)</li> </ul><img src="" height="1" width="1"/> SongMeanings is Back! 2004-09-17T00:00:00-07:00 <p>In case you haven’t heard (or seen), <a href="">SongMeanings</a> is back up again. Congrats to the team for getting it back up. There are thousands of people (myself included) that are extremely grateful.</p><img src="" height="1" width="1"/> Class, Gmail 2004-09-04T00:00:00-07:00 <p>In between having Physics 5 days a week, doing Calculus homework, and fixing Macs on campus, I found 7 Gmail invitations in my Inbox.</p> <p>Does anyone even want any of these anymore?</p><img src="" height="1" width="1"/> Fall Mac Imaging 2004-08-19T00:00:00-07:00 <p>We are in the process of imaging the Macs at the University of Toledo’s two open labs, comprising a total of 30 Apple (Quicksilver) G4’s.</p> <p>The absence of a sufficient network requires us to visit each machine individually and boot from a Firewire hard drive (or iPod) containing a basic install of Mac OS X, <a href="">NetRestore</a>, and our image. After the machine is imaged, NetRestore is setup to rename the machine, set the Open Firmware password, and finally reboot the machine from the freshly-imaged drive.</p> <p>We then have to perform some configuration manually. The machine must be bound to the Active Directory and printers must be installed before it is ready to be used. In total, each machine takes about 6-10 minutes.</p> <p>While this isn’t much of a chore for the small amount of machines the University has, it would be nice to further automate the process to make deployment even easier: my goal is to use some shell-scripts, both home-brewed and from excellent resources like <a href="">macosxlabs.org</a>.</p><img src="" height="1" width="1"/> Lack of Updates 2004-08-11T00:00:00-07:00 <p>Wow, I haven’t been blogging very frequently. I’ve been quite busy at work and at home and really don’t have anything cool to talk about.</p> <p>However, I have done a couple geeky things of note lately:</p> <ul> <li>Burned a Knoppix <span class="caps">ISO</span> image from my Linux box directly onto my iBook G4 wirelessly (aka directly to Toast, through 802.11b, without copying the <span class="caps">ISO</span> to the hard drive first) after I started downloading the <span class="caps">ISO</span> remotely earlier in the day</li> <li>Without any broadband to speak of, I connected to the Internet using my T616 phone via <span class="caps">GPRS</span> using Bluetooth. I then preceded to <span class="caps">SSH</span> into my Linux box. <span class="caps">SSH</span> over Bluetooth through <span class="caps">GPRS</span>—nuthin’ but ’net.</li> </ul> <p>That’s about it. Oh, I’m learning <a href="">Ruby</a>, too.</p><img src="" height="1" width="1"/> Greatest Accomplishment? 2004-08-05T00:00:00-07:00 <p>I feel SongMeanings has quite possibly been one of my greatest achievements technically. It was a great idea at the right time, mixed with technology and design combined with a real following: it was successful and I learned a lot from it.</p> <p>But the sad thing is, in its current state I am almost ashamed of it. I feel so frustrated that I can’t tell people, “Yeah, I’m capable and can do a lot, just check out SongMeanings.net!”</p> <p>Well, I suppose I <em>could</em> tell people that. But they will think I am only skilled at writing “We’ll-be-back-real-soon-we-promise” pages.</p><img src="" height="1" width="1"/> Knoppix STD Saves the Day! 2004-07-14T00:00:00-07:00 <p>Our good friend, <a href="">Knoppix <span class="caps">STD</span></a> proved to be a great asset to any PC-troubleshooter’s toolbox the other day.</p> <p>Jenn’s aunt’s Windows XP machine wouldn’t boot to anything but a lovely BSoD with an UNMOUNTABLE_BOOT_VOLUME error and scores of numbers strewn about the screen. I was worried a bit at first that the disk was corrupted and all the data was gone, because I had never seen this particular error before.</p> <p>Armed with my trusty Knoppix <span class="caps">STD</span> disk, I booted into Linux and first tried mounting the problem-drive to see just how bad the problem was. It mounted, and all the files showed up with what seemed like no problem. So I got to a Fluxbox shell, fired up Firefox, and <a href=";lr=&amp;ie=UTF-8&amp;q=%22UNMOUNTABLE_BOOT_VOLUME%22+XP&amp;btnG=Search">Googled the problem</a> (hint: this means the network card was autodetected and <span class="caps">DHCP</span> got me on the router with nary-a-command). I got to a <a href=";NoWebContent=1&amp;NoWebContent=1">Microsoft page</a> that offered a possible solution: boot from the XP disc, drop to the Recovery Console (by pressing ‘R’), run <code>chkdsk /r</code>, and reboot. I did so. Lo-and-behold, the glorious (blech!) Windows XP boot screen came up and the system booted normally.</p> <p>OK, so maybe I owe some credit to the Windows XP disc but Knoppix certainly was useful!</p><img src="" height="1" width="1"/> Cedar Point III 2004-07-08T00:00:00-07:00 <p>Jenn, Fred, and I went to Cedar Point today. It was fun as always… we rode:</p> <ul> <li>White Water Landing</li> <li>Millennium Force</li> <li>Witches’ Wheel</li> <li>Blue Streak</li> <li>Giant Wheel</li> <li>Magnum XL-200</li> <li>Gemini</li> <li>Raptor</li> </ul> <p>We ate at Johnny Rocket’s and had sundaes before we left, Mmmm!</p><img src="" height="1" width="1"/> SongMeanings is Down 2004-07-08T00:00:00-07:00 <p>I’m not sure why, or for how long, but <a href="">SongMeanings</a> is indeed down and has been down for several days. Apparently, a new link is being installed.</p> <p>I’ll keep this updated as/if/when I hear more.</p> <p>(This should provide an answer to the recent flood of traffic coming from “SongMeanings” Googlers.)</p><img src="" height="1" width="1"/> Vacation 2004-07-02T00:00:00-07:00 <p>Today I start my vacation, until Monday, July 12! I’m not sure how much I’ll do, but time off should be good. I haven’t taken more than a few days off since I started working in August of 2002.</p> <p>It’ll probably get wasted along with my Summer vacation.</p><img src="" height="1" width="1"/> Pieces 2004-06-30T00:00:00-07:00 <p>There are tons of little things that don’t currently have implementations or don’t seem to have clean enough ones. I am toying around with solutions for:</p> <ul> <li>Getting multiple POP3 accounts to aggregate to one <span class="caps">IMAP</span> account, with a folder for each account.</li> <li>Filing/synchronizing/accessing bookmarks both remotely and on the client-side (I’m thinking of doing a linkblog-type thing on kevinmarsh.com, then creating bookmarklets to ‘bookmark’ to the remote server.)</li> <li>Getting all my contacts and appointments in one place, easily accessible from anywhere, including iCal and Apple’s Address Book as well as via the web</li> <li>Music. I need my music accessible from anywhere. The iPod is a good start, but I should do something like <code>rsync</code> my MP3s to my Linux box every night and setup some kind of streaming solution. I also need to get tunes in my car somehow…</li> </ul> <p>I’ll be working on these things, maybe, and posting solutions here. If you have any ideas, please let me know.</p><img src="" height="1" width="1"/> Giving Blood 2004-06-29T00:00:00-07:00 <p>I headed over to the <a href="">Red Cross</a> donor center this evening to give blood. I’ve never done it before, and wasn’t quite sure what to expect, other than leaving with a pint or so less of my ever-so-vital, lifegiving, red fluid.</p> <p>I began by filling out a lengthly survey asking various personal questions like if I had done drugs, had sex for money, had anal sex within the last 7 years, lived in Africa, and so on. (Which of course I answered “yes” to). Then after a period of waiting, I got in the chair. As soon as I sat down, I saw Jenn next to me getting poked with the needle and quickly after, streams of blood flowing into a clear plastic package. I began to get a little nervous.</p> <p>One of the biggest mistakes I made was to watch them poke the needle in, which was a bit larger than I was used to. It felt quite odd going in, but not especially painful. As the blood began to run from my body, I was feeling fine. But as more and more blood made the trip from my vains to the bag, I was feeling a bit lightheaded and warm. My hand, trying to maintain grasp on a foam ball, was starting to become numb and the rest of my arm was quickly following.</p> <p>Apparently, I looked pale, because the nurse asked me if I was alright. “Do you feel like your about to pass out?” She asked. “I don’t know, I’ve never passed out before,” I replied. She took that as a yes, and after I said it I felt more and more like I might want to. She layed me down, and put two cold towels on more forehead and neck, which felt great.</p> <p>Meanwhile, I was still continuing. I started seeing things a little blurry, and heard the nurses talking about how I was almost done. One of them came up and asked me if I was feeling okay, and if I wanted to switch to the other arm for the “other three vials”. My thoughts at this time were mostly “Heck no, just do it in the arm you already poked and get it over with”. So she did, and I was done.</p> <p>I laid in the chair for about 30-45 minutes, then when I felt strong enough to get up, I sat up and walked over to the “canteen area” and got a piece of apple pie and 7-Up. I was beginning to feel a little more normal, and after about 10 minutes, we left.</p> <p>I’m not too sure if I’d give blood again, but according to studies, every time you donate blood, you save three lives. So think of it this way, every time you <strong>don’t</strong> give blood, you kill three people. That’s a pretty strong statement. If I do decide do give again, I will definately eat something before hand to avoid my biggest mistake: not eating all day before I gave.</p> <p>On the positive side (or negative—hah!), I’ll soon get to find out what my blood type is!</p><img src="" height="1" width="1"/> Mac OS X Tiger 2004-06-28T00:00:00-07:00 <p>I love <a href="">Apple</a> as much as the next guy, but it seems to me that Apple’s latest upgrade to OS X, <a href="">Tiger</a>, isn’t filled with as much innovation as we’ve come to expect (especially since Apple was bashing Microsoft in banners posted throughout <a href=""><span class="caps">WWDC</span></a>).</p> <p>It’s new features basically copy some third-party utilities that have been around for awhile. Granted, the implementation might be a little cleaner, since it is built into the OS (hello bloat!), but the actual ideas have been around awhile.</p> <p>Two of the greatest “features” in Tiger include:</p> <ul> <li><a href="">Spotlight</a> a.k.a. <a href="">Launchbar</a></li> <li><a href="">Dashboard</a> a.k.a. <a href="">Konfabulator</a> (who takes a nice stab at Apple on their front page)</li> </ul> <p>However, XCode 2 looks good, and the <span class="caps">RSS</span> reader integration in Safari also looks pretty clean.</p> <p>I am also digging the refinements to the menu bar and classic ‘Pinstripe’ <span class="caps">GUI</span> elements (not metal). They look a bit more smooth.</p> <p>The <a href="">new displays</a> look very nice, though.</p><img src="" height="1" width="1"/> Cedar Point II 2004-06-26T00:00:00-07:00 <p>Well, Jenn and I got another trip to Cedar Point under our belt, bringing the grand total to 2 for this season.</p> <p>We rode:</p> <ul> <li>Gemini</li> <li>Witches’ Wheel</li> <li>Corkscrew</li> <li>Sky Ride</li> <li>Johnny Rocket’s (lunch)</li> <li>CP & LE Railroad</li> <li>Antique Cars</li> <li>Wave Swinger</li> <li>CP & LE Railroad</li> <li>Iron Dragon</li> <li>Wicked Twister</li> <li>Chaos</li> </ul> <p>(Compliments to <a href="">Jenn</a>, who did all the hard work of remembering what we rode in in what order we rode it.)</p> <p>I had a blast and I’m pretty sure Jenn did too. We will be going again the week of the fourth to further maximize our Season Passes’ value. Yay!</p><img src="" height="1" width="1"/> LSG 2004-06-25T00:00:00-07:00 <p>I just finished my first full week working at UT’s Lab Support Group. So far, its a pretty good job. The people are cool and knowledgable, and the position looks like it will be a good learning opportunity for me.</p> <p>I worked on creating images for the Universities’ 40-some G4’s. It was pretty routine stuff, but in the future I will be working on some user-management and deployment shell scripts.</p> <p>Next week I will work several full days, and then after my week vacation I will begin working 9-5, all week.</p> <p>Oh, I get a Faculty parking pass too!</p><img src="" height="1" width="1"/> Things to Remember When Upgrading your Linux Kernel 2004-06-20T00:00:00-07:00 <p>I tried to upgrade the Linux kernel on my desktop Linux machine the other day to 2.6.7 (the “latest-and-greatest”).</p> <p>The operative word here being: <em>tried</em>.</p> <p>I used the <code>menuconfig</code> utility to go through and select (what I thought were) the correct options. And compiling (<code>make && make install</code>) went without a hitch.</p> <p>The kicker came when I tried to reboot the machine and boot into my shiny new kernel. It wouldn’t boot.</p> <p>It only got so far when it comes up with the message:</p> <pre> UFS: Cannot open root device "303" or unknown-block(3,3) Please append a correct "root=" boot option Kernel panic: VFS: Unable to mount root fs on unknown-block(3,3) </pre> <p>Uh oh.</p> <p>Apparently, the problem stems from not building ext2 support (or whatever format your root partition is in) into the kernel (as a ‘*’, not a module ‘M’). Even if you do compile ext2 support in as a module, it is never loaded because it needs the module to load it! (headache yet?)</p> <p>So, I have to make a Linux boot disk and try to boot from it, access my partition, reconfigure the kernel (this time making doubly sure ext2 is selected!), recompile, and reinstall.</p> <p>The Joys of Linux™</p><img src="" height="1" width="1"/> Promotions 2004-06-17T00:00:00-07:00 <p>I was just informed by the head of the Lab Support Group at UT that I will be starting a new position on Monday! As it turns out, I will be the University’s head Mac guy 35 hours a week.</p> <p>What does that mean? It means no more computer-lab-sitting and more computer-fixing! Yay!</p> <p>Unfortunately, this also means I’m going to scale back my hours at Savage Consulting quite a bit. I feel bad doing so. My boss assured me that I was an integral part of the operation and I have some fairly important duties here. I have learned a lot at this job, and have been here awhile (I started at the start of my senior year of high school.) But I feel I will be an overall better fit over at UT.</p> <p>I feel I’ll be able to apply some of the things I know a bit more there. They will need me to do all sorts of fun things like shell scripting and writing some AppleScript (among other things.)</p> <p>Am I up to the challenge? I think so. But only time will tell. Reports from the front lines, as always, will be forthcoming.</p><img src="" height="1" width="1"/> Pretty Pictures 2004-06-17T00:00:00-07:00 <p>Design and photography isn’t a full-time gig for me by any means, but it is a hobby that lets me creatively express myself that I do enjoy. I really wish I could do more designing and take more pictures, but the time isn’t always there.</p> <p>However, I am announcing that some of the work I have done has been uploaded and is now available for your inspection. There is a lot more where that came from, it just takes awhile to prepare it for the web. The work that is here is separated into two sections: the <a href="/portfolio">portfolio</a> (design) and the <a href="/gallery">gallery</a> (photography).</p> <p>The design work is mostly logos and web stuff. The logos were created in Adobe Illustrator and Photoshop and the web stuff is all hand-rolled <span class="caps">XHTML</span> and <span class="caps">CSS</span>. (No FrontPage here!)</p> <p>For the photos, I use a Sony Cybershot <span class="caps">DSC</span>-S30. On my wish list is a nice, prosumer digital <span class="caps">SLR</span>—If I could ever afford it.</p> <p>I am still trying to come up with a better solution for the gallery. The current method is clunky, at best, as it doesn’t offer thumbnails. I need to whip up a nice script with ImageMagick’s <code>convert</code> utility to automatically generate thumbnails and lay them out on the page, along with a link to the full version (possibly in a popup window). But I wanted to get some stuff up as soon as possible.</p> <p>Nevertheless, I hope you enjoy my work.</p><img src="" height="1" width="1"/> E-mail addresses 2004-06-15T00:00:00-07:00 <p>Commonly you know someone’s name and company they work at, but don’t know their e-mail address. Sometimes if you know other e-mail addresses within the company you can decipher their particular naming scheme (i.e., firstlast@company.com, flast@company.com, etc.)</p> <p>It should be possible to send an email to simply: “joe shmoe”@company.com and have the <span class="caps">MTA</span> automatically forward it to Joe using an internal corporate database.</p> <p>Of course, spaces and quotes are not valid for e-mail addresses.</p><img src="" height="1" width="1"/> Cool Thing to Do With A Linux Box I - Text-Based Games 2004-06-14T00:00:00-07:00 <p>To play some old-fashioned (but fun!) text-based adventure (or “interactive fiction”) games, use <a href="">Frotz</a> and grab some old data files from your favorite games. My favorite is the <a href="">Zork series</a>.</p> <p>If you aren’t sure what a text-based adventure game is, or why you’d want to play one, check out the <a href="">Brief Introduction to Interactive Fiction</a>.</p> <p><strong>Installing Frotz</strong><br /> To install Frotz, simply download the .tar.gz file to your linux box (perhaps using <code>wget</code>), issue the command <code>tar -zxvf [name of frotz].tar.gz</code> then run <code>make</code>, then <code>make install</code> as root.</p> <p><strong>Running Frotz</strong><br /> To play Frotz after it has been installed, use the command <code>frotz</code> then the name of the image (i.e., <code>frotz /etc/games/zork/zork1.dat</code>)</p> <p>To save the progress of your game, type <code>save</code> while running the game. It will ask for a filename. You can then load the save-state later by using the <code>restore</code> command.</p> <p>Hours of console-based fun—but watch out for the grues!</p><img src="" height="1" width="1"/> Weekend 2004-06-13T00:00:00-07:00 <p>Wow, what a busy weekend.</p> <p>Jenn was dog/housesitting for her co-worker so I spent some time over there. It was nice to get away for a little while. We watched <a href="">Gothika</a> and <a href="">Notting Hill</a> which actually was pretty good.</p> <p>Then on Sunday we went to church, had dinner, went to my house, and then back to church. A <a href="">missionary</a> from Kenya spoke at the morning service, and one from Mexico spoke at the evening service. It was quite interesting hearing about the adventures a missionary faces in “the field.”</p> <p>After church, we went to El Camino Real. It was the first time I’d ever been there. I got the Taco Salad, and it was good, but after seeing the fajitas I wish I would’ve gotten them.</p> <p>I’ll be at Scott Park from 8:30am – noon tomorrow and then at Savage Consulting until 5pm.</p> <p>Who said summers are for relaxing?</p><img src="" height="1" width="1"/> Gmail Invites 2004-06-08T00:00:00-07:00 <p>Well, well, well. It finally comes around for a begger like myself. I’ve had Gmail for about a month now and I was just notified that I have three — count ’em — three invitations to send to people! yay!</p> <p>The first one went to my lovely girlfriend, Jennifer (of course), but that leaves two up for grabs.</p> <p>Does anyone even want these things anymore?</p><img src="" height="1" width="1"/> Back! 2004-06-07T00:00:00-07:00 <p>Well, after what I think should be the last period of downtime, KevinMarsh.com is up and running again. I have finally gotten most of the issues with the new TextDrive service ironed out and things appear to be running smoothly.</p> <p>Thanks to Dean and Jason for providing all the VC200, me included, with such a wonderful experience (even if it did take awhile. <g>)</p><img src="" height="1" width="1"/> Cedar Point I 2004-06-05T00:00:00-07:00 <p>Our first trip to Cedar Point for the season was today. Jenn and I rode:</p> <ul> <li>Gemini</li> <li>Snake River Falls</li> <li>Wave Swinger</li> <li>White Water Landing</li> <li>Thunder Canyon</li> <li>Mine Ride (which got stuck on the 2nd hill)</li> <li>Iron Dragon</li> <li>Disaster Transport</li> <li>Space Spiral</li> <li>Cedar Downs</li> <li>Ocean Motion</li> <li>Midway Carousel</li> </ul> <p>Seeing as how we just got our season passes today as well, there will be many more trips to come!</p><img src="" height="1" width="1"/> Computer Lab Attendent Kevin 2004-05-30T00:00:00-07:00 <p>Today was my first official day of my new job at <a href="">The University of Toledo</a> Lab Attendent for the <a href=""><span class="caps">EIT</span></a> department.</p> <p>I was scheduled from 3 — 5pm in Carlson Library Lab B2. Yes, 2 hours is pretty pointless and a waste of gas, but with <a href="">gas as low as $1.859</a>, why not?</p> <p>Anyways, I was ready for duty, but unfortunately duty was not ready for me. I didn’t have login information for EIT’s “Headcount” system, so I wasn’t able to “clock-in” and “clock out”.</p> <p>I met a fellow lab attendent, who was on duty the same time I was, and her brother. They were very nice in showing me some of the things I had to do, and some of the experiences they’ve had. It seems as though people can get pretty beligerent, like when they are asked to put away their beverages or when Word crashes and their work is lost. Something to look forward to.</p> <p>I only ended up doing two major things in my 2 hour shift, which should net me around $9, after taxes:</p> <ol> <li>Refilling a ream of paper in the laser printer, and</li> <li>Calling “This lab closes in fifteen minutes” at 4:45pm</li> </ol> <p>I never thought I’d work in a technical support position but this is really just a springboard to the Lab Support position I interviewed for earlier: they require experience on the front lines.</p><img src="" height="1" width="1"/> Preparing for Cedar Point... 2004-05-30T00:00:00-07:00 <p>Well, the summer is here and most (Northern) Ohioian’s minds turn to thoughts of <a href="">Cedar Point</a>. I am no exception, I am really looking forward to going this year, as I wasn’t able to make it last summer.</p> <p>Anticipating going at least 3 – 4 times this year, Jennifer and I splurged and bought two season passes tonight at <a href="">Meijer</a>. For $89 we get to go as many times as we want. It may sound expensive, but considering tickets are normally $40/ea. going three times pays for them easily.</p> <p>I’m excited!</p><img src="" height="1" width="1"/> RIP TechTV 2004-05-28T00:00:00-07:00 <p>Well, the final nail in TechTV’s coffin was driven in today, as TechTV and G4 offically merged to form G4techTV. My DirecTV already shows Channel 354 as “G4TV” and the TechTV website,, now redirects to g4techtv.com, the new network’s “official website” (which is all G4-ish and shows no traces of the TechTV website’s look). Also, all the great content from the past years of The Screen Savers and Call For Help that lived on the web, is gone (except for in the Google cache.)</p> <p>As a long time fan of shows like The Screen Savers and Call For Help, and people like Leo Laporte, this is a pretty sad day. The only remnants to survive the tragedy are The Screen Savers and while Patrick and Kevin are pretty great, they will probably not be around for much longer (they’re already been fired.)</p> <p>I still remember TechTV back when it was called <span class="caps">ZDTV</span> and The Screen Savers were Leo Laporte and Kate Botello (I can still hear them chanting “DirectTV Channel 273!”) and there were shows like Internet Tonight and The Money Machine.</p> <p>Lets have a moment of silence for the once great network. (Shuts off TV.)</p><img src="" height="1" width="1"/> Updates 2004-05-25T00:00:00-07:00 <p>Wow, a lot has been going on in regards to this site and I’ve been so busy with them, I’ve neglected to write an actual post about them. I’m sure you’ve noticed the working links at the top and other things, keep your eyes open—there will be more to come. My head has been racing with neat things to put up here, I hope I can make it happen.</p> <p>I am quite excited about this whole blog thing, which is odd because of the numerous times I’ve tried it, I never really was. I think it’s partly due to <a href="">Textpattern</a> and some extra free time I’ve been ejoying.</p> <p>I’m also proud to announce that I am one of the <a href="">‘VC200’</a> member’s that has invested in Textpattern (a great deal consisting of what is essentially top-notch hosting for life, for $200).</p> <p>So, on June 1st this site will be moving to a new space, off my Linux box and out of my attic. I’m going to miss doing it, it has been really fun keeping up the server. I am planning on still using it for some things though, just not the main kevinmarsh.com page (that sound you just heard was the sigh of relief coming from Buckeye Cablesystem’s <span class="caps">NOC</span>).</p><img src="" height="1" width="1"/> Imports 2004-05-24T00:00:00-07:00 <p>Most of the old content from KevinMarsh.com has been imported into Texpattern. There are now a grand total of 23 entries here, including this one. I really need to write more (frequently).</p> <p>The good thing about not updating your blog a lot is that importing is not such a chore.</p><img src="" height="1" width="1"/> I'm Back! 2004-05-24T00:00:00-07:00 <p>After a short hiatus, KevinMarsh.com is back and better than ever! I’m now running the great <a href="">TextPattern</a> blog software.</p> <p>I’m still adding some stuff and changing bits around, but I thought I’d let my 2 fans continue to read the site while I do so. :)</p> <p>I’m still working on importing all my posts from my old system to the new one, so all the history may not be there (yet.)</p> <p>If you see any bugs, please drop me a line and let me know. I am aware of the broken links at the top, however. Thanks.</p> <p><strong>Update:</strong> Fixed some of the glaring bugs that I haven’t been able to nail down, thanks to the <code>base</code> tag and more! Yay Permalinks!</p><img src="" height="1" width="1"/> Textpattern 2004-05-20T00:00:00-07:00 <p>I’m working a little on getting <a href="">TextPattern</a> going. Yeah, I know. I was working on my own homebrewed <span class="caps">PHP</span> scripts but it just got so boring, cause I’ve done it all about a million times. And Dean has really done some great work here. The whole system is really great. MovableType, watch out!</p> <p>I’ll keep you posted on the progress of the switch-over.</p><img src="" height="1" width="1"/> Now With RSS! 2004-05-19T00:00:00-07:00 <p>I’m glad to announce that KevinMarsh.com now offers an <a href=""><span class="caps">RSS</span> feed</a> of full blog posts. The <span class="caps">RSS</span> feed is perfect for those users of <a href="">great <span class="caps">RSS</span> readers</a>.</p><img src="" height="1" width="1"/> Grades 2004-05-10T00:00:00-07:00 <p>I think there is a problem with my Discrete Math and Linear Data Structures grade. It is way lower than I expected. I got a perfect score on 3/4 projects, did reasonably well on the tests, and thought I did a good job on the final. The professor has been quite distracted lately so I think a mistake might have been made. I emailed him but it is really making me wonder about how I approach school (that coupled with a very low grade in Calculus).</p> <p>Next semester, I have to work about 5x as hard to bring my <span class="caps">GPA</span> up. I also have to prove to myself, I think, that when I put my mind to it I can do well. I think my biggest problem is procrastination.</p> <p>While it may seem like an excuse, working while going to school is extremely hard. Too much time is demanded of the college student and working takes away valuable study time. But what else can you do about it?</p><img src="" height="1" width="1"/> Gmail! 2004-05-07T00:00:00-07:00 <p>I am starting to think everyone in the world is not greedy and <a href="">looking to make a buck</a>—that there are actually <a href="">nice people</a> around!</p> <p>Update: <a href="mailto:kevin.marsh at gmail.com">kevin.marsh at gmail.com</a></p><img src="" height="1" width="1"/> Summertime 2004-05-07T00:00:00-07:00 <p>Well, exams are over and while I await the backlash of grades, I am thinking about what I’m going to try to do/accomplish this summer. I’ll be working, of course, but I also want to try to do some other things, including:</p> <ul> <li>Spend time with my <a href="">lovely girlfriend</a></li> <li>Clean up/organize my room</li> <li>Read up/practice some programming stuff</li> <li>Get outside more (bikeriding)</li> <li>Take lots of pictures (see above)</li> <li>Get motivated for a successful Fall semester</li> <li>Brush up on things I probably <em>should’ve</em> learned this semester</li> <li>Organize the files on my computers (both laptop and Linux box)</li> <li>Work on this more (add portfolio, resume, archives, searching, and some other random features)</li> </ul><img src="" height="1" width="1"/> Gmail 2004-05-05T00:00:00-07:00 <p>I’m really trying hard to get a <a href="">GMail</a> account. I got no love from Blogger (guess I’m not “active” enough) and I tried contacting some people who were fresh out of invites.</p> <p>It looks so cool and I want it so bad. :(</p><img src="" height="1" width="1"/> Dotgeek 2004-04-26T00:00:00-07:00 <p>I signed up for an account over at <a href="">Dotgeek</a>, they have free PHP5 hosting and PostgreSQL. I’m just using it to explore some of what is to come in <span class="caps">PHP</span>, but SQLite caught my attention. It looks like a great addition for the small <span class="caps">PHP</span> site that needs some dynamic content (probably 75% of them) but doesn’t need a full-blown database like MySQL.</p> <p>So check me out over at <a href="">kevin.dotgeek.org</a>.</p><img src="" height="1" width="1"/> How Does It Feel 2004-04-13T00:00:00-07:00 <p>How does it feel to be pushed out of something you created, your vision, your “baby?” Pretty awful. But then again, when you never gave it the time it deserved who are you to complain?</p><img src="" height="1" width="1"/> Project Stamina 2004-03-30T00:00:00-08:00 <p>Whenever I start a new project, I am incredibly motivated. I’ll get so much done in so little time. But then, after awhile, I start to get in a lull. I won’t feel like working on it at all. I’m not sure if I get bored with it so much as that I am burned out by all the work I did when I first started. I think I should probably not work so hard at the beginning, and maintain focus throughout the project instead of working all at the beginning and giving up.</p><img src="" height="1" width="1"/> C++ Perversion 2004-03-23T00:00:00-08:00 <p>One time, in a EECS1530 lecture about classes and object-oriented programming in C++, Dr. Miller said this:</p> <blockquote> <p>“If I call foobar on you, I can access your private members.”<br /> -Dr. Lawrence Miller, University of Toledo</p> </blockquote><img src="" height="1" width="1"/> You'll Think of Me 2004-03-16T00:00:00-08:00 <p>I think the music director at 102.9 is out to get me.</p> <p>Driving home, they played the three songs that hit me most in a row and I realized something. The only thing harder than trying to drive with her in the car and holding back tears is trying to drive home with tears flooding your eyes alone.</p> <p>But why would someone who was so struck—tortured even—by those three songs, play them over and over again when they finally do get home? Love.</p> <p>It happens every time we’re about to break up. I’ll think how much better things will be. How much more time I’ll have to concentrate on other things like school, work, and (selfishly) myself—how much more I’ll be able to do, how much more free time I’ll have to do whatever I want, and so on. But then, it’ll hit me. I’ll <strong>lose her</strong>. And in a moment, all these concrete plans you had laid out for your free self are tossed into a mixer with those treasured memories you once shared.</p> <p>The thought of breaking up doesn’t seem so bad when you’re sitting alone, or talking on the phone, or online, or even with her in an argument or a time of particular stress. It’s when you look at her, and think of the pain you’re causing her, that you crack. And something inside your throat aches… and the tears flow from your eyes. You begin to see yourself as the big jackass she’s seen you as for days.</p> <p>But we don’t see eye to eye. Is it just better to cut your losses and move on, no matter how hard that will be/already is? Sometimes it seems like it can’t be, and other times it seems so easy.</p> <p>(I know you’ll probably read this. And maybe a part of me wishes you did. I just needed to say this, and not directly at you.)</p><img src="" height="1" width="1"/> Frequency 2004-03-01T00:00:00-08:00 <p>My girlfriend, Jenn, has informed me that the reason she doesn’t visit more often is because I don’t post enough.</p> <p>I try to post whenever possible, and whenever I have a brilliant thought, but it seems as though I have to try to post more.</p> <p>I will post at least once a day—maybe even every few hours—just for her. I can’t have her keep going to other blogs, can I?</p><img src="" height="1" width="1"/> Blog Cheating 2004-03-01T00:00:00-08:00 <p>What does one do when their girlfriend visits <a href="">some other guy’s blog</a> more then they visit their boyfriend’s?</p> <p>They probably shouldn’t link to it, for starters.</p><img src="" height="1" width="1"/> 40 GB 2004-03-01T00:00:00-08:00 <p>Yay for 40gb hard drives for $20!</p> <p>Boo on old <span class="caps">BIOS</span> that don’t see them, freeze up when trying to detect them, and make the user think they have a dead hard drive on their hands.</p> <p>Yay for <span class="caps">BIOS</span> flash updates!</p><img src="" height="1" width="1"/> Linux Box 2004-02-23T00:00:00-08:00 <p>I recently got a Debian <span class="caps">GNU</span>/Linux box up, and connected to the Internet with my router (In fact, it’s serving this!) Anyways, when I started to put it together from some old spare parts, I was at a loss for what I’d actually <strong>do</strong> with it. I’ve had Linux boxes set up before but with no router, and therefore no Internet to them, they seemed worthless.</p> <p>Well, I’ve compiled a list of things I’ve been doing with my Linux box, currently (and uncreatively) named <em>linux</em>.</p> <ul> <li>Apache serving kevinmarsh.com (with Perl and <span class="caps">PHP</span>)</li> <li>MySQL database server</li> <li><span class="caps">SSHD</span> for remote logins</li> <li>MP3 Server (very limited until new hard drive is installed)</li> <li>Alert Server (SMS’s cell phone occasionally)</li> </ul> <p>I still have a few more ideas for what I want to do with this thing, but I’m waiting for my new hard drive to implement them.</p><img src="" height="1" width="1"/> Uptime 2004-02-18T00:00:00-08:00 <p>To display how long your Linux box has been running, how much cpu is being used, and how many users are logged in, use the <pre>uptime</pre> command.</p><img src="" height="1" width="1"/>
http://feeds.feedburner.com/kevinmarsh
crawl-002
refinedweb
18,789
62.17
Secure Transaction Service (III): Fuzzy Matching on personal data with Machine Learning One of the main issues in systems in charge of managing hundreds of thousands or even millions of personal records is the diversity of sources of information and the multiple levels of quality, validation and formats in which the information can be inserted into the databases. The main problem generated by a defective validation and a uniform application of quality measures when the clients/consumers of the system handle personal data is the appearance of hundreds or thousands of duplicates records that apparently represent different people, companies or whatever but actually are the same one. The effects of having duplicate records in your system are not good. Transactions are attributed to wrong people, balances are wrong claim management can turn into a nightmare, compliance work is simply ineffective facing threats as money laundry and fraud. We have a better way to recognize the people, companies and any entity we work with to improve our procedures and business quality. Not mentioning the obligations and regulations regarding compliance and Anti Money Laundry measures. To solve this problem we find different possibilities and concepts. Fuzzy Matching techniques should help us to apply some screening to data, detect the possible duplicates by finding possible matches. A Bit of Theory One way to apply Fuzzy Matching is usually based on string similarity measures like Jaro-Winkler or the Levenshtein distance measure. The obvious problem here is that the amount of calculations necessary grow quadratic. Every entry has to be compared with every other entry in the dataset, in our case this means calculating one of these measures 663.000^2 times. This can be done faster using TF-IDF, N-Grams, and sparse matrix multiplication. TF-IDF TF-IDF is a method to generate features from text by multiplying the frequency of a word in a document (Term Frequency, or TF) by the importance (the Inverse Document Frequency or IDF) of the same term in an entire corpus. This last term weights less important words (e.g. the, it, and etc) down, and words that don’t occur frequently up. IDF is calculated as: IDF(t) = log_e(Total number of documents / Number of documents with term t in it). We can consider a document containing 100 words in which the word cat appears 3 times. The term frequency . TF-IDF is very useful in text classification and text clustering. It is used to transform documents into numeric vectors, that can easily be compared. N-Grams While the terms in TF-IDF are usually words, this is not a necessity. In our case using words as terms wouldn’t help us much, as most company names only contain one or two words. This is why we will use n-grams: sequences of N contiguous items, in this case characters. Cosine Similarity To calculate the similarity between two vectors of TF-IDF values the Cosine Similarity is usually used. The cosine similarity can be seen as a normalized dot product. For a good explanation see: this site. We can theoretically calculate the cosine similarity of all items in our dataset with all other items in scikit-learn by using the cosine_similarity function, however the Data Scientists at ING found out this has some disadvantages: - The sklearn version does a lot of type checking and error handling. - The sklearn version calculates and stores all similarities in one go, while we are only interested in the most similar ones. Therefore it uses a lot more memory than necessary. To optimize for these disadvantages ING created their own library which stores only the top N highest matches in each row, and only the similarities above an (optional) threshold. There are many other types of algorithms. Please pay attention to Soundex and Levenshtein: - Dice / Sorensen (Similarity metric) - Double Metaphone phonetic metric and algorithm) - Hamming (Similarity metric) - Jaccard (Similarity metric) - Jaro (Similarity metric) - Jaro-Winkler (Similarity metric) - Levenshtein (Similarity metric) - Metaphone (Phonetic metric and algorithm) - Monge-Elkan (Similarity metric) - Match Rating Approach phonetic metric and algorithm) - Needleman-Wunch (similarity metric) - N-Gram (Similarity metric) - NYSIIS (Phonetic metric and algorithm) - Overlap (Similarity metric) - Ratcliff-Obershelp (Similarity metric) - Refined NYSIIS (Phonetic metric and algorithm) - Refined Soundex (Phonetic metric and algorithm) - Tanimoto (Similarity metric) - Tversky (Similarity metric) - Smith-Waterman (Similarity metric) - Soundex (Phonetic metric and algorithm) - Weighted Levenshtein (Similarity metric) The Context Well, it’s been a short intro to something basic: the existence of several options and strategies for the detection of similarities in literals. This is useful to us. The Secure Transaction Service manages hundreds of thousands of records coming from heterogeneous sources. Older databases still operate receiving new data that generates new duplicate cases. However, the existence of duplicates must be mitigated to minimum to have the STS data as clean and available as possible. We have three different timings of handling duplicates depending on the time and the way the data are being acquired: - Import: Migration of data from heterogeneous systems and databases. - Real-Time: Entry of new data, providing a prediction to the API consumers (web, mobile apps, for instance) about a probable insertion of a duplicate. - Background Cleaning: Supervision of migrated records and new data to detect the insertion of possible duplicates. This requires as well the re-arrange of existing links to existing linked information (e.g. financial transactions). The Use Case We’ll consider in our case a given source of data. The main factors of this data source are: - You could see in our last post the concepts derived of the applied standards. The PII (Personally Identifiable Information) is not usually present and it has to be composed somehow from the data structures in the source. - The source database was receiving information from several apps and the validation … well, some times it’s better not to talk about some topics. Come on! validate formats, regular expressions, try to normalize your data entries! Empty columns that are key for identification, personal remarks .. in the postcode column!!! and many more. An authentic nightmare for a data analyst. The Target We have to feed the STS database (remember, it’s distributed, it’s NoSQL) with a list of PIIs composed from the sources with no duplicates and the minimum loss of information. The Tools Use Apache Spark. That’s all. The Process We have defined several phases in a process: - Get the source data and transformation to processable entities. - Create the combinations of candidates for detection of duplicates. - Get a set of test data. - Training a Machine Learning Model and test the model against the test data. - Apply the trained & tested model to all the source records. - Generate the list of duplicates. - Merge the duplicates and obtain the final list. - Load the STS database. And first of all, do not be scared of Machine Learning because: Contrary to popular belief, Machine Learning is not a magical box of magic, nor is it the reason for $30bn in VC funding. At its core, machine learning is just a thing-labeler, taking your description of something and telling you what label it should get. Which sounds much less interesting than what you read on Hacker News.Cassie Kozyrkov (2018) 1-Get the source data and transformation to processable entities First, get the data from the source. A Materialized View (MV) can be good to simplify the query and you can bet with your co-workers about who builds the longest SQL query to feed the MV. It can take some time to design the query you’ll really need. A lot of join operations will needed. The values and IDs will be present or not almost in a random way. Who said this would be easy? But in the end, once you have your MV, it’s just a matter of: def getSourceData(): DataFrame ={ val mvQuery = s"(SELECT * FROM yourmaterializedview) AS TEMP" spark.read.jdbc(sqlServerUrl, mvQuery, sqlServerSourceConnectionProperties) } Easy right? maybe you want to apply additional filters and so on. What you’ll want for sure is to normalize the content in the DataFrame you’ve obtained from that query. Because, for sure, unexpected null values, bad design in relationships and incorrect data types and formats will be found. For sure! 2-Create the combinations of candidates for detection of duplicates Secondly, create all the possible combinations. In our case we have pre-arranged the source data structure to an entity we have called Person. We have to set here the conditions for comparison in order to not get a cartesian product. Well, that’s a possibility but it can take a long. The usage of functions to find similarities is interesting. Spark does not include too many functions for this purpose (only two) and we’ll need to import a library libraryDependencies += "info.debatty" % "java-string-similarity" % "1.1.0" There are some other options like Spark-Stringmetric. It’s just a matter of testing different options and choosing the best one for your purposes. In the function you can see how the combinations are made by combining soundex and Levenshtein for the family name given this is the column with more false similarities by far. Levenshtein is applied to the first name as well while we set two discreet values whose equality marks clear candidates as duplicates, date of birth (DOB) and the postcode. The combination of everything is used to calculate a vector of features for the involved columns. The vector contains the evaluation of the combination for possible duplicates. For instance: [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] Well, the distance between two records is 0. It’s 100% a duplicate [1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0] Everything is extremely distant. This is clearly a different record. [0.0,0.0,0.025654442,0.0,0.012552,0.0,0.25,0.0] There are some distance in some columns that we have to evaluate. Obviously we are not showing the personal data in the other columns but you can see in the picture below some examples from the column with the vectors of features for each pair or persons. 3-Get a set of test data We have now to generate a set of data to train and test the Machine Learning model. To do this we use the Dataset composed by two lists of Persons and the Vector with the scores for each combination of Persons. The function generateTrainingData() uses the collections of Persons to automatically generate a final decision/label from the features in the Vector for each combination or Persons. We can do this manually but it is a tedious and boring task. The final goal is to get a set of data big enough to train the model and verify the predictions from the training phase in the test phase against a set of pre-validated data. In this picture we can see how the vectors with the features have been evaluated and a label is assigned. In the capture any value is greater than the distance set in the evaluation. That’s what the label in the capture is always positive (1.0). It is not always the case though. I did not mention but it is important you can use a data file or a set of files with some real data to use as training/test datasets. As we’ll see later these files or file will be used also for the build test phase. 4-Training a Machine Learning Model and test the model against the test data This is the beauty and versatility of Spark. The Spark ML support (remember: org.apache.spark.ml) is amazing, it contains many many algorithms and the implementation makes them extremely easy to use and tweak with hyperparameters. We have used here a model based on Logistic Regression but obviously other options are valid as well. you can find here an explanation of how to use hyperparameters (Hyperparameters by definition are input parameters which are necessarily required by an algorithm to learn from data.) in this model with Spark. The code snippet with the ModelTrainer class is really clear. You can follow the step in the class to see the phases. We get some basic indicators from the tested model to be evaluated in the test phase (build time). The tuning of the parameters is very important to adapt to your analysis and data. We have used a multiclass logistic regression model with elastic net regularization. 5-Apply the trained & tested model to all the source records. Get the model, get the set of combinations (all comparable pairs for persons with their features) and apply bthe model (the function transform in Spark) 6-Generate the list of duplicates What we need her to work is a list of IDs with the groups of the records with their matches (the list of IDs of other records that have been predicted/detected as duplicates). We need this list to be able to merge the duplicates into a single record into the new storage. The final result is something like this: In the capture you can see that each ID has at least one duplicate..that is itself! But some others have several related IDs in the same row. Those are duplicates. The first column shows the number of duplicates for each record (again, 1 means it is not duplicated) 7-Merge the duplicates and obtain the final list The we get the definitive list of persons and we merge the set of duplicates (already merged into a singe record) and the list of persons no related to any duplicate. 8-Load data to the STS database One could say this is the easy part but it’s not. We have to build here the data structures linked to each Person in the STS database to form PIIs. The problem is, the data in the source are pretty defective. Many records have not the right information, the uniformity and general quality of the source data usually is low. We have to be careful here and design a good construction of the new data structures in our destination to not replicate the same defects in the new data repository. Testing The only logical concern about testing in a Machine Learning component is about data. We naturally want to test and the training of the model and we want to be sure that everything is tested the best as possible. scenario("apply the model to data with all possible combinations in data") { val (trainedModel, metadata) = etl.trainAndGetTrainedModel() val prediction = etl.applyModelToAllCombinations(trainedModel.get, allCombinationsDS) assert(!trainedModel.get.uid.isEmpty) assert(metadata.get("areaUnderROC") > 0.85) assert(metadata.get("maxFMeasure") > 0.9) assert(metadata.get("accuracy") > 0.9) } Not a big deal… but beware! we need a subset of real data to test the model in the test phase to obtain something serious. This is a problem because the obvious restrictions about the personal data. We cannot simply push the test files to git (besides, they can be relly big files). So, there are several options here: - Get real-like data. Not real information about real people but with no anonymization or obfuscation of values. - A much better option, save your test datasets in a security vault in cloud, protected by a strong keys. The delivery pipeline will extract and decrypt the test datasets for us during the build time test phase and for every time the component train the model. This keeps the test dataset apart from any public exposition/access. The FTS Delivery Platform supports 100% the AI components by providing transparent injection of test datasets in build and run time. Conclusion - Most of people thinks that Machine Learning techniques are difficult. Well, they are not when we use amazing frameworks and tools like Apache Spark. - On the opposite, the most difficult part in this kind of tasks is to have a good understanding of the data and the data types, get the knowledge about its properties and defects and prepare the data for their processing. - Then, the processing of predictions and groups of data is not a big deal and many options are available (Clustering, Graphs). Again, Spark provides all you need to perform these tasks. - The load of data to the destination storage is not straight forward. The construction and population of a new data model from the old one can be shocking. Be ready to make decisions about the massive number of defect you’ll find in the source data. - A new paradigm of programming is coming up based on the structure of data rather than strongly defined requirements. Data will be the requirements. As development engineers we have to be ready for this paradigm. It’s really easy with tools like Spark. Thanks a million if you have reached the end of this long long post and do not hesitate of sending your questions.
https://techblog.fexcofts.com/2019/02/27/secure-transaction-service-iii-fuzzy-matching-on-personal-data-with-machine-learning/
CC-MAIN-2021-39
refinedweb
2,834
54.02
curl-library formatting hugehelp.c Date: Mon, 2 Feb 2004 17:17:10 +0100 Looking through my build log () I noticed the following: echo '#ifndef HAVE_LIBZ' >> hugehelp.c /opt/freeware/bin/gnroff -man ../../curl/docs/curl.1 | /opt/freeware/bin/perl ../../curl/src/mkhelp.pl ../../curl/docs/MANUAL >> hugehelp.c gtroff: fatal error: can't find macro file an echo '#else' >> hugehelp.c /opt/freeware/bin/gnroff -man ../../curl/docs/curl.1 | /opt/freeware/bin/perl ../../curl/src/mkhelp.pl -c ../../curl/docs/MANUAL >> hugehelp.c gtroff: fatal error: can't find macro file an echo '#endif /* HAVE_LIBZ */' >> hugehelp.c The tmac package that comes with groff-1.17.2 on AIX doesn't have an.tmac, however it does have andoc.tmac (the "modern" an.tmac, most of the newer an.tmac's is just running andoc.tmac anyway, which again runs either doc.tmac or an-old.tmac) However AIX 'nroff' does have tmac.an (nroff names the files differently), but it doesn't have tmac.andoc. Go figure. What about using '-man' if NROFF is "nroff", and '-mandoc' if NROFF is "gnroff"? Would that create any trouble? My linux box has groff-1.18.1 with both an.tmac and andoc.tmac, but as I said AIX' groff only has andoc.tmac. I checked around a bit, and groff seems to have andoc.tmac on at least AIX, Solaris, Linux, IRIX and cygwin. IIRC andoc.tmac is an original groff "invention", so it's probably always there. -Tor ------------------------------------------------------- The SF.Net email is sponsored by EclipseCon 2004 Premiere Conference on Open Tools Development and Integration See the breadth of Eclipse activity. February 3-5 in Anaheim, CA. Received on 2004-02-02
https://curl.haxx.se/mail/lib-2004-02/0017.html
CC-MAIN-2019-26
refinedweb
285
63.86
A static site generator (SSG) is a tool for building informational websites such as blogs and documentation repositories. SSGs allow technical users to build websites that are faster and more secure than ones running on dynamic platforms such as Wordpress, without having to write each HTML page. There are many SSGs out there already, such as Jekyll and Hugo, but many people opt to write their own – either so that they fully understand it and can be more productive, or to meet custom needs. After this tutorial, you'll: At the end, you'll have a full SSG that you can use as is or extend for your own requirements. A basic SSG takes in a list of Markdown files, converts them to HTML, and inserts them into different predefined HTML templates. Beyond that, most SSGs have the concept of frontmatter to define metadata such as title and publish date for each Markdown file. SSGs also usually have global configuration files, containing general information about the site such as its name and domain. Before we start dealing with files, we're going to implement our SSG using strings. This will serve as an initial proof of concept. We'll start by defining the main functions we'll use. Create a new Python repl and enter the following code in main.py. def load_config(): pass def load_content_items(): pass def load_templates(): pass def render_site(config, content, templates): pass def main(): config = load_config() content = load_content_items() templates = load_templates() render_site(config, content, templates) main() This skeleton defines the program flow: Throughout this tutorial, we will keep to this flow, even as we expand and refine its individual elements. Now we need to import some modules. At the top of main.py, enter the following line. import markdown, jinja2, toml, re All four of these modules are essentially parsers: markdown: This module will render Markdown. jinja2: The Jinja templating language, which we will use to create HTML templates that we can enhance with Python-esque code. toml: We will use TOML (Tom's Obvious, Minimal Language) for post frontmatter and global configuration. re: We'll use Python's regular expressions (regex) module for some additional, very light, parsing not provided by the three packages above. Now that we have our parsers, let's add some content to parse. Add a TOML string for global site configuration at the top of the main function. def main(): config_string = """ title = "My blog" """ For now, this just defines the title of our site. Change it to whatever you want. To load this config, we'll use toml.loads on its content. Go to the load_config function at the top of main.py and give it the following parameter and content. def load_config(config_string): return toml.loads(config_string) To use this function, go back to the main function and pass config_string to this line in the main function. config = load_config(config_string) Now let's create a couple of content strings below the config string. We're going to format these strings with a block of TOML metadata terminated by a row of five plus signs ( +++++). The rest of the string will contain Markdown-formatted text. Add this block of code below the definition of config_string in the main function. content_strings = [""" title = "My first entry" date = 2021-02-14T11:47:00+02:00 +++++ Hello, welcome to my **blog** """, """ title = "My second entry" date = 2021-02-15T17:47:00+02:00 +++++ This is my second post. """] We'll parse these strings in our load_content_items function. Give the function a content_strings parameter and add the following code. def load_content_items(content_strings): items = [] for item in content_strings: frontmatter, content = re.split("^\s*\+\+\+\+\+\s*$", item, 1, re.MULTILINE) item = toml.loads(frontmatter) item['content'] = markdown.markdown(content) items.append(item) # sort in reverse chronological order items.sort(key=lambda x: x["date"],reverse=True) return items Here we use a for loop to construct a list of items from our item strings. For each one, we split up the frontmatter and content on a regular expression that will match a line of text containing five plus signs. We pass in 1 as re.split's maxsplit parameter to ensure that we only split on the first matched line, and re.MULTILINE so that our regex will work correctly in a multiline string. We then use toml.loads() to convert the frontmatter into a dictionary. Finally, we convert the Markdown in content into HTML and add it to the dictionary we just created. The result will be a dictionary that looks something like this: { 'title': 'My first entry', 'date': datetime.datetime(2021, 2, 14, 11, 47, tzinfo=<toml.tz.TomlTz object at 0x7f4032da6eb0>), 'content': '<p>Hello, welcome to my <strong>blog</strong>.</p>' } Finally, since this is a blog site, we're sorting our items dictionary in reverse chronological order. We do this by using Python's list.sort method's custom sort functionality to sort by each list entry's date value. The key parameter takes a function which it will pass each value into and use the return value to sort the list. For brevity, we've created an in-line anonymous function using a lambda expression. Back in our main function, let's pass content_strings to the load_content_items function call. content = load_content_items(content_strings) Now let's create a template string below the content strings. This is just some HTML with Jinja code in {{ }} and {% %} blocks. Add this code block beneath the definition of content_strings in the main function. template_string = """ <html> <body> <h1> {{ config.title }}</h1> {% for post in content %} <article> <h2>{{ post.title }}</h2> <p>Posted at {{ post.date }}</p> {{ post.content }} </article> {% endfor %} </body> </html> """ Each of the values inside {{ }} blocks is something we've assembled in the preceding code: config.title from the config strings, content from the content strings, and the individual values inside the Jinja for loop from each item in the content list. Note that in Jinja, post.title is equivalent to post["title"]. To load this template, we will add the following parameter and code to the load_templates function. def load_templates(template_string): return jinja2.Template(template_string) We'll also change the load_templates function invocation in the main function. templates = load_templates(template_string) Now let's populate the template with our config and content data. We'll do this using the template's render() method. This method takes a list of keyword arguments which it will use to resolve the variable references template's {{ }} and {% %} blocks. In the render_site function, add the following code: def render_site(config, content, template): print(template.render(config=config, content=content)) As our render_site invocation in main already takes the correct arguments, we can run our code now. The result should look like this: <html> <body> <h1>My blog</h1> <article> <h2>My second entry</h2> <p>Posted at 2021-02-15 17:47:00+02:00</p> <p>This is my second post.</p> </article> <article> <h2>My first entry</h2> <p>Posted at 2021-02-14 11:47:00+02:00</p> <p>Hello, welcome to my <strong>blog</strong></p> </article> </body> </html> We now have the core of our SSG. Modify the content of one of the content strings and the output will change. Add new variables to each content file's frontmatter and the template, and they will propagate through without any changes to the Python code. Next, let's create and ingest some files. First, we need to create a directory structure. In the file pane of your repl, create four directories: content, content/posts, layout and static. Your file pane should now look like this: We will put our Markdown files in content/posts, our Jinja files in layout and unprocessed files like CSS stylesheets and images in static. We're using content/posts so we can create different content types later on, such as undated pages like "About". First, we'll create our config file config.toml. In addition to the title value, we'll give it a base URL based on our repl's URL. config.toml title = "My blog" baseURL = "" Replace the all-caps text with the relevant values. Now let's put our content strings into post files. Create two files with the following content: content/posts/first-post.md title = "My first entry" date = 2021-02-14T11:47:00+02:00 +++++ Hello, welcome to my **blog**. content/posts/second-post.md title = "My second entry" date = 2021-02-15T17:47:00+02:00 +++++ This is my second post. Make as many additional posts as you want. Just remember to give each one a title, correctly formatted datestamp and some Markdown content. File names should be lowercase with no spaces, ending in the .md file extension. In contrast to our proof of concept, this will be a multi-page website, so we're going to create three HTML files in our layout directory: index.html, post.html and macros.html. index.htmlwill be the template for our homepage, showing a list of blog posts in reverse chronological order. post.htmlwill be the template for post pages, containing their rendered Markdown content. macros.htmlwill not be a template, but a container file for Jinja macros. These are reusable snippets of HTML that we can use in our templates. Create three files and populate them as follows. layout/index.html <html> {% import "macros.html" as macros %} {{ macros.head(config.title) }} <body> <h1>Posts</h1> <ul> {% for post in content.posts %} <li><a href="{{ post.url }}">{{ post.title }}</a> (posted at {{ post.date }})</li> {% endfor %} </ul> </body> </html> layout/post.html <html> {% import "macros.html" as macros %} {{ macros.head(this.title) }} <body> <h1>{{ this.title }}</h1> <p>Posted at {{ this.date }}</p> {{ this.content }} <p><a href="{{ config.baseURL }}">Return to the homepage ⤾</a></p> </body> </html> ( ⤾ is the HTML entity for "⤾".) layout/macros.html {% macro head(page_title) -%} <head> <title>{{ page_title }}</title> <link rel="stylesheet" href="/css/style.css"> </head> {% endmacro -%} The only macro we've defined is head, which will generate an HTML <head> tag containing an appropriate title for the page as well as a link to our website's stylesheet. Let's create that now. In the static directory, create a subdirectory called css. Then create a file called style.css in this subdirectory and add the following code. static/css/style.css h1 { font-family: sans-serif; margin-top: 2em; } body { font-family: serif; margin: 0 auto; max-width: 40em; line-height: 1.2em; } These are a couple of small style adjustments to improve readability and differentiate our site from an unstyled page. Feel free to add your own touches. Now that we've created our input files, let's write some code in main.py to read them and create our website. To do this, we'll be iterating our proof-of-concept code. First, at the top of the file, let's import some new modules for dealing with reading and writing files and directories. Add the second line below the first in main.py. import jinja2, markdown, toml, re import os, glob, pathlib, shutil, distutils.dir_util Then delete the config_string, content_strings and template_string definitions from the main function. First, let's ingest the configuration file. Change the load_config function as follows. def load_config(config_filename): with open(config_filename, 'r') as config_file: return toml.loads(config_file.read()) Now change this line in the main function: config = load_config(config_string) To this: config = load_config("config.toml") Next, we will ingest the content/posts directory. Change the content of the load_content_items function as follows. def load_content_items(content_directory): items = [] for fn in glob.glob(f"{content_directory}/*.md"): with open(fn, 'r') as file: frontmatter, content = re.split("^\+\+\+\+\+$", file.read(), 1, re.MULTILINE) item = toml.loads(frontmatter) item['content'] = markdown.markdown(content) items.append(item) # sort in reverse chronological order items.sort(key=lambda x: x["date"],reverse=True) return items Instead of looping through a list of strings, we're now looping through all files ending in .md in the content/posts directory using the glob method and parsing their contents. Since we're now building a real site with multiple pages, we'll need to add a couple of additional attributes to our post dictionary. Namely, slug and url. slugwill be the name of the post's Markdown file without the .mdextension. urlwill be a partial URL including the post's date and slug. For the first post, it will look like this: /2021/02/14/first-post/ Let's create the slug by using os.path.basename to get our file's filename without its full path (i.e. first-post.md rather than content/posts/first-post.md). Then we'll use os.path.splitext on the result to split the filename and extension, and we'll discard the extension. Add the following line to the for loop, below where we define item['content']. item['slug'] = os.path.splitext(os.path.basename(file.name))[0] We'll then use this slug along with our post's date to construct the full URL. We'll use Python's string formatting to ensure correct zero-padding of single-digit values for months and days. Add this line below the one we just added: item['url'] = f"/{item['date'].year}/{item['date'].month:0>2}/{item['date'].day:0>2}/{item['slug']}/" Now we can update our function invocation in main. Change this line: content = load_content_items(content_strings) To this: content = { "posts": load_content_items("content/posts") } Using a dictionary instead of a plain list will allow us to add additional content types in a later section of this tutorial. Now that we have a list of posts, let's ingest our templates so we have somewhere to put them. Jinja works quite differently from the file system and from strings, so we're going to change our load_templates function to create a Jinja Environment with a FileSystemLoader that knows to look for templates in a particular directory. Change the function code as follows. def load_templates(template_directory): file_system_loader = jinja2.FileSystemLoader(template_directory) return jinja2.Environment(loader=file_system_loader) Then, in the main function, change this line: template = load_templates(template_string) To this: environment = load_templates("layout") In the next section, we'll pass this environment to our render_site function where we'll load individual templates as we need them. Now let's render the site by writing some output files. We'll be using a directory named public for this, but you don't need to create this in your file pane – we'll do so in code. Go to the render_site function and replace its code with the following (remember to change the function parameters). def render_site(config, content, environment, output_directory): if os.path.exists(output_directory): shutil.rmtree(output_directory) os.mkdir(output_directory) We do two things here: remove the output directory and all of its content if it exists, and create a fresh output directory. This will avoid errors when running our code multiple times. Now let's write our home page by adding this code to the bottom of the function. # Homepage index_template = environment.get_template("index.html") with open(f"{output_directory}/index.html", 'w') as file: file.write(index_template.render(config=config,content=content)) Here we use our Jinja environment to load the template at layout/index.html. We then open the public/index.html file and write to it the results of rendering index_template with our config and content dictionaries passed in. The code for writing individual post files is a bit more complex. Add the for loop below to the bottom of the function. # Post pages post_template = environment.get_template("post.html") for item in content["posts"]: path = f"{output_directory}/{item['url']}" pathlib.Path(path).mkdir(parents=True, exist_ok=True) with open(path+"index.html", 'w') as file: file.write(post_template.render(this=item, config=config, content=content)) First we create the directories necessary to show our post URLs. To display a URL such as 2021/02/14/first-post/, we need to create a directory named 2021 inside public, and then nested directories named 02, 14 and first-post. Inside the final directory, we create a file named index.html and write our rendered template to it. Note the values we pass to render: variables for this post are contained in this and site-wide configuration variables are contained in config. We also pass in content to allow us to access other posts. Although we aren't using this in the post.html template right now, it's good to have the option for future template updates. Now we need to load our static files. Add this code to the bottom of the render_site function: "static", "public")distutils.dir_util.copy_tree( All this code does is copy the file tree from our static directory into our public directory. This means that our CSS file at static/css/style.css can be accessed in our HTML templates as css/style.css. Similarly, if we create a file at static/my-picture.jpg, we can reference that in our HTML or Markdown as my-picture.jpg and it will be found and loaded. Now we just need to update the function invocation in our main function. Change this line: render_site(config, content, templates) To this: render_site(config, content, environment, "public") Now run the code. You should see the public directory appear in your file pane. Look inside, and you'll see the directories and files we just created. To see your site in action, run the following commands in Replit's "Shell" tab. cd public python -m http.server This should bring up the Replit web view with your home page, as below. Click on each of the links to visit the post pages. This server will need to be restarted periodically as you work on your site. In addition to chronological blog posts, our site could do with undated pages, such as an "About" or "Contact" page. Depending on the kind of site we want to build, we may also want photo pages, or pages including podcast episodes, or any number of other things. If we give this SSG to someone else to use, they may have their own ideas as well – for example, they may want to make a site organised as a book with numbered chapters rather than as a blog. Rather than trying to anticipate everyone's needs, let's make it so we can create multiple types of content pages, and allow the user to define those types and how they should be ordered. This is simpler than it sounds, but will require some refactoring. First, let's add some content to our config.toml file to give this customization a definite shape. Add these lines below the definition of baseURL. config.toml title = "My site" baseURL = "" types = ["post", "page"] post.dateInURL = true post.sortBy = "date" post.sortReverse = true page.dateInURL = false page.sortBy = "title" page.sortReverse = false Here we've told our site generator we want two kinds of pages – a post type, which we will use for blog posts, and a page type, which we will use for evergreen content such as contact details and general site information. Below that, we've used TOML's dictionary syntax to specify some characteristics of each type. By creating these settings, we'll make it possible to sort a content type by any attribute in its frontmatter. To implement this, let's first import a new module at the top of main.py. Add the third line to your file, below the first two. import jinja2, markdown, toml, re import glob, pathlib, os, shutil, distutils.dir_util import inflect The inflect module allows us to turn singular words into plurals and vice versa. This will be useful for working with the types list from our configuration file. Change the load_config function to resemble the following. def load_config(config_filename): with open(config_filename, 'r') as config_file: config = toml.loads(config_file.read()) ie = inflect.engine() for content_type in config["types"]: config[content_type]["plural"] = ie.plural(content_type) return config This code will expand the dictionaries we load from our config file with a key containing the type's plural. If we were to print out our config dictionary at this point, it would look like this: { "title": "My site" "baseURL": "" "types": ["post", "page"] "post": { "plural": "posts", "dateInURL": true, "sortBy": "date", "sortReverse": true }, "page": { "plural": "pages", "dateInURL": true, "sortBy": "title", "sortReverse": false } } Now let's modify load_content_items to deal with multiple, user-defined content types. First, we need to change the function to take our config dictionary as an additional parameter. Second, we'll put all of our function's current content in an inner function named load_content_type. Your function should now look like this: def load_content_items(config, content_directory): def load_content_type(content_type): items = [] for fn in glob.glob(f"{content_directory}/*.md"): with open(fn, 'r') as file: frontmatter, content = re.split("^\+\+\+\+\+$", file.read(), 1, re.MULTILINE) item = toml.loads(frontmatter) item['content'] = markdown.markdown(content) item['slug'] = os.path.splitext(os.path.basename(file.name))[0] item['url'] = f"/{item['date'].year}/{item['date'].month:0>2}/{item['date'].day:0>2}/{item['slug']}/" items.append(item) # sort in reverse chronological order items.sort(key=lambda x: x["date"],reverse=True) return items To load from the correct directory, we will need to change this line: for fn in glob.glob(f"{content_directory}/*.md"): To this: for fn in glob.glob(f"{content_directory}/{config[content_type]['plural']}/*.md"): Here we're using the plural of the content type we defined earlier. This will ensure that items of type "post" can be found in "content/posts" and items of type "page" can be found in "content/pages". We now need to add code to respect our configuration settings. We'll do this by changing this line: item['url'] = f"/{item['date'].year}/{item['date'].month:0>2}/{item['date'].day:0>2}/{item['slug']}/" To this: if config[content_type]["dateInURL"]: item['url'] = f"/{item['date'].year}/{item['date'].month:0>2}/{item['date'].day:0>2}/{item['slug']}/" else: item['url'] = f"/{item['slug']}/" Now we'll sort according to the configuration file by changing this line: # sort in reverse chronological order items.sort(key=lambda x: x["date"],reverse=True) To this: # sort according to config items.sort(key=lambda x: x[config[content_type]["sortBy"]], reverse=config[content_type]["sortReverse"]) We can complete this load_content_items function by writing some code to iterate through our site's configured content types, calling load_content_type for each one. Add the following code below the definition of load_content_type (ensure that it's de-indented so as to be part of load_content_items). content_types = {} for content_type in config["types"]: content_types[config[content_type]['plural']] = load_content_type(content_type) return content_types Then in the main function, change this line: content = { "posts": load_content_items("content/posts") } To this: content = load_content_items(config, "content") Now we need to change our output code in render_site to render each content type with its own template. As we did with load_content_items, we'll start by moving the post-creating for loop into an inner function, this time named render_type. Alter your render_site function so that it resembles the following. def render_site(config, content, environment, output_directory): def render_type(content_type): # <-- new inner function # Post pages post_template = environment.get_template("post.html") for item in content["posts"]: path = f"public/{item['url']}" pathlib.Path(path).mkdir(parents=True, exist_ok=True) with open(path+"index.html", 'w') as file: file.write(post_template.render(this=item, config=config)) if os.path.exists(output_directory): shutil.rmtree(output_directory) os.mkdir(output_directory) for content_type in config["types"]: # <-- new for loop render_type(content_type) # !!! post for loop moved to inner function above # Homepage index_template = environment.get_template("index.html") with open("public/index.html", 'w') as file: file.write(index_template.render(config=config, content=content)) # Static files distutils.dir_util.copy_tree("static", "public") Then change this line in the render_type inner function that loads the post template: post_template = environment.get_template("post.html") Into this line that loads a template for the provided content type: template = environment.get_template(f"{content_type}.html") Alter the for loop below that line to use the content type's plural. for item in content[config[content_type]["plural"]]: Finally, change post_template in the loop's final line to template. file.write(template.render(this=item, config=config, content=content)) Now that we've done all that work to generify our code, all that's left is to create our pages. First, let's create a page template at layout/page.html. Use the following code. <html> {% import "macros.html" as macros %} {{ macros.head(this.title) }} <body> <h1>{{ this.title }}</h1> {{ this.content }} <p><a href="{{ config.baseURL }}">Return to the homepage ⤾</a></p> </body> </html> This is just our post.html template without the date. Now create a new subdirectory in content called pages. Inside that subdirectory, create a file named about.md and put the following content in it. title = "About" +++++ This website is built with Python, Jinja, TOML and Markdown. This is sufficient to create a new page at /about/, but it won't be linked anywhere. For that, we'll need to create a global navigation bar for our site. Create the following additional macro in layout/macros.html. {% macro navigation(pages) -%} <nav><ul> {% for page in pages %} <li><a href="{{ page.url }}">{{ page.title }}</a></li> {% endfor %} </ul></nav> {% endmacro -%} Then include the macro in index.html, page.html and post.html by inserting the following code just underneath {{ macros.head(this.title) }}. {{ macros.navigation(content.pages) }} Finally, add the CSS below to static/css/style.css to apply light styling to the navigation bar. nav ul { list-style-type: none; text-align: right; } Run your code and preview your site with cd public && python -m http.server in the repl shell, and you should see something like this: We've created a flexible SSG capable of generating many different types of HTML pages, which can be served from any web server. Apart from fleshing out the templates and adding new content types, you might want to expand the generator's functionality to allow things like: You can find our SSG repl below:
https://docs.replit.com/tutorials/16-static-site-generator
CC-MAIN-2021-25
refinedweb
4,342
59.3
Hi David, what about using a different namespace for the label element? Carsten > -----Original Message----- > From: David Crossley [mailto:crossley@indexgeo.com.au] > Sent: Thursday, November 08, 2001 9:26 AM > To: cocoon-dev@xml.apache.org > Subject: SVG templates are broken XML > > > Hopefully this issue will go away when we get rid of > the side-bar image buttons. However, it may indicate > some other issue, so i will raise it again. > > See background info at issue 4) below. Basically, the > svg template files at documentation/svg/*.xml are all > broken according to the svg10.dtd, mainly because they > have an extra <label> element inside the <text> element. > > This has drastic effect when you try to declare the > SVG DTD and then do "build docs". Here is the resultant > error message ... > -------------- > FATAL_E 10050 [ ] (): Error in TraxTransformer: > javax.xml.transform.TransformerException: The current > document is unable to create an element of the requested > type (namespace:, name: label). > -------------- > > The full cocoon.log is attached. > --David > > > Date: Sat, 3 Nov 2001 01:03:09 +1100 > > Subject: XML validation during build docs > > From: David Crossley <crossley@indexgeo.com.au> > > > > OK, i have XML validation working now during build docs. > > It revealed some validation errors - nothing too drastic. > > I have mended all the broken xdocs. > > > > These are the steps that i took to get it going. Basically > > every XML instance document must declare its ruleset. > > Step 4 is a worry and we need to resolve it. The rest can > > be committed when ready. > > > > 1) in cocoon.xconf set the parser parameter "validate" > > > > 2) add initial internal DTD to both *.roles config files > > > > 3) add an initial external DTD for book.xml documents > > and add a Declaration to each */book.xml > > ... is there a proper DTD somewhere? > > > > 4) declare the DTD for each SVG template in > > documentation/svg/*.xml > > I got the final release svg10.dtd from W3C. However, > > i encountered some serious issues. Our SVG files are > > broken according to the SVG DTD ... > > a) We have an extra "label" element inside the "text" > > element, which is not allowed by the DTD. > > b) There is no attribute "xmlns:xlink" for the svg element, > > yet our files have that. > > > > As a workaround to get the rest of the validation run > > happening, i have written a minimal svg DTD based on > > those simple XML files to reflect their current structure. > > > > --David > --------------------------------------------------------------------- To unsubscribe, e-mail: cocoon-dev-unsubscribe@xml.apache.org For additional commands, email: cocoon-dev-help@xml.apache.org
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200111.mbox/%3CGMEBIBHGAOFGJCDPJANDCEEEDBAA.cziegeler@sundn.de%3E
CC-MAIN-2015-11
refinedweb
413
61.53
#include <HelixIF.H> In 3D, if a_vertical is false, the given function is restricted to the x-y plane (z = 0), and this restricted function is rotated around the z-axis at the specified rate as z changes. In 3D, if a_vertical is true, the given function is restricted to the x-y plane (z = 0), but this x-y cross section is oriented vertically and swept in a helix at the specified rate. In 2D, the given function is simply returned. Constructor specifying one implicit function to be rotated, the rotation rate, and whether the domain is on the inside (a_inside), i.e. where the function is negative. Copy constructor. Destructor. Pass this call onto the IFs contained in this IF class. Reimplemented from BaseIF. References BaseIF::boxLayoutChanged(), and m_impFunc. Referenced by boxLayoutChanged().
http://davis.lbl.gov/Manuals/CHOMBO-SVN/classHelixIF.html
CC-MAIN-2017-17
refinedweb
134
57.16
I’ve released a module for rendering your gym environments in Google Colab. Since Colab runs on a VM instance, which doesn’t include any sort of a display, rendering in the notebook is difficult. After looking through the various approaches, I found that using the moviepy library was best for rendering video in Colab. So I built a wrapper class for this purpose, called colabgymrender. apt-get install -y xvfb python-opengl ffmpeg > /dev/null 2>&1 pip install -U colabgymrender Wrap a gym environment in the Recorder object. env = gym.make("CartPole-v0") env = Recorder(env, <directory>, <fps>) If you specify a frame… In this project, we’ll write code to crop images of your eyes each time you click the mouse. Using this data, we can train a model in reverse, predicting the position of the mouse from your eyes. We’ll need a few libraries # For monitoring web camera and performing image minipulations import cv2# For performing array operations import numpy as np# For creating and removing directories import os import shutil# For recognizing and performing actions on mouse presses from pynput.mouse import Listener Let’s first learn how pynput’s Listener works. pynput.mouse.Listener creates a background thread that records mouse… In this project, I’ll walk through an introductory project on tabular Q-learning. We’ll train a simple RL agent to be able to evaluate tic-tac-toe positions in order to return the best move by playing against itself for many games. First, let’s import the required libraries Note that tabular q-learning only works for environments which can be represented by a reasonable number of actions and states. Tic-tac-toe has 9 squares, each of which can be either an X, and O, or empty. Therefore, there are approximately 3⁹ = 19683 states (and 9 actions, of course). Therefore, we have a table… Here, I’ll walk through a machine learning project I recently did in a tutorial-like manner. It is an approach to generating full images in an artistic style from line drawings. I trained on 10% of the Imagenet dataset. This is a dataset commonly used for benchmarks in computer vision tasks. The Imagenet dataset is not openly available; it is restricted to those undergoing research which requires use of it to compute performance benchmarks for comparing with other approaches. Therefore, it is typically required that you submit a request form. But if you are just using it casually, it is available… This paper proposes Wav2Lip, an adaptation of the SyncNet model, which outperforms all prior speaker-independent approaches towards the task of video-audio lip-syncing. The authors note that, while prior approaches typically fail to generalize when presented with video of speakers not present in the training set, Wav2Lip is capable of producing accurate lip movements with a variety of speakers. They continue to summarize the primary intentions of the paper: I am a high-school student studying and researching in ML. I work on projects in Python, mostly using TensorFlow.
https://ryanrudes.medium.com/?source=post_internal_links---------2----------------------------
CC-MAIN-2021-21
refinedweb
508
51.38
RFID and IoT based Remote Access Door Lock System Introduction: RFID and IoT, ESP8266 RFID based Remote Access Door Lock- In this tutorial, you will learn how to make RFID and IoT based Remote Access Door Lock system using Nodemcu ESP8266 Wifi module, MFRC522 RFID Module, Electronic Lock, and Blynk application. With the help of this project, you can remotely monitor your door lock from anywhere in the world with your iPhone or Android device. In the cell phone app I added two tabs, one is used for the monitoring, each time a user swipes an RFID card a message is received. The other tab is used for remote access control. When all the buttons are turned ON it means the admin has given access to all the three users. If all the buttons are turned off, then the users won’t be able to open the door lock. In order to open the door lock, permission should be granted by the admin. Note: For the practical demonstration and step by step explanation, watch the video tutorial given at the end of this article. In this tutorial, we will cover, - MFRC522 RFID module technical specifications and Pinout - Complete circuit diagram explanation and finally - Nodemcu ESP8266 Wifi Module Programming. Without any further delay, let’s get started!!! The components and tools used in this project can be purchased from Amazon, the components Purchase links are given below: MFRC522 RFID module with tags: Nodemcu ESP8266 Wifi Module: 12v Electronic Door Lock / Elock / Solenoid Lock: *Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way! RFID and IoT: Radiofrequency RFID and IoT technologies when mixed together, so many amazing monitoring and control system projects can be designed. With the help of this project, I will explain how to use RFID and IoT “Internet of Things” technologies together to make a remote access door lock control system. I have been using RFID modules in different Arduino based projects. List of the RFID and Arduino based projects: · Arduino RFID Servo Motor Control system for Car Parking “MFRC522” · RFID & GSM based student Attendance Alert message to parents · RFID based students attendance system with message Alert · Bike anti theft system using MFRC522 RFID module · Raspberry Pi Home Automation using RC522 RFID, Smart Home In this project, for the first time, I am using RFID with the Nodemcu ESP8266 Wifi module, just to explain how RFID and IoT can be used to build something amazing that can be used in real life. About the MFRC522 RFID Module: As you can see this is the MFRC522 RFID module. The MFRC522 is a highly integrated reader/writer IC for contactless communication at 13.56 MHz. This module has a total of 8 male headers which are clearly labeled as SDA, SCK, MOSI, MISO, IRQ, GND, RST, and 3.3V. As per the datasheet, the typical voltage is 3.3V while the maximum voltage is 3.6 volts. This module can be easily powered up using the Nodemcu ESP8266 Wifi Module. wires the Electronic Lock can be controlled. These two wires will be connected with the relay common and normally open legs. RFID and IoT based Remote Access Door Lock Circuit Diagram: As you can see the circuit diagram is very simple, let’s start with the MFRC522 RFID module, as you can see the 3.3v pin of the RFID module is connected with the Nodemcu ESP8266 Wifi module, the RST pin of the RFID module is connected with the digital pin 2, GND pin of the RFID module is connected with the ground pin of the Nodemcu module, the IRQ pin is not connected, the MISO pin is connected with the digital pin D6, MOSI pin is connected with the digital pin D7, SCK pin of the RFID module is connected with D5, and lastly the SDA pin of the MFRC522 RFID module is connected with the digital pin D4 of the Nodemcu ESP8266 Wifi Module. The 12V Electronic door lock is controlled using a one channel relay module. As you can see the GND wire of the electronic door lock is connected with the ground of the power supply. While the 12V wire of the electronic lock is connected with the common of the relay module and the normally open leg of the relay module is connected with the 12v power supply. No by turning ON and turning OFF this relay module the electronic door lock can be opened and closed. The relay module is controlled using the D0 pin of the Nodemcu ESP8266 Wifi module. Finally, this is the regulated 5V power supply based on the LM7805 voltage regulator. This 5V regulated power supply is used to power up the Nodemcu Module. J1 is the female power jack and this is where we connect the 12v power supply. Module and a wire from the power supply ground is connected with the ground pin of the Nodemcu module. So, that’s all about the circuit diagram, now let’s make the blynk application, and follow the same exact steps. Blynk Application Designing for Remote Access Door Lock: I always first start with the Blynk application designing, this way I know which virtual pins I have to use in the programming. Moreover, this also helps me in checking my code, as I keep testing my project. So, first let’s start with the Blynk application designing. - First of all, open the blynk application. - Click on the new project and enter the project name as “IoT RFID”. - tabs and add it. - Click on the tab and add two tabs, with names MONITORING AND REMOTE ACCESS. - While the MONITORING tab is selected, click on the screen and search for the terminal widget and it. - Now click on the terminal widget and select the virtual pin V2 and set the add newline to yes. - Now select the REMOTE ACCESS tab. - Click on the screen and add three buttons. - Click on the first button, set the name, and select the virtual pin V3, select the button mode as SWITCH. Select the font size as per your requirement. - Click on the second button, set the name, and select the virtual pin V4, select the button mode as SWITCH. Select the font size as per your requirement. - Click on the third button, set the name, and select the virtual pin V5, select the button mode as SWITCH. Select the font size as per your requirement. In this project, I considered three users, ENG. FAHAD, ELECTRONIC CLINIC, and JAMSHAID KHAN. Still, if you find it hard to follow, you can watch the video tutorial given at the end of this article. MFRC522 RFID Interfacing with Nodemcu: I connected the MFRC522 RFID Module and the 12V electronic door lock as per the circuit diagram already explained. Now let’s have a look at the Arduino programming. RFID and IoT based Remote Access Door Lock system Nodemcu ESP8266 Programming: RFID and IoT based Remote Access Door Lock system Nodemcu ESP8266 Program Explanation: Before you start the programming, first of all, make sure that you download all the necessary libraries. So, first of all, I started by including the libraries needed for the RFID and IoT based Remote Access Door Lock system. #include <SPI.h> #include <MFRC522.h> #define BLYNK_PRINT Serial #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> Next, I defined pins for the SS, RST, and Electronic Lock. #define SS_PIN 4 // sda #define RST_PIN 2 int elock = D0; MFRC522 mfrc522(RST_PIN, SS_PIN); // Create MFRC522 instance. This is the authentication code that was sent via email; I simply copied and paste it over here. char auth[] =”iyzplTOdDMzqRJN7wo_LVlobNBbzjO21″; This is the router name. char ssid[] = “ZONG MBB-E8231-6E63”; This is the password. char pass[] = “08659650”; Next, I defined a timer. SimpleTimer timer; fflag, eflag, and jflag are variables of the type integer, which will be used as the flags. All the flags are assigned zeros, which means that by default the users have no access. So, the flags value can be zero or one. 0 means no access while 1 means that the use can control the electronic lock using the RFID tag. int fflag = 0; int eflag = 0; int jflag = 0; The terminal widget is assigned the virtual pin V2. WidgetTerminal terminal(V2); Inside the void setup() function. I activated the serial communication for debugging purposes. While 9600 is the baud rate. The electronic lock is set as the output and is turned OFF using the digitalWrite() function. iot_rfid is a user-defined function that is executed after every 1 second. The RFID code is placed inside this function. void setup() { Serial.begin(9600); Blynk.begin(auth, ssid, pass); pinMode(elock,OUTPUT); digitalWrite(elock, LOW); SPI.begin(); // Init SPI bus mfrc522.PCD_Init(); // Init MFRC522 card //Serial.println(“Scan a MIFARE Classic PICC to demonstrate Value Blocks.”); timer.setInterval(1000L, iot_rfid); } Then starts the void loop() function. As you can see inside the void loop() function we have only two functions the timer.run() and Blynk.run(). void loop() { timer.run(); // Initiates SimpleTimer Blynk.run(); } The iot_rfid() function is a user-defined function, which has no return type and does not take any argument as the input. 99% of this code is exactly the same as used in my previous projects which I have already explained in very detail, links to the related RFID based projects are given in the description. In this code, I did a very little modification……… I added these flags…. void iot_rfid() { // Prepare key – all keys are set to FFFFFFFFFFFFh at chip delivery from the factory. MFRC522::MIFARE_Key key; for (byte i = 0; i < 6; i++) { key.keyByte[i] = 0xFF; } // Look for new cards if ( ! mfrc522.PICC_IsNewCardPresent()) { return; } // Select one of the cards if ( ! mfrc522.PICC_ReadCardSerial()) { return; } // Now a card is selected. The UID and SAK is in mfrc522.uid. // Dump UID Serial.print(“Card UID:”); for (byte i = 0; i < mfrc522.uid.size; i++) { Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? ” 0″ : ” “); Serial.print(mfrc522.uid.uidByte[i], DEC); } Serial.println(); // Dump PICC type byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak); // Serial.print(“PICC type: “); //Serial.println(mfrc522.PICC_GetTypeName(piccType)); if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K && piccType != MFRC522::PICC_TYPE_MIFARE_4K) { //Serial.println(“This sample only works with MIFARE Classic cards.”); return; } // defining Cards here So, this condition means, if the RFID card identification number is 66 71 176 30 and the fflag value is 1 then send a message to the serial monitor and terminal widget on the blynk app and Open the door for 5 seconds. When the fflag value is 0 the door will not be opened. So the fflag value can be 0 or 1 which is controlled using the blynk app. Similarly, for the remaining two conditions. if( ((mfrc522.uid.uidByte[0] == 66) && (mfrc522.uid.uidByte[1] == 71) && (mfrc522.uid.uidByte[2] == 176) && (mfrc522.uid.uidByte[3] == 30)) && (fflag == 1) ) { Serial.println(“Eng. Fahad”); Blynk.virtualWrite(V2, “Eng. Fahad” ); digitalWrite(elock, HIGH); delay(5000); digitalWrite(elock, LOW); } else if(( (mfrc522.uid.uidByte[0] == 00) && (mfrc522.uid.uidByte[1] == 47) && (mfrc522.uid.uidByte[2] == 115) && (mfrc522.uid.uidByte[3] == 137))&& (eflag == 1) ) { Serial.println(“Electronic Clinic”); Blynk.virtualWrite(V2, “Electronic Clinic” ); digitalWrite(elock, HIGH); delay(5000); digitalWrite(elock, LOW); } else if( ((mfrc522.uid.uidByte[0] == 198) && (mfrc522.uid.uidByte[1] == 69) && (mfrc522.uid.uidByte[2] == 34) && (mfrc522.uid.uidByte[3] == 75))&& (jflag == 1) ) { Serial.println(“Jamshaid Khan”); Blynk.virtualWrite(V2, “Jamshaid Khan” ); digitalWrite(elock, HIGH); delay(5000); digitalWrite(elock, LOW); } else Serial.println(“unregistered user”); } The following three functions are used to send values 0 and 1 using the buttons through virtual pins V3, V4, and V5. These values are then stored in fflag, eflag, and jflag; depending on the value stored in these flags, the access is given to the users. 0 means no access while 1 means giving access to the person. // in Blynk app writes values to the Virtual Pin 3 BLYNK_WRITE(V3) { fflag = param.asInt(); // assigning incoming value from pin V3 to a variable // Blynk.virtualWrite(V2, fflag ); } // in Blynk app writes values to the Virtual Pin 4 BLYNK_WRITE(V4) { eflag = param.asInt(); // assigning incoming value from pin V4 to a variable } BLYNK_WRITE(V5) { jflag = param.asInt(); // assigning incoming value from pin V5 to a variable } In the end, I successfully tested my project “RFID and IoT based Remote Access Door Lock system”. Watch Video Tutorial:
https://www.electroniclinic.com/rfid-and-iot-esp8266-rfid-based-remote-access-door-lock-rfid-iot/
CC-MAIN-2021-10
refinedweb
2,075
65.73
ECMAScript 6: the modules As a JavaScript application begins to grow, it becomes harder and harder to organize and manage. It is therefore advisable to cut it into small functional pieces that are easier to handle and whose stewardship is less problematic. Beyond the division into functions and classes one can also cut the code into coherent modules having a certain level of abstraction. On the other hand a module embarks its stewardship and becomes easy to use and reuse. Unfortunately, JavaScript does not know the namespaces that exist in multiple languages. With ES5 you can get by with objects and closures and there are a multitude of implementations. ES6 finally offers us a native modularization! ES6 modules The ES6 modules: - have a simple syntax and are based on the division into files (a module = a file), - are automatically in "strict" mode, - provide support for asynchronous loading. Modules must expose their variables and methods explicitly. So we have two keywords: - export: to export everything that must be accessible outside the module, - import: to import everything that must be used in the module (and that is exported by another module). Export and import Export Since everything written in a module is internal to it, you have to export what you want to make usable by the other modules. To export, use the export keyword: export function rename(name) { var person = new Person(); return person.changeNom(name); } export class Identite { // code } function verify() { // code } Here we export the rename method and the Identite class, but the verify method remains internal to the module. Another way to do this is to group what needs to be exported: function rename(name) { var person = new Person(); return person.changeNom(name); } class Identite { // code } function verify() { // code } export { rename, Identite }; Import To import into a module something that is exported by another module we use the keyword import: import { rename, Identite } from "./identite.js"; //We can also rename what we export with the same syntax. import { rename as renameIdentite, Identite } from "./identite.js"; //If we want to import everything from a module we can use this syntax: import * from "./identite.js"; We saw above that the syntax is simple. What is less is that currently it is not recognized by our browsers and must therefore manage to operate all that. On the other hand, ES6 does not specify how modules should be loaded, in other words the implementation of this aspect is left to the discretion of developers, probably because it was difficult to define a universal specification. In addition to the development of the client aspect of an application (the frontend) we do not only have JavaScript, there is necessarily also CSS code with probable use of a Sass type preprocessor. It would be nice to have a tool that allows us to manage all that. The good news is that it exists! There are even several solutions but the one that seems to have the most success is Webpack. It is given modules with dependencies (js, css, png ...) and it transforms all this into usable static assets: Webpack Installation To use Webpack you must first install it. But you must already have: node.js, so install it if you do not have it, it will serve you for many other things! npm, it's the dependency manager of node.js, you also have to install it if you do not have it (the good news is that it installs with node.js). You can then install Webpack: npm install webpack -g Then you have to initialize npm: npm init Accept all defaults (they are only of interest if you want to publish a package), so you create a package.json file like this: { "name": "test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } You are now ready to install items in your project.. If you look at your package.json file you will find these added dependencies: "devDependencies": { "babel-core": "^6.26.0", "babel-loader": "^7.1.2", "babel-preset-es2015": "^6.24.1", "webpack": "^3.10.0" }
http://nssn.devdojo.com/articles/ecmascript-6-the-modules
CC-MAIN-2020-05
refinedweb
686
54.83
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards #include <boost/phoenix/core/reference.hpp> Values are immutable constants. Attempting to modify a value will result in a compile time error. When we want the function to modify the parameter, we use a reference instead. For instance, imagine a lazy function add_assign: void add_assign(T& x, T y) { x += y; } // pseudo code Here, we want the first function argument, x, to be mutable. Obviously, we cannot write: add_assign(1, 2) // error first argument is immutable In C++, we can pass in a reference to a variable as the first argument in our example above. Yet, by default, the library forces arguments passed to partially applied functions.
http://www.boost.org/doc/libs/1_49_0/libs/phoenix/doc/html/phoenix/modules/core/references.html
CC-MAIN-2014-42
refinedweb
130
55.74
1-781-743-2119 ext 2 Chat PLEASE NOTE: this paper covers version 11.0 of our SDK and is made available for archival purposes. For newer versions of this whitepaper, see: When creating a new application using the WebDocumentViewer, whether you are migrating from our older web control (WebImageViewer / WebAnnotationViewer), or you are starting a new web project from scratch, there are a few steps you will need in order to get the project up and running. We will use this document to discuss the requirements of using the WebDocumentViewer, and then walk through its creation, step by step. WebDocumentViewer (and its companion Thumbnail Viewer, WebDocumentThumbnailer) is a modern HTML5 compatible web viewing control. It replaces WebAnnotationViewer (WebImageViewer) and WebDocumentThumbnailer replaces WebThumbnailViewer. These older controls are still supported, but are considered legacy controls with no new features being added. As Microsoft further deprecates 'classic asp.net web apps', these legacy controls will become more and more difficult to maintain and support. Customers using WAV/WIV and WTV are encouraged to begin migration to WDV with or without WDT. We will use this KB to discuss the requirements of using the WebDocumentViewer, and then walk through its creation, step by step. This document and our SDK assume that you're a developer familiar with basic use of Visual Studio, IIS Express or IIS, and general web application development practices using MS Visual Studio 2013 or later. The samples will be using an HTML 5 approach in a non-MVC application targeting .NET framework 4.5.2 in a 64 bit application. ALSO NOTE: This document covers a standard ASP.NET web app, not ASP.NET Core. We do have support for ASP.NET Core targeting .NET framework (not pure .NET Core), but that is beyond the scope of this document (please see FAQ: Support for ASP.NET Core / .NET Core). If you have an. On SDK installation, they are placed in: C:\Program Files (x86)\Atalasoft\DotImage 11.0\bin\WebResources\WebDocViewer\ provide NuGet packages for our components, but this example will assume you've installed and activated our SDK locally. If you wish to use NuGet with our SDK, please check out our NuGet tutorial. (Please note that as of this writing (September 2018) the NuGet tutorial is out of date.. there are outdated script links which will result in a non-working application.. Support recommends using the information in this WDV whitepaper (This current document and not the NuGet tutorial) for the time being. SimpleWDVTestApp hosted in IIS under: c:\inetpub\wwwroot\SimpleWDVTestApp\ Then you'd copy your licenses from: C:\users\YOUR_USERNAME\AppData\Local\Atalasoft\DotImage 11.0\ to c:\inetpub\wwwroot\SimpleWDVTestApp\bin\ We're going to be creating a very minimal WebDocumentViewer (WDV) based application. We will add a WebDocumentThumbnailer (WDT)at a later stage. It's just going to open a document for viewing and allow for annotation and saving using defaults as much as possible. While this may seem not too useful, it's the fundamental minimum you need to get the WDV running. Don't worry, we will get fancier in a bit. For now, we're going to start with the basics. The first step will be to open Visual Studio 2013. You can use later versions of Visual Studio, however for the purpose of this project, 2013 is the platform we will be following. From there, you will create a new ASP.Net web application. Lets also target .NET 4.5.2 as our target framework, since it is the minimum version. " /> using System; using System.IO; using System.Web; using Atalasoft.Imaging.WebControls; namespace SimpleWDVTestApp { public class WebDocViewerHandler : WebDocumentRequestHandler { public WebDocViewerHandler() { } } } <form id="form1" runat="server"> <div> </div> </form> <form id="form1" runat="server"> <div id="_toolbar1"></div> <div id="_containerViewer" style="width: 710px; height: 600px; display: inline-block;"></div> </form> <script type="text/javascript"> var _viewer = null; var _docUrl = 'SampleImages/DocCleanMultipage.tif'; // Initialize Web Scanning and showscrollbars: true, forcepagefit: true }); }); </script> Alright. If you've followed everything this far, you should have a ready-to-run application. Go ahead and have Visual studio build and run. If everyting worked out right, it should look like this: Congratulations! you've built the most basic working WebDocumentViewer! OK, so the interface is really minimal and all it does is opens a single document at startup. It has annotations available but no option to save your changes. It also (as currently configured) has no support for PDF (the base SDK support out of the box supports PNG, BMP, TIF, GIF, JPEG, and several others, but not PDF). That's OK, we can make it better. So, lets flesh this out.. we will start by showing you how to add support for saving, then we'll show you how to programmatically open an arbitrary file, and then we'll add support for viewing PDF in the viewer. The WebDocumentViewer has "out of the box" saving capabilities, but the save button is hidden in our current app/view. This is because the default saving requires at a minimum that you specify a save folder in the configuration. savepath: 'Saved/', // relative url to save annotation data to showscrollbars: true, forcepagefit: true }) Thats it for basic saving. If you run your app again, you should now see a save option on the toolbar.. if you add some annotations to the document and then hit save.. it will save a copy to the Saved/ directory with the same name as the original and will save an xmp sidecar file with the annotations. Look in Saved and you should see a DocCleanMultipage.tif and DocCleanMultipage.xmp file now in the Saved directory This is the super basic out of the box saving.. We could have just included the savepath in the initial config and it would already have been there, but it's important to let you know that the save button does not show automatically unless that option is set. When we get to advanced functionality, we will revisit saving to do something slightly more useful.. like saving to arbitrary locations or even preparing a save to send to a database or web service. This next upgrade, we will add buttons to open some additional files. We already had you copy some test files to SampleImages before. If you haven't done so, add a directory called SampleImages to the root of the project and add the files from SampleImages.zip to that directory. For this example we are going to make super simple HTML buttons. You can use any valid means of triggering programmatically, using third-party controls etc.. the only key issue is that you must never cause / call a postback. The WebDocumentViewer is essentially a Single Page Application (SPA) pattern and works with asynchronous callbacks. Causing a postback (resubmitting/loading the page) completely starts over from scratch and loses all changes. We will add a button to open a different document (Gettysburgaddress.tif) as well as one to open the document that we already have present (DocCleanMultipage.tif) so you can see the proper method to implement a programmatic OpenURL. Optionally, we will disable the initial document load so that your viewer loads empty and doesn't have any document until it's loaded. The signature of the OpenUrl command is: _viewer.openUrl(DocumentUrl, AnnotationsUrl, CallbackFunction); DocumentUrl A string containing the relative path (within the web app) of the document to open. AnnotationUrl (optional) A string containing the relative path (Within the web app) of the annotations file to open. If this is left blank, then no annotations are opened and the current annotations (if any) are preserved. This can cause issues if you open a document with less pages in it than you have of annotations (you had a 3 page doc open with annotations on all pages then you openUrl(NewOnepageDoc);.. this would leave the 3 pages of annotations with the unreachable 2nd and 3rd pages hanging out awkwardly. If this is set to an empty string ('') then it will tell the control to destroy any existing annotations (so load fresh without any annotations). CallbackFunction (optional) A JavaScript function that will be called after the openUrl is completed. This is useful for situations where you need to take some specific action ONLY AFTER the new document loads.. for instance, say you are going to load a 2 page doc and want it to open "to the last page"... You can not do this: _viewer.openUrl('my2pageDoc.tif'); _viewer.showPage(1); // page indices are zero indexed so 1 is the second page If you try, it will error because the openUrl does not hold execution.. so _viewer.showPage will call before the document is open and has the page.. Instead, you'd use the callback like this: _viewer.openUrl('folderFor/my2pageDoc.tif', null, function() {_viewer.showPage(1);}); Note that the null is required as a placeholder .. you must either provide an annotations url or give it null because the THIRD argument is the callback, not eh second.. if you wanted to open a new document and clear annotations too and then scroll to the second page, the code would be: viewer.openUrl('folderFor/my2pageDoc.tif', '', function() {_viewer.showPage(1);}); Now, calling raw JavaScript is not really "a thing" it's usually called as part of some action. Maybe you have a third party grid or tree control or maybe you have some other code entirely.. either way you normally would be binding to some kind of onclick action or other. So for this example we will make HTML buttons. This is actually a good excuse to talk about postbacks. If you make an HTML button or (even worse) an ASP:Button, and do not take steps to prevent a callback, your button will break the viewer/ make it do undesirable things. This is because the viewer is following an SPA pattern and uses asynchronous Ajax calls to the back end.. a postback completely destroys all data on the control as it requests a reload. To avoid callbacks, we must ensure any onclick event is done correctly.. that it returns false (a signal to the browser to NOT do a postback) So, to put this all together, lets add a button for each test file (modify the HTML form tag to add the buttons right above the viewer divs: <form id="form1" runat="server"> <input type="button" id="btn_open_DocCleanMultipage" value="Open DocCleanMultipage" onclick="_viewer.openUrl('SampleImages/DocCleanMultipage.tif', ''); return false;" /> <input type="button" id="btn_open_GettysburgAddress" value="Open GettysburgAddress" onclick="_viewer.openUrl('SampleImages/GettysburgAddress.tif', ''); return false;" /> <input type="button" id="btn_open_dcm" value="Open DCM (pdf)" onclick="_viewer.openUrl('SampleImages/DCM.pdf', ''); return false;" /> <input type="button" id="btn_open_hamlet" value="Open Hamlet (pdf)" onclick="_viewer.openUrl('SampleImages/Hamlet.pdf', ''); return false;" /> <div id="_toolbar1"></div> <div id="_containerViewer" style="width: 710px; height: 600px; display: inline-block;"></div> </form> This will make your Default.axpx look a bit like this: and when you run it you will have some (admittedly ugly, but functional) buttons at the top of the page.. Well, the first two work but when you try and open the PDFs the viewer will go blank... So that brings us to the final improvement for this app.. PDF is a very common file format and DotImage has a lot of really awesome PDF related tools and features. However, PDF viewing is not part of the base SDK.. it requires an add-on license for our PdfReader component. It also requires that you explicitly add PDF support to applications you want to be able to view PDFs You may have noticed in the earlier stages, we added references to several PDF related dlls (Atalasoft.dotImage.Pdf.dll, Atalasoft.dotImage.PdfDoc.Bridge.dll, Atalasoft.dotImage.PdfReader.dll, Atalasoft.PdfDoc.dll). We did so because the WebControls dll requires them as dependencies.. becuase these dlls are integral to support for text searching for PDFs .. an "out of the box" feature of the control we won't be directly covering in this paper. So, first thing, if you have not added those references please revisit the earlier section on adding references to the dlls we need. This will assume you have either a valid license for our Pdf reader component or you have an active, valid evaluation license that includes the PdfIum license (in 11.0 and newer, your PdfReader addon license will create an Atalasoft.dotImage.PdfIum.lic file as this is our new PDF engine in 11.0 and newer) Now we need to add support for PDF.. this will be the first actual server-side code we need to modify past the original creation of the WebDocViewerHandler.ashx. The full updated handler will now look like this: using System; using System.IO; using System.Web; using Atalasoft.Imaging.Codec; using Atalasoft.Imaging.Codec.Pdf; using Atalasoft.Imaging.WebControls; namespace SimpleWDVTestApp { public class WebDocViewerHandler : WebDocumentRequestHandler { static WebDocViewerHandler() { RegisteredDecoders.Decoders.Add(new PdfDecoder() { Resolution = 200 }); } public WebDocViewerHandler() { } } } Believe it or not, that's all it takes.. if you're licensed for PDF reader and have those dlls referenced and have this in your handler and run your app, the PDF open buttons should now work. Up to this point, the whole setup has been bare minimum. This is intentional as we wanted to show you the minimum needed to just get WebDocumentViewer up and running and then add a bit of info for the most common first questions (how do I open other documents?, how do I save?, how do I add PDF support?). There are MANY more things we could do from here, and in a future WDV whitepaper covering more advanced topics, we'll delve into those a bit more. However, many customers want /need a Thumbnail based viewer for their WDV.. they want a thumbnail control to let users see/scroll a quick high level presentation of their document and use it to trigger viewing of the selected page on the main big viewer. So, we're going to start from scratch again to show you how to build an app using WebDocumentViewer (WDV) with WebDocumentThumbnailer (WDT). We won't be going quite as slowly (less screenshots) because most of this is review from the previous.. we will be concentrating here on some of the subtle changes needed to get that thumbnail viewer running and connected to the viewer. Many of the advanced use cases that will be covered in more advanced papers will start from this base WDV with WDT sample app. <form id="form1" runat="server"> <div style="width: 900px;"> <div id="_toolbar1"></div> <div id="_containerThumbs" style="width: 180px; height: 600px; display: inline-block;"></div> <div id="_containerViewer" style="width: 710px; height: 600px; display: inline-block;"></div> </div> </form> <script type="text/javascript"> var _viewer = null; var _thumbs = null; var _docUrl = 'SampleImages/DocCleanMultipage.tif'; // Initialize allowannotations: true, // flag to enable annotations savepath: 'Saved/', // relative url to save annotation data to showscrollbars: true, forcepagefit: true }); _thumbs = new Atalasoft.Controls.WebDocumentThumbnailer({ parent: $('#_containerThumbs'), // parent container to putthe thumbnails in serverurl: '/WebDocViewerHandler.ashx', // server handler url to send image requests to documenturl: _docUrl, // document url relative to the server handler url allowannotations: true, // flag to enable annotations viewer: _viewer, // link actions to the _viewer so they open the same doc allowdragdrop: true, showscrollbars: true }); }); </script> Congratulations! you've built the most basic working WebDocumentViewer With WebDocumentThumbnailer! We've taken the liberty of enabling saving AND of enabling drag drop - so try this - go ahead and gran an image from the thumb viewer and drag it to a different position relative to other pages.. say take page 1 and move it below page 2... the thumbnail viewer will update, the main viewer will update, AND if you save.. the saved image will match the order in which you placed them in teh viewer! If you notice, we didn't just drop in the buttons from our previous example. The openUrl works ALMOST the same but there's a key difference we wanted to highlight explicitly.. When using WDV with WDT, you do NOT openUrl on the _viewer (WDV) you must openUrl on the WDT (_thumbs) You might have even noticed that we slipped something in there already - when we gave you the viewer initialization notice how the updated WDV initialization removed the documenturl and we added it instead to the _thumbs viewer? this was intentional. So, knowing what you know now, it's really easy - we can add the same buttons from before and just change _viewer to _thumbs ...like this: <form id="form1" runat="server"> <input type="button" id="btn_open_DocCleanMultipage" value="Open DocCleanMultipage" onclick="_thumbs.openUrl('SampleImages/DocCleanMultipage.tif', ''); return false;" /> <input type="button" id="btn_open_GettysburgAddress" value="Open GettysburgAddress" onclick="_thumbs.openUrl('SampleImages/GettysburgAddress.tif', ''); return false;" /> <input type="button" id="btn_open_dcm" value="Open DCM (pdf)" onclick="_thumbs.openUrl('SampleImages/DCM.pdf', ''); return false;" /> <input type="button" id="btn_open_hamlet" value="Open Hamlet (pdf)" onclick="_thumbs.openUrl('SampleImages/Hamlet.pdf', ''); return false;" /> <div style="width: 900px;"> <div id="_toolbar1"></div> <div id="_containerThumbs" style="width: 180px; height: 600px; display: inline-block;"></div> <div id="_containerViewer" style="width: 710px; height: 600px; display: inline-block;"></div> </div> </form> It is our hope that you've been following along with the tutorial and have successfully built your solution. However, if you've run into issues or if you want a working reference app, we've implemented both the SimpleWDVTestApp and SimpleWDVWDTTestApp for you to download and run if needed. They also make great test harnesses for any experimental WDV / WDT code you want to try out... letting you start from a known-working application.007 - 2020/01/22 - TD Q10475 - INFO: WebDocumentViewer Whitepaper - Getting Started With Web Viewing (11.0 Version)
https://www.atalasoft.com/kb2/KB/50029/INFO-WebDocumentViewer-Whitepaper-Getting-Started-With-Web-Viewing-110-Version
CC-MAIN-2020-45
refinedweb
2,954
55.64
A seven segment display is a set of seven bar-shaped LED (light-emitting diode) elements, arranged to form a squared-off figure 8. It’s also the most common, simple-to-use and cheap display. The pin configuration is as follows: There are two types of Seven Segment display available in the market: - Common Cathode In common cathode, the negative terminal of all LED’s inside are connected which must be grounded using a COM port. To light up a particular LED, one need to apply positive input of +5v with current limiting resistors; - Common Anode—in common anode, the positive terminal of all the LED’s are connected that must be applied to a positive +5V supply. To light up a particular LED, connect to ground the specific pin. #NOTE: In this tutorial, we will be using common cathode LED’s For multiplexing, we will be using a BC547 transistor, which is an N-P-N transistor. You can also choose any other similar transistor like 2N3904 We need multiplexing, as it will reduce the number of output pins required for the operation. Consider if we are using 3- segments we will expect a total of 21 pins. However, by multiplexing, we will only require 10 pins. Multiplexing is achieved by using persistence of vision. Yes, the same technique used to display videos. If the frame rate is more than 25 frames, our human eye can’t detect that visual change, and hence, the image seems continuous. In SSD multiplexing, we will connect all the segments in parallel, like all the ‘a’ will be joined together and likewise. They are connected to the output port. An ‘a’ is connected to PC7, and ‘g’ is connected to PC0. Also, the dot pin is left unconnected. However, if you wish to you can connect it to PC8. Also for selecting a particular segment, the transistor base is connected to PB0 for LSB and PB2 for the MSB. As we all know, that when transistor is operated in saturated region, it act like a switch, that is the collector and the emitter gets shorted with almost a negligible drop across both the terminals. For the transistor to get shorted we need some base current. Hence, please make sure that you connect the base with a certain suitable resistance of 1k-10k so as to make transistor act as a switch safely. Typical Schematic: Sample code: #include <avr/io.h> #include <util/delay.h> volatile uint8_t inddigit[]={0,0,0}; //Global variable to Store Individual digits void ssd(uint8_t n) // FINDIng THE INDIVIDUAL DIGITS OF THE NUMBER And Multiplexing { DDRB=0xFF; PORTB=0x00; int i=0; while (n!=0) { inddigit[i]=n%10; n=n/10; i++; } for(i=0;i<3;i++) { PORTB=(1<<i); // 'i'th PORTB IS HIGH display(inddigit[i]); _delay_ms(5); PORTB=(0<<i); //'i'th PORTB IS LOW } } void display (uint8_t n1) // To Display Value on SSD { DDRC=0b11111111; PORTC=0xFF; switch(n1) { case 0: PORTC=0x7E; break; case 1: PORTC=0x30; break; case 2: PORTC=0x6D; break; case 3: PORTC=0x79; break; case 4: PORTC=0x33; break; case 5: PORTC=0x5B; break; case 6: PORTC=0x5F; break; case 7: PORTC=0x70; break; case 8: PORTC=0x7F; break; case 9: PORTC=0x7B; break; default: PORTC=0xFF; } } int main(void) { DDRC=0xFF; //INITIALIZE PORTB AS ALL OUTPUT int i=000,d=0; while(1) { i++; for(d=0;d<100;d++) //to Display the same value for a particular time before incrementing ssd(i); } } By: Tushar Gupta Nice tutorials about AVR. There is an error on your schematic, you must flip the collector (C) with the emitter (E). In this configuration the emitter should be connected to the ground and the emitter to the common cathode of the display. Thank you for notice. Will be fixed soon.
https://embedds.com/interfacing-seven-segment-with-atmega32-avr-series/
CC-MAIN-2020-24
refinedweb
640
60.04
#include <CCAMACScalerLRS4434.h> class CCAMACScalerLRS4434 : public CScaler { CCAMACScalerLRS4434(unsigned int b, unsigned int c, unsigned int n); virtual void Initialize(); virtual void Read(std::vector<unsigned long>& Scalers); virtual void Clear(); virtual unsigned int size();} This function provides very high level support for the LeCroy LRS 4434 32 channel CAMAC scaler module. The support module is intended to be used with the production readout framework but could really be used in any application with suitable adaptation on the part of the caller. Constructs a new CCAMACScalerLRS4434 object. This object can be used to manipulate the physical scaler module at the location in the CAMAC subsystem described by the constructor parameters. Sets up the module for use in data taking. The module will be software latched which requires that the LAD switch on the physical module be in the Off position. Reads the 32 scaler channels of the module and appends their values to the Scalers vector. The scalers are atomically latched, read and cleared with respect to additional counts. The clear is done as the NSCL Scaler display and analysis software all expect the scaler values to be incremental. Clears the scaler counters. The counters are all simulataneousl cleared so there is no skew in time for when the counters in the scaler begin to count again. Returns 32 the number of elements that will be added to the Scalers vector by the Read operation.
http://docs.nscl.msu.edu/daq/newsite/nscldaq-11.2/r30456.html
CC-MAIN-2017-39
refinedweb
235
60.45
John, Thank you for clarifying things for me! As far as the replacement function goes, well -- yours is right on the money. It's a simple moving average calculation and it gets the job done. I just kept getting a different result when comparing to an actual financial chart since the calculation was based on open prices. I just added a calculation for the Exponential Moving Average (based on): def ema(s, n): """ returns an n period exponential moving average for the time series s s is a list ordered from oldest (index 0) to most recent (index -1) n is an integer returns a numeric array of the exponential moving average """ s = array(s) ema = [] j = 1 #get n sma first and calculate the next n period ema sma = sum(s[:n]) / n multiplier = 2 / float(1 + n) ema.append(sma) #EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev) ema.append(( (s[n] - sma) * multiplier) + sma) #now calculate the rest of the values for i in s[n+1:]: tmp = ( (i - ema[j]) * multiplier) + ema[j] j = j + 1 ema.append(tmp) return ema I hope you can find it useful in your examples. --- John Hunter <jdhunter@...4...> wrote: ··· OK, I see what is going on. The lines are being plotted over the rectangles, so even if the rectangles are transparent, you still see the lines. There are two candlestick functions in matplotlib candlestick and candlestick2. They have slightly different call signatures and a different implementation under the hood. candlestick creates a bunch of separate lines and rectangles, candlestick2 uses collections (see the help for the matplotlib.collections module). You can control the z-ordering on the plot by setting the zorder property (see examples/zorder_demo.py). For candlestick (see examples/candlestick_demo.py) you would do lines, patches = candlestick(ax, quotes, width=0.6) set(lines, zorder=0.9*patches[0].zorder) for candlestick2 you would do (untested) linecol, rectcol = candlestick2(blah) z = rectcol.get_zorder() linecol.set_zorder(0.9*z) Argg, that's embarrassing. Good thing mpl is distributed with no warranties.... No telling how many billions this bug has cost the wall street barons already! In matplotlib/finance.py in the candlestick2 function, find this code colord = { True : colorup, False : colordown, } colors = [colord[open>=close] for open, close in zip(opens, closes) if open!=-1 and close !=-1] That should read colors = [colord[close>=open] for open, close in zip(opens, closes) if open!=-1 and close !=-1] right? I believe this is already correct in candlestick, so this is a candlestick2 specific bug. OK, if you submit a replacement function that better matches actual plots, I will be happy to include it. Thanks for the report! JDH ------------------------------------------------------- SF email is sponsored by - The IT Product Guide Read honest & candid reviews on hundreds of IT Products from real users. Discover which products truly live up to the hype. Start reading now. _______________________________________________ Matplotlib-users mailing list Matplotlib-users@lists.sourceforge.net __________________________________ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone.
https://discourse.matplotlib.org/t/candlestick-issues/2395
CC-MAIN-2021-43
refinedweb
510
67.15
I need something that will force FileSystem.FileExists to continuously ping the path until it sees the file. (I’ve searched without success.) Once it verifies the file exists, then it will continue. Any help is appreciated. Thank you! I need something that will force FileSystem.FileExists to continuously ping the path until it sees the file. (I’ve searched without success.) Why not ask once, and if not create the file; otherwise pass the result? Maybe you could use a while loop to do this, don’t know if it’s really possible. @JacobSmall I’m printing PDFs (you can see the Shared section for my DYN file). There’s an issue with merging the final created set of PDFs in that it will often merge before the final PDF is created. So, if I could simply verify that the final printed PDF exists then it would guarantee that all PDFs would be included during merge. Ah. With PDFs and some other ‘driver’ based files the fact that the file exists is often not enough information, and just because they are sent doesn’t mean they are done (which is your exact issue). To complicate things even further, just because the PDF file exists doesn’t mean it’s done writing to disc. In some cases the driver will actually create the file, open the file, add the content to the file, save the file, and close it. It’s unlikely you’d get this outcome with most drivers for single sheet PDFs, but it’s possible to run into concurrent access issues and other problems all the same. As such it may be best to wait for confirmation from the printer itself, but that’s a difficult task which will vary based on your driver. Alternatively, you could write the expected list of PDFs to a text file, and run a second graph that reads the path to each of the generated PDFs, and combines them into a single text file. Benefit here would be that you would get consistent results, and you could easily adjust the order and combine PDFs from other sources (ie: the specification, which likely didn’t come from Revit) while you were at it. Not a great method as there is no way to know how long it takes to wright a PDF (depends on content being printed). But you could use pythons sleep function. import time time.sleep(10) OUT = IN[0] This will pause the script for 10 seconds (my input variable change as needed) and then pass the information input into the node. The TimeSpan nodes are just to check that it is working. As you can see it took longer than 10 seconds to complete this very simple script. Again this does not mean that the PDF will be completed after the given sleep time and it could also force you to wait longer as the PDF could complete well before the sleep timer ends.
https://forum.dynamobim.com/t/is-there-a-continuous-execute-until-true-node/51906
CC-MAIN-2020-50
refinedweb
496
70.43
A Safe Read Function Fredrik Lundh | June 2007 The file read method takes an optional size argument, which tells Python how much data you want to read from the file. If this argument is used, Python allocates a buffer large enough to hold size bytes of data, reads that much data from the file, and finally adjusts the size of the resulting buffer to match the amount of data actually read from the file. This is all and well if you’re using a fixed size, or trust the source, but if you’re getting the size from somewhere else, your program might misbehave badly if it gets broken data. For example, the following snippet reads an 8-byte header from a binary file, where the first four bytes is a constant string, and the next four bytes contains the size of the following data block. header = fp.read(8) tag, size = struct.unpack("4si", header) if tag != "HEAD": raise IOError("invalid header") data = fp.read(size) If the size field contains bogus data (accidentally or on purpose), the read call may attempt to allocate hundreds of megabytes of memory, or gigabytes, even if the file isn’t close to being that large. If you’re lucky, this results in a memory error, but it may also cause excessive swapping, or otherwise affect other processes on the same machine. Here’s a simple replacement. This behaves like an ordinary read(size) call, but doesn’t blindly overallocate. def safe_read(fp, size, blocksize=1024*1024): if size <= 0: return "" if size <= blocksize: return fp.read(size) data = [] while size > 0: block = fp.read(min(size, blocksize)) if not block: break data.append(block) size = size - len(block) return "".join(data)
http://sandbox.effbot.org/zone/safe-read.htm
crawl-003
refinedweb
289
70.63
Bug #1933 RCP: 0.7.8, "Tokenize" checkbox available but not working in XML/W+CSV import module Description This checkbox allows skipping the tokenization step in XML/XTZ import module (if unchecked). In XML/W+CSV unchecking the box has no effect on the import process (the text is tokenized in all cases). The box should either be removed or (better) be functional in the XML/W module History #1 Updated by Matthieu Decorde almost 5 years ago - % Done changed from 0 to 80 import option fixed #2 Updated by Matthieu Decorde almost 5 years ago at least for this import module! Also available in: Atom PDF
https://forge.cbp.ens-lyon.fr/redmine/issues/1933
CC-MAIN-2021-39
refinedweb
108
59.64
Welcome to our Python Tutorial. We’ll cover the basics here and link to more in depth resources along the way. We hope you enjoy the tutorial and walk away with a better understanding of the Python programming language. Let’s get started with our introduction to Python for beginners! - Download and Install Python - Variables - Functions - Docstrings - Escape Characters - Numbers - Keywords - Strings - Style Rules - Booleans - Loops - Lists - Operators - Conditional Statements - Exception Handling - Dictionaries - Modules - Taking Input From The User Download and Install Pythondisplay. >> interpretor type when you want to execute the script from the shell. # The script can be given an executable mode, or permission, using the chmod command: $ chmod +x hello.py Now you can execute the script directly by its name. Variables In Python, variables are a storage placeholder for texts and numbers. It must have a name so that you are able to find it again. The variable is always assigned with the equal sign, followed by the value of the variable. Python is dynamically typed, which means that you don’t have to declare what type each variable is.. # variable a,b and c are assigned to the same memory location,with the value of 1 a = b = c = 1 Get Area using Python Variables length = 1.10 width = 2.20 area = length * width print "The area is: " , area This will print out: The area is: 2.42 Learn More About Variables Functions A function is something you can call (possibly with some parameters, the things you put in the parentheses), which performs an action and returns a value. Functions are useful because: - Reuse code - Easy to debug - Smaller unit of code(relatively speaking) Function syntax A function must be defined before it is called. To define a function, use the following syntax: def myFunction(): The above function has no parameters, meaning no values are being passed into the function. To name parameters, use the following syntax. def myFunction(name,age): Now we have a function call that passes in a few parameters. We’ll move onto the body of the function and use those parameters. def myFunction(name,age): print 'Name: ' + name print 'Age: ' + age With our function body, the code MUST be indented. The method, when called, would print the name and age passed into it. Instead of printing a value, a function can return that value to the program. def myFunction(name,age): return 'My name is ' + name + ' and I am ' + age + ' years old' >>> myFunction('John','44'): 'My name is John and I am 44 years old' Return is the common conclusion of a function as the calling program will typical store its contents into a variable or act on the return value in a conditional statement. Learn More About Functions Comments in Python are used to explain what the code does. They are meant as documentation for anyone reading the code. Python is automatically ignoring all text that comes after the “#” Comments can be in the beginning of the line or at the end of one. Multiline comments are possible and are enclosed by triple quotes. # First comment print "Hello, Python!"; # second comment #this is a comment in Python """ This is an example of a multiline comment that spans multiple lines ... """ Learn More About Comments Docstrings Here is an example of a multi-line docstring: def my_function(): ... """Do nothing, but document it. ... ... No, really, it doesn't do anything. ... """ ... pass ... Now that we have created our Docstring in the my_function() method, let’s see how it can be useful. Let’s say I’m a new developer in a project and I want to know what my_function() does. See below using the print function. >>> print my_function.__doc__ Do nothing, but document it. No, really, it doesn't do anything. Multiple Docstrings In One Source File The following Python file shows the declaration of docstrings within a python source file. You can clearly see the different levels of docstrings and how they can be used within a single Below we show you two methods you can use to access the docstring. >>> Docstrings vs Comments Docstrings and comments are similar in nature, but serve a different purpose. Comments are great for describing lines of code and why they are there. This is very helpful in large code sets. Docstrings document what a class, module or package does and most importantly, is available to the help function, whereas, comments are not. Docstrings, therefore, can help to document the code programmatically. Learn More About Docstring Escape Characters Escape characters allow you to do things you normally wouldn’t be able to do following the normal Python syntax rules. For example, you want to print this line in your code with double quotes around the title of the movie, “Titanic”. >>> print "Cory's favorite movie is "Titanic"" SyntaxError: invalid syntax The compiler doesn’t allow you to use double quotes inside double quotes, so you have to “escape” the double quotes from the compiler and allow them to be treated as a string. To do this, you simply add a backslash(\) before the character you want to escape. >>> print "Cory's favorite movie is \"Titanic\"" Cory's favorite movie is "Titanic" Below is a table of other common escape characters. Numbers Python supports 4 types of Numbers, the int, the long, the float and the complex. You don’t have to specify what type of variable you want. Python does that automatically. Converting Numbers You can simply convert them, like this: >>> float(3) 3.0 >>> int(4.123) 4 Using Python interpreter as a calculator You can use the interpreter to do math with numbers. >>> 2 + 2 4 >>> 4 * 2 8 >>> 10 / 2 5 >>> 10 - 2 8 Keywords Keywords in Python are reserved words that cannot be used as ordinary identifiers. They must be spelled exactly as they are written. List of keywords The following is a list of keywords for the Python programming language. Learn More About Keywords Strings, which means they can’t change. String syntax is recognized by anything between ” ” or ‘ ‘. Much like Lists, Strings have functions that can work on their value. String Functions Changing Case string.lower() # lower case the string string.upper() # upper case the string string.title() # upper case the first letters Replace string.replace(“This”,”That”) # will replace the text “This” with “That” Split Split will split a string into an array based on the delimiter passed into the function. x = '1,2,3' x.split(",") ['1','2','3'] There are many more string functions available. See our Learn More About Strings section. String Concatenation In Python there are a few different ways to concatenating strings. Concatenation combines two (or more) strings into a new string object. You can use the + operator, like this: print "You can concatenate two " + "strings with the '+' operator." str1 = "Hello" str2 = "World" str1 + str2 # concatenation: a new string # String literals may be concatenated by a space word = 'left' "right" 'left' # Any string expression may be concatenated by a + word = wordA + " " + wordB Learn More About Strings Style Rules A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important. An example of this would be: Semicolons Do not terminate your lines with semi-colons and do not use semi-colons to put two commands on the same line. Line length Maximum line length is 80 characters. Parentheses Use parentheses sparingly. Indentation Indent your code blocks with 4 spaces. Learn More About Style Rules Booleans The built-in type Boolean can hold only one of two possible objects: True or False Boolean Values Boolean values respond to logical operators and / or. The examples below show how multiple boolean values act together with differing operators. >>> True and False False >>> True and True True >>> False and True False >>> False or True True >>> False or False False Learn More About Booleans Loops Programming languages need a way to repeat the same sequence, this is called Iteration. Loops in programming allow us to iterate over elements in severals ways. For Loops For loops allows us to iterate over elements of a sequence, it is often used when you have a piece of code which you want to repeat “n” number of time. It works like this: Let’s say that you have a list of browsers like below. That reads, for every element that we assign the variable browser, in the list browsers, print out the variable browser >>> browsers = ["Safari","Firefox","Chrome"] >>> for browser in browsers: ... print browser ... Safari Firefox Chrome While Loops The while loop tells the computer to do something as long as the condition is met It’s construct consists of a block of code and a condition. The loop will continue WHILE the condition met is true. Once it is false, the loop will exit. browsers = ["Safari", "Firefox", "Google Chrome", "Opera", "IE"] i = 0 while i < len(browsers): print browsers[i] #add 1 to i each iteration so that we exit once we reach the total number of browsers i = i + 1 Eternal Loops You typically want to avoid Eternal loops as they will never end until all system resources are consumed or the program is killed externally. An example of an eternal loop. while True: print "Hello World" Typically eternal loops aren't this obvious and usually involves inadvertently updating a variable that is being used as a counter. Continue The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop. This is typically used when a certain condition is met that makes it unnecessary to execute the remaining block. for i in range(1,10): if i == 3: # don't print 3's, I hate 3's, but keeping printing continue print i Break Break statements allow you to exit the loop if a condition is met. This is different from the Continue statement where the loop will continue. for i in range(1,10): if i == 3: # 3's are so bad that I can't continue this loop any longer break print i Pass The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. >>> while True: ... pass # Busy-wait for keyboard interrupt ... Learn More About Loops Lists Lists in Python are a collection of items, such as Strings, Integers or other Lists. Lists are enclosed in [ ] with each item separated by commas. Lists, unlike Strings are mutable, which means they can be changed. List Examples emptyList = [] bourbonList = ['jeffersons','woodford reserve','maker's mark'] numList = [1,2,3,4] List Functions While you can use other function against a list, like len to get the length of a list len(bourbonList) >>> 3 Lists has its own set of methods. Append will add an element to the end of a list. bourbonList.append("Jack Daniels") print bourbonList >>> ['jeffersons','woodford reserve','maker's mark','Jack Daniels'] Here are more List functions and their purpose Too see a more comprehensive list of List functions, check out our Learn More About Lists section. Learn More About Lists Operators Comparison operators Logical operators Learn More About Operators Conditional Statements In programming, very often we want to check the conditions and change the behavior of the program. acondition user. # This program compares two strings. # Get a password from the user. password = raw_input('Enter the password: ') # Determine whether the correct password # was entered. if password == 'hello': print'Password Accepted' else: print'Sorry, that is the wrong password.' Another Example Let's show one more example that makes use of the elif statement. #!/usr/bin/python number = 20 guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations, you guessed it.') elif guess < number: print('No, it is a little higher than that') else: print('No, it is a little lower than that') Learn More About Conditional Statements Exception Handling When an error occurs in a Python program, Python generates an Exception. Why? So that it can be handled gracefully without breaking the program or causing issues with user interaction. Exception Examples Handling Exceptions To handle exceptions you need to use the catch-all except clause. This involves using the "try" and "except" Python keywords. Simply put, you wrap the executing code in a "try" block and if any exception occurs, you catch it and handle it accordingly. An example in pseudo code: try: some statements here except: exception handling Let's see a short example on how to do this: try: print 1/0 except ZeroDivisionError: print "You can't divide by zero, you're silly." Learn More About Exception Handling Dictionaries Dictionary is another data type in Python. Dictionaries are collections of items that have a “key” and a “value”. Python dictionaries are also known as associative arrays or hash tables. They are just like lists, except instead of having an assigned index number, you make up the index. Create a Dictionary # This is a list myList = ["first","second","third"] # This is a dictionary myDictionary = {0:"first",1:"second",2:"third"} Accessing / Getting values To access dictionary elements, you can use the square brackets along with the key to obtain its value. data = {'Name':'Zara','Age':7,'Class':'First'}; # Get all keys data.keys() # Get all values data.values() # Print key1 print data['Name'] # Prints 7 print data['Age'] # Prints name and age print 'Name', data['Name']; print 'Age', data['Age']; Looping through a Dictionary You can use a for loop to iterate Dictionary items. data = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } for key, value in data.items(): print key,value Looping their values directory (not in order) for value in data.values(): print value There are many more operations you can perform on a Dictionary, like add, clear, delete, list all keys, list all values, test if a key exists, etc. You can learn more about these features by reviewing the articles in Learn More About Dictionaries. Learn More About Dictionaries Modules. There are different ways to import a module. Importing Modules. Math Module Requests Module The Requests module is a an elegant and simple HTTP library for Python that allows you to send HTTP/1.1 requests. To install requests, simply: $ pip install requests Or, if you absolutely must: $ easy_install requests To create a Request object, simply call a URL using the following syntax. >>> r = requests.get('') To operate on the object, you have many choices. Here is one example to check the http status code. >>> r = requests.get('') >>> r.status_code 200 Learn More About Modules Taking User Input There are two functions in Python that you can use to read data from the user: raw_input and input You can store the results from them into a variable. raw_input is used to read text (strings) from the user: #Ask the user to input a name, and store it in the variable name name = raw_input("What is your name? ") type(name) #Create a new string with a greeting greet = 'hello ' + name input is used to read integers age = input("What is your age? ") print "Your age is: ", age type(age) #Ask the user to input a number, and store it in the variable foo foo = int(raw input('enter a number: ')) Learn More About Taking User Input Sources Recommended Python Training Course: Python 3 For Beginners Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.
https://www.pythonforbeginners.com/python-tutorial
CC-MAIN-2021-49
refinedweb
2,589
62.48
o CFQ enables idling on very selective queues (sequential readers). That's why we implemented the concept of group idling where irrespective of workload in the group, one can idle on the group and provide fair share before moving on to next queue or group. This provides stronger isolation but also slows does the switching between groups. One can disable "group_idle" to make group switching faster but then we loose fairness for sequenatial readers also as once queue has consumed its slice we delete it and move onto next queue. o This patch implments the concept of wait busy (simliar to groups) on queues. So once a CFQ queue has consumed its slice, we idle for one extra period for it to get busy again and then expire it and move on to next queue. This makes sure that sequential readers don't loose fairness (no vtime jump), even if group idling is disabled. Signed-off-by: Vivek Goyal <vgoyal redhat com> --- block/elevator-fq.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 files changed, 55 insertions(+), 1 deletions(-) diff --git a/block/elevator-fq.c b/block/elevator-fq.c index 5511256..b8862d3 100644 --- a/block/elevator-fq.c +++ b/block/elevator-fq.c @@ -21,6 +21,7 @@ int elv_slice_async = HZ / 25; const int elv_slice_async_rq = 2; int elv_group_idle = HZ / 125; static struct kmem_cache *elv_ioq_pool; +static int elv_ioq_wait_busy = HZ / 125; /* * offset from end of service tree @@ -1043,6 +1044,36 @@ static void io_group_init_entity(struct io_cgroup *iocg, struct io_group *iog) entity->my_sd = &iog->sched_data; } +/* If group_idling is enabled then group takes care of doing idling and wait + * busy on a queue. But this happens on all queues, even if we are running + * a random reader or random writer. This has its own advantage that group + * gets to run continuously for a period of time and provides strong isolation + * but too strong isolation can also slow down group switching. + * + * Hence provide this alternate mode where we do wait busy on the queues for + * which CFQ has idle_window enabled. This is useful in ensuring the fairness + * of sequential readers in group at the same time we don't do group idling + * on all the queues hence faster switching. + */ +int elv_ioq_should_wait_busy(struct io_queue *ioq) +{ + struct io_group *iog = ioq_to_io_group(ioq); + + /* Idle window is disabled for root group */ + if (!elv_iog_idle_window(iog)) + return 0; + + /* + * if CFQ has got idling enabled on this queue, wait for this queue + * to get backlogged again. + */ + if (!ioq->nr_queued && elv_ioq_idle_window(ioq) + && elv_ioq_slice_used(ioq)) + return 1; + + return 0; +} + /* Check if we plan to idle on the group associated with this queue or not */ int elv_iog_should_idle(struct io_queue *ioq) { @@ -1889,6 +1920,7 @@ static void io_free_root_group(struct elevator_queue *e) /* No group idling in flat mode */ int elv_iog_should_idle(struct io_queue *ioq) { return 0; } EXPORT_SYMBOL(elv_iog_should_idle); +static int elv_ioq_should_wait_busy(struct io_queue *ioq) { return 0; } #endif /* CONFIG_GROUP_IOSCHED */ @@ -2368,6 +2400,24 @@ static void elv_iog_arm_slice_timer(struct request_queue *q, elv_log_iog(efqd, iog, "arm_idle group: %lu", sl); } +static void +elv_ioq_arm_wait_busy_timer(struct request_queue *q, struct io_queue *ioq) +{ + struct io_group *iog = ioq_to_io_group(ioq); + struct elv_fq_data *efqd = q->elevator->efqd; + unsigned long sl = 8; + + /* + * This queue has consumed its time slice. We are waiting only for + * it to become busy before we select next queue for dispatch. + */ + elv_mark_iog_wait_busy(iog); + sl = elv_ioq_wait_busy; + mod_timer(&efqd->idle_slice_timer, jiffies + sl); + elv_log_ioq(efqd, ioq, "arm wait busy ioq: %lu", sl); + return; +} + /* * If io scheduler has functionality of keeping track of close cooperator, check * with it if it has got a closely co-operating queue. @@ -2456,7 +2506,8 @@ void *elv_select_ioq(struct request_queue *q, int force) * from queue and is not proportional to group's weight, it * harms the fairness of the group. */ - if (elv_iog_should_idle(ioq) && !elv_iog_wait_busy_done(iog)) { + if ((elv_iog_should_idle(ioq) || elv_ioq_should_wait_busy(ioq)) + && !elv_iog_wait_busy_done(iog)) { ioq = NULL; goto keep_queue; } else @@ -2640,6 +2691,9 @@ void elv_ioq_completed_request(struct request_queue *q, struct request *rq) if (elv_iog_should_idle(ioq)) { elv_iog_arm_slice_timer(q, iog, 1); goto done; + } else if (elv_ioq_should_wait_busy(ioq)) { + elv_ioq_arm_wait_busy_timer(q, ioq); + goto done; } /* Expire the queue */ -- 1.6.0.6
http://www.redhat.com/archives/dm-devel/2009-September/msg00277.html
CC-MAIN-2014-49
refinedweb
653
55.58
This: - HTTP endpoints present your bot as a web service. You'll need to set up a web server to use as an interface for your bot's implementation. Your bot can respond synchronously or asynchronously to these events. - Google Cloud Pub/Sub endpoints use a topic on Google Cloud Pub/Sub to relay an event to your bot's implementation. This is useful when your implementation is behind a firewall. Bots that use pub/sub endpoints can only respond asynchronously. - DialogFlow endpoints let your bot utilize the natural language processing (NLP) capabilities of DialogFlow. Please see DialogFlow documentation for details. For a simple, straightforward bot architecture, try implementing a bot using an HTTP endpoint (a web service, essentially) that responds synchronously, always enclosing its payload in the HTTP POST response.. tl;dr... A very simple bot implementation The following code implements a simple bot in Python using the Flask web framework. #!/usr/bin/env python3 """Example bot bot presents an HTTP endpoint and doesn't need to use Cloud Pub/Sub to relay events to it. And because it always returns its response payload within the JSON response, it doesn't need to authenticate using a service account.. Verifying bot authenticity Once you've registered your HTTP bot, you need a way for your implementation to verify that the request is actually coming from Google. Google Chat includes a bearer token in the Authorization header of every HTTP Request to a bot. For example: POST Host: yourbot bot's project number from the Google API Console. For example, if the request is for a bot with the project number 1234567890, then the audience is 1234567890. You should verify that the request is coming from Google and is intended for the target bot. If the token doesn't verify, the bot should respond to the request with an HTTP Bots in Google Chat. */ public class JWTVerify { // Bearer Tokens received by bots will always specify this issuer. static String CHAT_ISSUER = "chat@system.gserviceaccount.com"; // Url to obtain the public certificate for the issuer. static String PUBLIC_CERT_URL_PREFIX = ""; // Intended audience of the token, which will be the project number of the bot. static String AUDIENCE = "1234567890"; // Get this value from the request's Authorization HTTP bots will always specify this issuer. CHAT_ISSUER = 'chat@system.gserviceaccount.com' # Url to obtain the public certificate for the issuer. PUBLIC_CERT_URL_PREFIX = '' # Intended audience of the token, which will be the project number of the bot. AUDIENCE = '1234567890' # Get this value from the request's Authorization HTTP bot: There are three kinds of events shown in the above diagram: ADDED_TO_SPACE, MESSAGE, and REMOVED_FROM_SPACE. A bot can't respond after being removed from a room, but it can respond to the other two types. Responding synchronously A bot can respond to an event synchronously by returning a JSON-formatted message payload in the HTTP response. The deadline for a synchronous response is 30 seconds. A synchronous response from a bot is always posted in the thread that generated the event to the bot. Responding asynchronously If a bot bots that don't use service accounts cannot respond asynchronously. Retry If an HTTP request to your bot fails (e.g. timeout, temporary network failure, or a non-2xx HTTP status code), Google Chat will additionally retry delivery twice, with at least a ten-second delay between each retry. As a result, a bot may receive the same message up to three times in certain situations. No retry is attempted if the request completes successfully but returns an invalid message payload. Bot-initiated messages This section describes how bots can send arbitrary messages into a space. Many bots send messages only in direct response to an event that they receive from Google Chat. However, some bots bot receives from Google Chat. Keep track of this ID so that the bot can inject messages into the thread. As a new thread To send a message into Google Chat as a new thread, your bot. The thread key is specified in the threadKey query parameter in an inbound HTTP request. For instance:?\ threadKey=ARBITRARY_STRING Thread keys are also scoped to a specific bot; if two different bots happen to both post messages using the same thread key, those two messages will not be grouped into the same thread.
https://developers.google.com/hangouts/chat/how-tos/bots-develop?hl=tr
CC-MAIN-2020-45
refinedweb
714
63.39
In @emaste removed gets() from FreeBSD 13's libc, and our copies of libc++ and libstdc++. In that change, the declarations were simply deleted, but I would like to propose this conditional test instead. Details Details In @emaste removed gets() from Diff Detail Diff Detail Event Timeline Comment Actions which I think is much clearer, and captures the intent I'm wondering if this has become complicated enough that we should define a _LIBCPP_C_HAS_NO_GETS config macro. Then the code in cstdio becomes: #if _LIBCPP_STD_VER <= 11 && !defined(_LIBCPP_C_HAS_NO_GETS) using ::gets; #endif which I think is much clearer, and captures the intent We do not import gets into namespace std when: - It does not exist in the underlying C library, or - We are compiling for C++14 or later.
https://reviews.llvm.org/D67316?id=219245
CC-MAIN-2020-10
refinedweb
127
54.97
The Java Specialists' Newsletter Issue 1932011-06-30 Category: Performance Java version: Java 6 GitHub Subscribe Free RSS Feed Welcome to the 193rd issue of The Java(tm) Specialists' Newsletter, sent from the amazing Island of Crete. A few weeks ago my Greek teacher introduced me to "aoristos", the simple past. This is great, because now I can bore my Greek friends with wild tales of life in Africa when I was a child. "Ipia me tous elefantes" - I drank with the elephants. The beauty of being from Africa is that Europeans will believe anything you say. "Ahh, so you had a lion as a pet? I knew it!" If you know a bit of Greek, try this aoristos flash card test. My name is on top at the moment, but I'm sure I will easily be dethroned :-) In my previous newsletter, I challenged you to explain why the anonymous class sets the this$0 field before calling super(). Kai Windmoeller was the first to send me a partial reason and Wouter Coekaerts was the first with a perfect explanation. Both Kai and Wouter subsequently sent me other clever ideas that I would like to incorporate in future newsletters. [And the explanation is ....... you'll have to figure that out yourself :-) A hint though, if you compile the class with -source 1.3 and -target 1.3, it does not do that. See what issues that can cause and you will see why we need this.] this$0 super() NEW: Please see our new "Extreme Java" course, combining concurrency, a little bit of performance and Java 8. Extreme Java - Concurrency & Performance for Java 8. My newsletter is strongly connected to my courses. When I research Java for my newsletter, ideas emerge on how to improve my advanced Java courses. Questions asked during the courses often stimulate ideas for new research topics. It is a delicate ecosystem. They cannot exist without each other. A few months ago, during one of my masters courses, one of the programmers mentioned that they had noticed a memory bottleneck with the ConcurrentHashMap. They were creating about 100000 maps and wanted them to be threadsafe. The natural choice seemed to be the ConcurrentHashMap, since it, well, is supposed to work with concurrent access. The ConcurrentHashMap splits the bucket table into a number of segments, thus reducing the probability that you would have contention when modifying the map. It is quite a clever design and scales nicely to about 50 cores. Above 50 cores, you would be better off using Cliff Click's Highly Scalable Libraries. Since my friends did not need high scalability, the ConcurrentHashMap seemed fine. Whilst doing a memory profile, JVisualVM showed that the top culprit was the ConcurrentHashMap.Segment class. The default number of segments per ConcurrentHashMap is 16. The HashEntry tables within the segments would probably be tiny, but each Segment is a ReentrantLock. Each ReentrantLock contains a Sync, in this case a NonFairSync, which is a subclass of Sync and then AbstractQueuedSynchronizer. Each of these contains a queue of nodes that maintain state of what is happening with your threads. It is used when fairness is determined. This queue and the nodes use a lot of memory. Many years ago, I wrote a newsletter that demonstrated a simple memory test bench. It would construct an object, then release it again with System.gc() and measure the difference. Here is a slightly updated version of the MemoryTestBench. It still does virtually the same, with the only enhancement that I sleep a bit after each System.gc() call: public class MemoryTestBench { public long calculateMemoryUsage(ObjectFactory factory) { Object handle = factory.makeObject(); long memory = usedMemory(); handle = null; lotsOfGC(); memory = usedMemory(); handle = factory.makeObject(); lotsOfGC(); return usedMemory() - memory; } private long usedMemory() { return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } private void lotsOfGC() { for (int i = 0; i < 20; i++) { System.gc(); try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } public void showMemoryUsage(ObjectFactory factory) { long mem = calculateMemoryUsage(factory); System.out.println( factory.getClass().getSimpleName() + " produced " + factory.makeObject().getClass().getSimpleName() + " which took " + mem + " bytes"); } } I created an ObjectFactory interface and some basic classes to test that it still worked correctly: public interface ObjectFactory { Object makeObject(); } public class BasicObjectFactory implements ObjectFactory { public Object makeObject() { return new Object(); } } public class IntegerObjectFactory implements ObjectFactory { public Object makeObject() { return new Integer(333); } } public class LongObjectFactory implements ObjectFactory { public Object makeObject() { return new Long(333L); } } I tried this out with Java 1.6.0_24 on my Mac OS X 10.6.8 and with a self-built Java 1.7.0 based on the OpenJDK. I also tried 32 vs. 64 bit, server vs. client on the 32 bit and the flag -XX:+UseCompressedOops on the Server Hotspot Compiler. The -server and -client made the least difference, so I only include the -server results. Also, the results for Java 1.7.0 were similar enough to 1.6.0_24 that I will only show the 1.6 data: Java Version 1.6.0_24 with -server 32/64bit 64 64 32 CompressedOops No Yes N/A Object 24 24 8 Long 24 24 16 Integer 24 24 16 It looks as if the -XX:+UseCompressedOops flag has no effect on these objects. You will only see the difference with more complex objects that have pointers to others. This flag can also speed up your application substantially if you are using a 64 bit machine. Here are some factories for creating various hash maps. The first is not threadsafe, the other two are: public class HashMapFactory implements ObjectFactory { public Object makeObject() { return new HashMap(); } } public class SynchronizedHashMapFactory implements ObjectFactory { public Object makeObject() { return Collections.synchronizedMap(new HashMap()); } } public class HashtableFactory implements ObjectFactory { public Object makeObject() { return new Hashtable(); } } We see that even basic hash tables differ greatly in size between various implementations. If memory space is a major issue, like it was for my friends, then the Java 1.0 Hashtable class might work best. Hashtable is fully synchronized, which means that it will cause contention when accessed from more than one core at a time. It also uses integer division to locate the correct bucket, which is slower than the bit masking approach used since Java 1.4. However, if memory is your bottleneck, then Hashtable might be a good solution. Here are the memory sizes: 32/64bit 64 64 32 CompressedOops No Yes N/A HashMap 216 128 120 SynchronizedMap 272 160 152 Hashtable 176 112 96 The ConcurrentHashMap allows us to construct it with a concurrency level, which is used to calculate the number of segments that the map will contain. The actual number of segments is a power of 2 greater or equal to the concurrency level. Thus if we construct a map with concurrency level of 200, it will create 256 segments. As mentioned above, every segment is subclassed from ReentrantLock. Thus we will show the sizes for ReentrantLock, and ConcurrentHashMaps with sizes 16 (the default), 2 and 256: public class ReentrantLockFactory implements ObjectFactory { public Object makeObject() { return new ReentrantLock(); } } public class ConcurrentHashMapFactory implements ObjectFactory { public Object makeObject() { return new ConcurrentHashMap(); } } public class SmallConcurrentHashMapFactory implements ObjectFactory { public Object makeObject() { return new ConcurrentHashMap(16, .75f, 2); } } public class BigConcurrentHashMapFactory implements ObjectFactory { public Object makeObject() { return new ConcurrentHashMap(16, .75f, 256); } } Based on these results, we can see why the ConcurrentHashMap uses so much memory, even when it is empty. 32/64bit 64 64 32 CompressedOops No Yes N/A ReentrantLock 72 56 40 ConcurrentHashMap 2272 1664 1272 SmallConcurrentHashMap 480 312 272 BigConcurrentHashMap 34912 25664 19512 Another option is Cliff Click's Highly Scalable Libraries. import org.cliffc.high_scale_lib.*; public class HighlyScalableTableFactory implements ObjectFactory { public Object makeObject() { return new NonBlockingHashMap(); } } Click's empty NonBlockingHashMap uses a lot less memory than the ConcurrentHashMap. 32/64bit 64 64 32 CompressedOops No Yes N/A ConcurrentHashMap 2272 1664 1272 NonBlockingHashMap 1312 936 872 Let's see what happens when we put some elements into the map, by writing an ObjectFactory that fills the map with objects. By adding autoboxed Integers from the integer cache and constant Strings, we can measure the hash map overhead, instead of the objects contained inside the map. public class FullMapObjectFactory implements ObjectFactory { private final ObjectFactory factory; protected FullMapObjectFactory(ObjectFactory factory) { this.factory = factory; } public Object makeObject() { return fill((Map) factory.makeObject()); } protected Map fill(Map map) { for (int i = -128; i < 128; i++) { map.put(i, "dummy"); } return map; } } With this particular data set, the NonBlockingHashMap uses the least amount of memory, but I have seen other data sets where the Hashtable uses the least. You would have to try it out in your particular situation to find the best possible map for your needs. Also remember that the NonBlockingHashMap scales to hundreds of cores, whereas the Hashtable would have contention with two. 32/64bit 64 64 32 CompressedOops No Yes N/A ConcurrentHashMap 30024 21088 16872 SmallConcurrentHashMap 16736 10488 8400 BigConcurrentHashMap 48144 34040 26416 Hashtable 15440 9792 7728 NonBlockingHashMap 10912 6696 6632 As in all performance issues, you need to measure and not guess. Please only change your code if you have measured and verified that this is indeed your bottleneck. Kind regards from sunny Crete Heinz P.S. You might have seen disturbing images of Greek rioting. Fortunately this is far away from where we live on the Island of Crete. The despair is quite real though. Performance Articles Related Java Course
http://www.javaspecialists.eu/archive/Issue193.html
CC-MAIN-2016-40
refinedweb
1,567
55.95
Description Introduction: The purpose of this lab is to explore and reinforce the concepts from the lecture section of CS 1428. Today we will cover creating and compiling a file using the Code::Blocks integrated development environment. Directions: 1-Launch Code::Blocks on your own computer. 2- Create a new empty file by selecting File->New->Empty File.Now select File->Save File As…and name your file “your__last_name_lab0.cpp”. 3-As the first lines of your new file copy the following: //Your Name //CS1428 //Lab 0 The “//”indicates that a line is a comment that will be ignored by the compiler. Comments can be used to mark ownership of files or explain what blocks of code are doing. 4-The next line of your file should be: #include <iostream> This tells Code::Blocks that you want to use commands which are defined in a library. You can include any number of blank lines to improve the readability of your code. 5-Your next line of code will be: using namespace std; This line is important when you’re using standard libraries like iostream. 6- Now type: int main () { This is the beginning of a function definition. Every C++ program must include a “main” function. Code::Blocks will probably autofill the closing “}” curly bracket. All of the code for a function must be written between these brackets. 7-For the first line of your main function type the instruction: cout << “Hello World.” << endl; This line will cause the text “Hello World” to be printed in the console and then will start a new line. The semicolon at the end of the line tells the compiler that you’ve finished the command and is very important. Every statement in C++ must end with a semicolon. 8-Use the “cout” statement to answer the following questions. Answer each question with a separate “cout” and end each statement with an “endl” to start a new line. Keep your answers short. Do you have any programming experience? What is the purpose of a compiler? What is an algorithm? What data type would you use to store a number that includes a decimal? What is the name of the compiler we are using with the Code::Blocks IDE? What would you change in this code in order to ensure that it will execute correctly on a Macintosh computer? Windows? Linux? What is an “argument” in programming? What type of value will your main function return? What type of device is a computer monitor? What area of computer science interests you most? 9-The last statement in your function should be: return 0; Make sure that you close the main function with a final curly bracket “}”. 10- Save your work. Use the “Build and Run” button to compile and execute your program. If there are any errors in your code they will be displayed in the Build Log window of Code::Blocks. Correct any errors that exist in your code. If there are no errors in your code you will see something like this (although these answers may not be correct): 11-Attach your .cpp file to the TRACS assignment and submit. You can leave whenever you’ve finished the assignment.
https://edulissy.com/shop/success/lab-0-solution-6/
CC-MAIN-2021-17
refinedweb
535
75.1
Versioning XML Vocabularies by David Orchard | Pages: 1,. <xs:any. mustUnderstand soap:mustUnderstand="1" wsdl:required="1" wsp:Usage="wsp:Required" 0.. ((b, c) | (b, d)) b The use of ##any means there are some schemas that we might like to express, but that aren't allowed. ##any ##any, minOccurs maxOccurs ##other minOccurs="1" maxOccurs="2" any 11. Be Deterministic rule: Use of wildcards MUST be deterministic. Location of wildcards, namespace of wildcard extensions, minOccurs and maxOccurs values are constrained, and type restriction is controlled. wildcards As shown earlier, a common design pattern is to provide an extensibility point -- not an element -- allowing any namespace at the end of a type. This is typically done with <xs:any. . minOccurs="0". xsi:basetype="". xml:mustUnderstand. xs:any]. © , O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://www.xml.com/pub/a/2003/12/03/versioning.html?page=2
CC-MAIN-2016-30
refinedweb
152
50.84
This action might not be possible to undo. Are you sure you want to continue? 05/30/2012 text original Kary Främling Introduction to Java programming K.Främling Page 2 FOREWORD I originally wrote this document for the needs of the Java Basics course at Arcada Polytechnic in spring 1999. The document has hardly been updated at all since then, so it remains on the level of Java version 1.1. Despite this, it should be quite good as an introductory book to Java programming. Since I had been working very intensively with Java programming for over two years in 1999, I have tried to include as many practical issues as possible that Java programmers are faced with. In the future, I might update the book so that it would correspond to recent evolution of the Java language. That way it would serve its original purpose, i.e. give essential skills in Java programming without necessarily having to buy an expensive book. Kary Främling, April 3rd, 2003 Introduction to Java programming K.Främling Page 3 Table of Contents 1. What is java ........................................................................................................................5 1.1 1.2 1.3 2. Different kinds of Java applications ...........................................................................5 Platform independence ...............................................................................................9 History of Java..........................................................................................................10 Java development tools.....................................................................................................13 2.1 2.2 The Java Development Kit (JDK) ............................................................................13 Online documentation...............................................................................................17 3. Java syntax........................................................................................................................18 3.1 3.2 3.3 3.4 3.5 Variable declarations ................................................................................................18 Arrays .......................................................................................................................18 Flow control..............................................................................................................20 Standard input and output.........................................................................................21 Programming style....................................................................................................22 4. Classes and objects ...........................................................................................................23 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 Class declarations .....................................................................................................24 Class variables and instance variables......................................................................25 Method definitions....................................................................................................26 Creating and referencing objects ..............................................................................27 Garbage collection....................................................................................................29 Java Bank Account ...................................................................................................29 Class hierarchies and inheritance .............................................................................31 How to declare and use global constants and variables............................................33 5. Applets..............................................................................................................................35 5.1 5.2 Passing parameters to applets from a HTML page...................................................35 Animation .................................................................................................................37 ..................47 User interaction.................57 Reading a file using a URL .............................60 The “File” class .............................2 8..............................................................................................................................................49 Window-related user interface elements ........................3 Window layout managers ...............52 The "null" layout............1 6..................................................................................3 5................49 6.....................................52 Dialog windows.................................................................2 7........................58 Other input/output classes ..........................................................................................................................................................52 7.......................................1 7...............................................................................................................56 Reading and writing text files.......... Abstract Classes and Interfaces ..................................................56 8.......................................50 7....................................................4 8. Sound effects ....49 User interface elements ......2 6...............................................................1 8..................................4 6.........................................................................................................................................3 8...........Introduction to Java programming K............................................ Window layout ............................... File reading and writing.......................5 File dialogs for opening and saving files.....................................................................................................................Främling Page 4 5..............3 Reacting to a user click inside the applet display area ............................................60 9...........54 8......................................45 Double-buffered animation.....62 ...... The three main ones treated here are: • • • Programs with a textual interface.1 Different kinds of Java applications Java applications can be of several kinds. • 100% compatible yet. Windowing applications that use a graphical user interface. Java applications can always be compiled to native code and run as fast as any other program.Introduction to Java programming K.Främling Page 5 1. • A language that is standardized enough so that executable applications can run on any (in principle) computer that contains a Virtual Machine (run-time environment). and IBM WebExplorer) and operating systems. These three kinds of application may all easily be included in the same Java program as can be shown by the following examples. Java is not: • Slower than any other Object Oriented language. that support creating graphical user interfaces. Applets used in Internet browsers. 1. • A programming language that supports the most recent features in computer science at the programming language level. controlling multimedia data and communicating over networks. What is java Java is: • • A new Object Oriented Programming Language developed at Sun Microsystems. Microsoft Internet Explorer. • A standardized set of Class Libraries (packages). . since it has collected the best parts of the existing ones. since the same application does not always look the same on all platforms due to virtual machine implementation bugs and differences. • Virtual machines can be embedded in web browsers (such as Netscape Navigator. Easier to learn than most other Object Oriented programming languages. so everything has to be contained in classes (no global functions like in “C” or C++).” just writes out the text that we want onto the standard output.Introduction to Java programming K. } } The first line “public class HelloWorld” defines a “class” that is called HelloWorld. These concepts will be explained in detail further on.out. we first save it as a file named ”HelloWorld. which is the object that corresponds to the standard output. Any class may contain a ”main” function. world!"). ”System” is a pre-defined class that contains the member ”out”. we can compile it with the DOS command ”javac HelloWorld. . Simple text interface application (compiled and run) public class HelloWorld { public static void main(String argv[]) { System. ”public static void main(String argv[])” is the standard declaration for a program entry point in Java. We run it with the command line ”java HelloWorld” (if we are still in the same directory and the Java environment is set up correctly). This is useful for test and debugging purposes.println("Hello.println("Hello. The resulting output is the given text followed by a newline character. Then. In fact. so the same program may have several program entry points.java”. ”println” is a method of this object that takes the text to write out as a parameter.java”. world!").out. the file name always has to be the same as the class name for a public class and it has to have the extension ”. Java is a pure object oriented language. ”System.java” (if the Java development environment is set up correctly). if we are in the same directory as the saved file. To compile this program.Främling Page 6 Example 1. ” and “import java. which is indicated by the words “extends Applet” at the end of the line. we only override the method “public void paint(Graphics g)” with our own behaviour.APPLET>.class width=100 height=50>The source</a>.” are for including external libraries. world!". world!” in the HTML page shown. for some reason.drawString("Hello.Introduction to Java programming K.Applet. “import java. A derived class is a class that inherits from the behaviour of its’ base class.*.Främling Page 7 Example 2. 0.awt.APPLET>.drawString("Hello. just like “. 25).awt. world!". The Applet class already contains most of the program code for executing the applet. </body> </html> Example 2 shows a very simple applet. Simple applet (compiled and run) import java. In this case. 25). tag but isn't running the applet. “g. public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.applet.Applet." Your browser is completely ignoring the <. import java. width. however. height: width and height of the display area reserved for the applet. The applet is included in an HTML page using the ”applet” tag. alt: a text to show if the browser is not capable of executing the applet. It takes a number of arguments. which are: • • • code: name of the “. An applet may. tell the browser to go to a new page. .class” file that contains the compiled applet. for instance. Applet display is only possible within the display area that has been reserved for it.Främling Page 8 Figure 1. Simple applet screen.Introduction to Java programming K. “f = new Frame(). 1.drawString("Hello. f.Introduction to Java programming K. f. adds the “HelloWorldFrame” applet to it and then displays the frame.Främling Page 9 Example 3. then the “HelloWorldFrame” could be derived from the “Panel” base class. } } Example 3 shows how to make the applet executable as an independent application (i.setLayout(new GridLayout()). This kind of an application is often called an “app-applet” since it may be included as an applet in a HTML page or it may be run as an independent application.” declares a variable f that is a reference to a Frame object.2 Platform independence Platform independence means that the same (compiled) program can be executed on any computer. If no applet behaviour is needed. f. since any kind of machine may be used to see WWW pages. The trick is to create a normal program entry point.Applet. 25).*.applet. without any need for an Internet browser).add(new HelloWorldFrame()).” creates a new “Frame” object and makes “f” reference it. f. f = new Frame(). . “Frame f. The following lines set up some characteristics of the frame.show(). public class HelloWorldFrame extends Applet { public static void main(String argv[]) { Frame f.setSize(100. world!". import java. 0. } public void paint(Graphics g) { g. for instance. Simple “app-applet” (compiled and run) import java. It is obvious that this is necessary in Internet applications. 100). This is why most recent Internet browsers include a Java Virtual Machine (JVM) that executes instructions generated by a Java compiler. which creates a window (a “Frame” object) that the applet can be displayed in.awt.e. 3 History of Java 1990 – 1993: James Gosling and others at Sun were working on a project that needed a new programming language. Inside that environment is the Java virtual machine. named after the tree outside James Gosling's office. Java virtual machines nowadays exist for most operating systems. 1995 – 1996: Companies begin to license the Java technology and to incorporate it into their products. The “. so Sun named it Java. who incorporated it in their product.Introduction to Java programming K. But Oak turned out to be an existing programming language. including Netscape Communications. The first box indicates that the Java source code is located in a “. . A Java program is said to be compiled to byte-codes.java” file. Compilation of a Java program to byte-codes and executing it with the Java VM. which is processed with a Java compiler called “javac”. which interprets and executes the byte code. Figure 2 also shows the development process a typical Java programmer uses to produce byte codes and execute them. which contains the byte code. Their project was called *7 (Star Seven) and its’ goal was developing a universal system for small. It is a trademark of Sun Microsystems.class” file is then loaded across the network or loaded locally on your machine into the execution environment on that platform. as illustrated by Figure 2. personal digital assistance in set top boxes. We call the JVM a virtual machine because the Java compiler produces compiled code whose target machine is this virtual machine instead of being a physical processor or computer. ”Oak” was the original name of the language developed. whose target architecture is the Java Virtual Machine. The Java compiler produces a file called a “. 1. 1993 – 1995: World Wide Web (WWW) emerged and made Sun develop a web browser that was originally named WebRunner and later HotJava. Figure 2. after many visits to a local coffee shop! Java is not an acronym.Främling Page 10 This Java virtual machine can also be incorporated or embedded into the kernel of the operating system.class” file. HotJava was presented to various companies. . not only for applets. constructors. Microsoft understands the threat that Java represents and tries to ”pollute” the language in order to take it over. Java is still a very young language...Introduction to Java programming K.0 . Networking was also improved. • 1. which are Smalltalk and C++. Contained the complete specification of the language and a class library for the most essential things. especially for distributed computing. Java begins to be used for application develoment. Characteristics common with Smalltalk are: • Similar object model (single-rooted inheritance) hierarchy. It was also intended to be very light-weight. statements. Common characteristics with C++ are: • • Same syntax for expressions.1. Java shares many characteristics of the two most important existing object oriented programming languages. What makes Java more interesting than both these languages is that it has borrowed all the best ideas in Smalltalk and avoided the bad ideas in C++..1 – 1.2: Appeared in 1995. Simple inheritance. access protection. OWL. This is the reason why there exists several specification levels of the language: • 1..). which make C++ a very difficult language to learn.Främling Page 11 1997 . Dynamic memory layout plus garbage collection. Similar OO structural syntax (classes. and control flow.7A: Appeared in 1997. • • • Compiled to byte-code (initially interpreted). …). access to objects via reference only. Java was already from the start meant to be multi-platform. especially concerning the size of the compiled programs and the size of the virtual machine.). .: Java becomes increasingly popular and most operating systems provide a Java Virtual Machine. Included improvements in the graphical interface and added most of the functionalities that are usually included in proprietary class libraries (MFC. These are the main reasons for its’ suitability for WWW applications.0. method declaration.1. . Främling Page 12 Java takes a direction where it provides all the functionalities that are normally provided by the operating system. especially in handling multimedia and distributed computing.1. Most of the contents of this course stay within the limits of the 1.1 specifications only recently. this version seems to be very slow (at least the beta versions tested). Java Beans are specified and supported. The Java virtual machines become very rapid by version 1. New interface libraries and several improvements.Introduction to Java programming K.2 specification. .0. Unfortunately.7A. • Java 2: Appeared in December 1998. since most Internet browsers have updated to 1. javasoft. Java development tools Sun is the main distributor of Java development tools. These files provide the connective glue that allow your code written in the Java Programming Language to interact with code written in other languages like C. • java: The Java Interpreter that you use to run programs written in the Java(tm) Programming Language. • javap: Disassembles compiled Java(tm) files and prints out a representation of the Java bytecodes. The jre tool is similar to the java tool. The JDK contains everything you need to develop general-purpose programs in Java: • Base Tools • javac: The Java Language Compiler that you use to compile programs written in the Java(tm) Programming Language into bytecodes. • appletviewer: Allows you to run applets without a web browser. 2. • jre: The Java Runtime Interpreter that you can use to run Java applications. General information about Java and the corresponding development tools may be found at the address The Java Development Kit (JDK) The Java Development Kit (JDK) is the minimal file you need to download in order to develop in Java. Also see Writing Doc Comments for Javadoc. The version that is meant for the Windows environment contains an automatic installer that takes care of the installation. • jdb: The Java Language Debugger that helps you find and fix bugs in Java(tm) programs.Främling Page 13 2. . but is intended primarily for end users who do not require all the development-related options available with the java tool. All the basic tools needed are still free.com. • javadoc: Generates API documentation in HTML format from Java(tm) source code. • javah: Creates C header files and C stub files for a Java(tm) class.Introduction to Java programming K. Only setting up the Windows PATH may require some manual intervention. • rmiregistry: Starts a remote object registry on a specified port. It is.bat: Launches the program. • Digital Signing Tool • javakey: Generates digital signatures for archive files and manages the database of entities and their keys and signatures.Remote interface. which contains only what is necessary for running a Java application (JVM and libraries). . It may be useful to associate this with using various "make" tools for project management.Främling Page 14 • RMI Tools • rmic: Generates stub and skeleton class files for Java objects implementing the java. useful to create straight away at least the following two script files for each project: • makeit. It is possible to use the JDK as the only development environment for any development project.Introduction to Java programming K. but no development tools.rmi. The remote object registry is a bootstrap naming service which is used by RMI servers. • Internationalization Tools • native2ascii: Converts non-Unicode Latin-1 (source code or property) files to Unicode Latin-1. It may be freely distributed with your application. • serialver: Returns the serialVersionUID for one or more classes. you need to download the Java Runtime Environment (JRE). • runit. • JAR Tool • jar: Combines multiple files into a single Java Archive (JAR) file. If you have developed an application in Java and want to deploy it.bat: Contains the command line for compiling the whole project. • Environment Variables • CLASSPATH: Tells the Java Virtual Machine and other Java applications where to find the class libraries. however. */ public static void main(String argv[]) { Frame f.applet.awt. return * values and so on.show().setSize(100. } } We compile it with the command: . f. 100). } /** * This is a documentation comment for the paint() function. * @return Nothing at all. but you can look at the Sun documentation * about javadoc for more details.Introduction to Java programming K.drawString("Hello. /** * This is a documentation comment for the main() function.Applet. It should * appear just before the class definition. 25). Inserting documentation comments (compiled and run) import java. f = new Frame().add(new HelloFrameDoc()). world!". f. * There are special codes for documenting parameters.*. it is void! */ public void paint(Graphics g) { g. */ public int testField. * So. For instance: * @param g The Graphics object to draw to. HelloFrameDoc is a class for demonstrating how to use * the javadoc tool. 0. f. * The first phrase of the comment is used as an introduction * and the rest in the detailed description. */ public class HelloFrameDoc extends Applet { /** * This is a documentation comment for the testField * variable. * <B>Creator</B>: Kary FRÄ.Främling Page 15 It is also useful to have a script file for generating the program documentation with javadoc.MLING. import java.setLayout(new GridLayout()). f. /** * This is a documentation comment for the whole class. Javadoc uses special documentation comments in the program for creating an HTML documentation that is identical to the one that comes with the JDK. Example 4. for instance.1. We can notice that the generated documentation contains a lot of interesting information even for the programmer himself. what methods are overloaded in what classes and so on. They usually offer a complete development environment including a text (for JDK 1. Figure 3. Other development environments have been developed by Microsoft.Introduction to Java programming K. For getting the images in the generated pages to display.java Then we generate the documentation with the command (-d HelloFrameDoc means that the documentation will be generated in the "HelloFrameDoc" directory): javadoc -d HelloFrameDoc HelloFrameDoc. like the class tree of his own classes.java Then we can start studying the documentation starting from the file " tree. Example of a documentation generated with javadoc.html" (Figure 3).7A\docs\api\images" "HelloFrameDoc" directory.1. it is enough to copy the "C:\jdk1. Inprise (Borland). Symantec etc.Främling Page 16 javac HelloFrameDoc.7A) directory into the . which all may contribute to programming more efficiently. It shows all inheritance relations between the classes. . For JDK1.Främling Page 17 editor.7B\docs". this would normally be the directory "C:\jdk1. Experience has shown that this documentation is very practical to use for programming projects.7B. 2. There is also an index to class and method names. This is a javadoc-generated HTML documentation for the entire standard class library of Java.Introduction to Java programming K.2 Online documentation An online Java and JDK documentation is available for download at the same place as the JDK. The starting point for the documentation is the file "index. And. In the current versions. all class methods and their description and all class variables.html" that is found in this directory. a graphical debugger and project management. above all.1. it is always accurate for the corresponding JDK since it has been generated from the source code of the JDK.1. it is a ZIP file that should be uncompressed into the appropriate directory. followed by a list of identifiers." 3.5 8 bit signed integer. . 32 bit IEEE 754-1985 floating point real number. c.Introduction to Java programming K. b. "int a = 0. with a few new ones. but the type and list of identifiers is not. . This means that ia now references an array object which can contain an array of 3 integers.) etc.. followed by a type. we would write: int[] ia = new int[3].". This means that ia is a reference (compare with reference and pointer in "C" and C++) to an array of integers. Control flow ("if". "while". we would write "int[] ia.1. // "public" is a modifier. 64 bit IEEE 754-1985 Variable declarations consist of three parts: modifiers. Variable declarations Standard primitive types in Java: boolean char byte short int long float double true or false 16 bit character. using 2's complement floating point real number. Variable names. using 2's complement 16 bit signed integer. This is true for • • • • • 3.1 Comments (+ documentation comment). In order to actually create the array at the same time.Främling Page 18 3. Variables may be initialised as in "C".2 Arrays Arrays are NOT declared as in "C". "for".g. To declare an array of integers. The modifiers are optional. declarations and initialisations. Most keywords. Example: public int a.. coded using Unicode 1. using 2's complement 64 bit signed integer. Java Syntax Java syntax is very close to that of "C" and C++. using 2's complement 32 bit signed integer. e. ArrayIndexOutOfBoundsException at TblExample.Introduction to Java programming K. A VERY IMPORTANT improvement in Java compared to languages like "C" and C++ is that tables "know" themselves how big they are. Just like in "C".Främling Page 19 Example 5. If our program wants to handle exceptions graciously. i <= itab1. i++ ) System. for ( i = 0 . Invalid table indexes are automatically detected in Java.out. This is why we can get the length of the table with "itabl1.out. 30}.length . When this occurs. table indexes start from 0.println(itab1[i]).println(itab1[i]). // Create an "IndexOutOfBoundsException" here. System. In programming terms we call this throwing an exception.out.lang. i < itab1. for ( i = 0 .length . // Table initialisation. we say that an exception occurred.main(Compiled Code) Example 5 shows how tables can be initialized in Java. If an exception occurs in a program that does not handle it.println("We got away from the Exception!"). Table initialisation and index exceptions (compiled and run) public class TblExample { public static void main(String argv[]) { int i. i++ ) System. int[] itab1 = {10. That is why the second loop goes too far. } } Screen output: 10 20 30 10 20 30 java. 20. we could define an exception handler by replacing the for-loop that provokes the exception with the following code: .length". then the program exits immediately. j < 10 . Labelled breaks (compiled and run) public class LabelledBreak { public static void main(String argv[]) { brkpnt:for ( int i = 0 . i++ ) { for ( int j = 0 .out. as shown in the following example. Java proposes labelled breaks. } There are a lot of pre-defined exception classes in Java and the programmer may define new ones. return But there is no “goto” statement! Instead.println(itab1[i]).out. Example 6. for instance. } } } } Screen output: . which makes Java programs much more stable than "C" or C++ programs.3 Flow control Flow controls which have an identical syntax to that of "C" are: • • • • • • if-else switch-case while do-while for break. j++ ) { if ( j == 3 ) break brkpnt. try { for ( i = 0 .length . i <= itab1.out. } catch ( IndexOutOfBoundsException e ) { System.Introduction to Java programming K. i < 10 . i++ ) System. j = " + j). This will be treated more in detail later.println("We caught it!"). continue.Främling Page 20 // Create an "IndexOutOfBoundsException" here. System. but this is a very important feature in the Java language.println("i = " + i + ". 3. in)). standard output and standard error.readLine()). System.print("Enter an integer: "). /** * Example showing the use of standard input and output.println("Square: " + n*n + " } } Cube: " + n*n*n).io. j = 1 i = 0.flush(). then we would go through the outer loop 10 times and through the inner one 3 times for each outer loop repetition.out. the labelled break breaks the outer loop straight away and we do not even finish the first repetition of the outer loop. which is the reason why we "embed" it into an "InputStreamReader" and then a "BufferedReader" (more about this in the chapter about file reading and writing). j = 2 If we would have an ordinary “break.out. 3. */ class StdioExample { public static void main(String args[]) throws IOException { int n. // Program output: Enter an integer: 9 Square: 81 Cube: 729 "System. However. n = Integer. "out" and "err". which correspond to standard input.Introduction to Java programming K.in" is an object of class "InputStream".4 Standard input and output The global class "System" contains the fields "in". This class offers very basic reading capabilities. System.parseInt(stdin.out. j = 0 i = 0.*. Using standard input and output in Java (compiled and run) import java. BufferedReader stdin = new BufferedReader(new InputStreamReader(System. System. Using these is illustrated by the following example: Example 7. .” in Example 6.Främling Page 21 i = 0. It is highly recommended to use the same programming conventions that have been used by Sun in their class libraries. which contains a (static) member function called "parseInt()" that converts the given argument string into an integer and returns the value. we just pass it on.parseInt(stdin. documentation comments). This means: • • • • • • • Indentation. 3.flush().println()" always flushes the output stream automatically. . Class names (ThisIsAClassName). Constant names (THIS_IS_A_CONSTANT). This does not seem to be used by Sun.out. "n = Integer.Främling Page 22 The commented line "System. where the standard output is buffered. "throws IOException" in the method declaration means that the method might throw an exception of type IOException. but is highly recommended to increase program readability. • Comments (class and method definitions.out." is one possibility to convert a string into an integer.readLine()). See what happens if you do not feed in an integer! Integer is a standard Java class. Function parameter names (thisIsAFunctionParameter). Local variable names (this_is_a_local_variable). In that case the display might be deferred and not occur until the buffer is full. "System. Class variable/field names (thisIsAClassMemberVariable).Introduction to Java programming K.5 Programming style." might be necessary on some systems. Method names (thisIsAMethodName). This exception might occur in the call to "readLine()" and since we do not catch it. for instance. It would then be directly accessible only to the breaking subsystem.Främling Page 23 4. since there is no way why the injection system should have access to the private calculations of the ABS system. We may also have private classes. Only some of all the methods are visible to other objects.Introduction to Java programming K. it means that there is no way for one subsystem to interfere with the internal functioning of another one. Steering system. This is called encapsulation in OOP. be a private class to the breaking subsystem. Others (have a look at your car's fuse boxes to get an idea). A class corresponds to the factory or machine that produces these subsystems. for instance. where derived classes inherit behaviour from their base class. methods implement the communication protocol between the objects. they become objects that communicate through well-defined protocols in such a way that (hopefully) makes the car work and makes it possible to drive with it. We also have private methods and private variables. This is natural. This means that we can define class hierarchies. which are only visible to the object itself. In this course. In Object Oriented Programming (OOP). Once these subsystems are installed in a car. These are the public methods. we could for instance say that the clutch. . The ABS system might. These are used for the internal operations of the object. break and accelerator classes are all derived from the "PedalControlledDevice" base class. A car contains subsystems which may be considered as objects. Classes and Objects A class is a template that defines how an object will look and behave once instantiated. Another important concept in OOP is inheritance. Ignition system. such as: • • • • • Injection system. we will use cars as an example of a system with various objects that interact with each other. Breaking system (including ABS). Then the "PedalControlledDevice" would define all the behaviour common to the derived classes. In a car. In a car. Introduction to Java programming K.Främling Page 24 The third classical concept in OOP is polymorphism, which means that we may have several methods which the same name, but with different parameters. This means that the actual behavior of the method depends on the kind of data that it works on. An example of this is the "toString()" method that is defined for all classes in Java and gives a textual description of the object, no matter what the type of the object is. 4.1 Class declarations A class declaration has the following syntax: [public, private or protected] class <classname> [extends <baseclassname>] [implements <classname, classname, …>] { /* Variable and method declarations. */ } Example: A minimal class definition for a bank account. public class BankAccount { } // No semicolon A minimal class declaration just contains the keyword “class” and the classname. A class is private by default, which is usually not very useful. If it should not be private, the class declaration should be preceded either by the keyword “public” or the keyword “protected”. A public class is visible in the entire program. A protected class is accessible only to classes in the same package (more about packages later). In both cases, the class definition has to be in a file of its’ own, which has the same name as the class (case sensitive!) and the extension “.java”. If the class is derived from another class, then we add “extends <baseclassname>” to indicate the base class to use. There may be only one base class. If there is no "extends" statement, then the class has the "Object" class as its' base class. In Java, the class "Object" is the root of the class hierarchy, so it is the ultimate base class for all classes. The “implements” keyword is a way of achieving a kind of multiple inheritance. It is possible to implement several abstract classes or interfaces with this keyword. Abstract classes and interfaces will be treated later, but C++ programmers should at least know what abstract classes mean. Introduction to Java programming K.Främling Page 25 Attention! There is no semicolon after the closing bracket in Java, which is a difference from “C” structures and C++ classes. 4.2 Class variables and instance variables Every object stores its' state in its' instance variables. For a bank account, instance variables could be "balance" and "id". There may also be instant variables that are set to constant values (like "#define" or "const" in "C"). Example: Class definition with instance variables and constants. public class BankAccount { // Class variable public static int nextID = 100; // Instance variables private double balance; private int id; // Constant value private final int } PREFERENCE_CLIENT_LIMIT = 10000; All variable declarations are private unless specified otherwise (so the "private" keywords in the example are not necessary). The keyword "final" signifies that we define a constant value. Public variables are accessible from any other object in the application. Protected variables are only accessible to the classes in the same class package. Class variables are indicated with the keyword "static". Class variables can be used directly through the class name, e.g. "BankAccount.nextID". So, this is a property of the class itself, not a property of the objects of this class (it is, however, directly accessible to instance methods). Usually static variables are initialised at their point of declaration, but a class may also have a special static initialisation block. Introduction to Java programming K.Främling Page 26 Example: Static initialisation block. static { nextID = 0; } 4.3 Method definitions Methods are functions that are associated to a class (class methods) or the objects of a class (instance methods). There is a special kind of method that is called a constructor method. This is a method that is called when a new object is created using the “new” keyword. A constructor initialises the newly created object, which mainly means that it sets up values for the object’s instance variables. There may be several constructors in the same class. Example: Constructors for the “BankAccount” class. public BankAccount() { this(0.0) ; } public BankAccount( double initBal ) { balance = initBal; id = newID(); } The name of a constructor function is always the same as the class name and there is no return type, but it should be declared public. There are two constructors for the class “BankAccount”. The first one is the default one, which takes no parameters. This one is used in a call like “BankAccount ba = new BankAccount()”. The only thing that it does is to call the other constructor, which takes an initial balance as a parameter. The second constructor sets the balance of the new “BankAccount” object to the value passed as a parameter and affects it a new ID. Normal method declarations consist of an access specifier (“public”, “protected” or “private”), a return type, the name of the method and the list of parameters and their type. There may be class methods and instance methods. Access to methods is determined in the same way as for variables. “newID” is a class method that returns the next unused account ID. This method has to be a class method, since there is no way that the newly created object could know what ID to use by itself. It is like in a car factory – it is the factory that knows what serial number to give to a newly manufactured car, not the car itself. } public void deposit(double amt) { balance +=amt. Now.toString() + "(id:" + id + ". } public int id() { return id.Introduction to Java programming K. private static int newID() { return nextID++. So.balance()”. } public String toString() { return super. In Java. “BankAccount. let us have a look at a small example that shows how objects are created and how references to them are managed: . Example: Instance methods of ”BankAccount”.4 Creating and referencing objects What happens in Java when we use the operator “new” is that the virtual machine reserves enough memory for containing all the data of the newly created object. a dot and the name of the method (e. This means that we do not need to worry about stack handling and “copy constructors” in the same way as in C++. The result of the operation is a reference to the newly created object. if we have an object “ba” of class “BankAccount”. } 4. bal:" + balance + ")" . instance methods can only be accessed through an object. Just like instance variables.Främling Page 27 Example: The class method newID. we could access the method “balance” by writing “ba.g. public double balance() { return balance.newID” if “newID” would not be private). all objects are situated in “global memory”. } A class method may be accessed from an object of another class (if it is not private) simply by writing the class name. } public void withdraw(double amt) { balance -=amt. what we have set up is a minimal kind of “linked list” (quite uncompleted here). secondObject. ObjCreationExample object6 = new ObjCreationExample(). while “object1 instanceof Point” is false. object2. public class ObjCreationExample { public ObjCreationExample firstObject. ObjCreationExample object5 = new ObjCreationExample().firstObject = object4. object1. object1. “instanceof”. public static void main(String args[]) { ObjCreationExample object1 = new ObjCreationExample(). . ObjCreationExample object2 = new ObjCreationExample(). which shows the objects that we created and the reference links that we set up. ObjCreationExample object4 = new ObjCreationExample(). ObjCreationExample object3 = new ObjCreationExample(). Java contains an operator which allows us to check the class that an object belongs to. } } This example sets up the “object space” shown in Figure 4.secondObject = object5.Främling Page 28 Example: Object creation and referencing (compiled). “instanceof” also works for base classes. Computer memory object2 object1 object4 References object3 object6 object5 Figure 4. the test “object1 instanceof ObjCreationExample” is true in the preceding example.firstObject = object3. This means that the test “object1 instanceof Object” is true too. So. Illustration of "object space". In fact. where one object has a link to the next one and so on.Introduction to Java programming K. Garbage collection means that there is an automatic functionality that regularly goes through the object space and checks which objects are still referenced and which are not. so they no longer exist once we return from main. so it is safe to liberate the space they use.Introduction to Java programming K. The memory address is different if you have different pieces of data. for instance).6 Java Bank Account Now our complete “BankAccount” example looks like this: .Främling Page 29 All objects are uniquely identified by their address. there is no destructor function in Java neither (unlike C++). It is not necessary thanks to garbage collection. if there are any non-Java resources used by the object that have to be liberated (a communications port reserved by the object. And since these references no longer exist. there is no reason to keep all these objects in memory. that is called before the object is destroyed by garbage collection. they would anyway since we exit the program). However. In the example of the previous chapter. Garbage collection was also used in Smalltalk from the start. This is because all the variables that reference them are local to the main-function. there may be a “finalize()” method. Those which are no longer referenced are unusable for the program. 4. there is no “delete” keyword. Having no “delete” operator.5 Garbage collection In Java. 4. all the objects would be automatically deleted once we exit from the “main” function (well. out.withdraw(5.25). id = newID(). b=BankAccount@1cc802(id:101.println("a=" + a. a=BankAccount@1cc803(id:100. } // Class method private static int newID() { return nextID++.99). System. } public void withdraw(double amt) { balance -=amt.deposit(125.0) .println("b=" + b). } public double balance() { return balance. } public String toString() { return super. public BankAccount () { this(0. } public int id() { return id. private int id. bal:" + balance + ")" . // Instance variables private double balance.Främling Page 30 Example 8. b=BankAccount@1cc802(id:101. // Constant value private final int PREFERENCE_CLIENT_LIMIT = 10000.99) The method “toString()” is special since it allows us to make a string value of the object. System. } } // no semi-colon Screen output: a=BankAccount@1cc803(id:100. System. bal:15. } // Another "special" class method public static void main(String args[]) { BankAccount a=new BankAccount(15. b.toString() ).out. } public void deposit(double amt) { balance +=amt. BankAccount b=new BankAccount(). a. Complete BankAccount example (compiled and run) public class BankAccount { // Class variable public static int nextID = 100.0) bal:9. .println("b=" + b.75) bal:125. } public BankAccount( double initBal ) { balance = initBal.toString() ).exit(0).out.println("a=" + a).out. System.toString() + "(id:" + id + ".Introduction to Java programming K. System.50).25) bal:0. awt. public static void main(String argv[]) { Frame f.show(). Circle drawing using a class derived from the standard “Point” class (compiled and run). f.out. it's there only if you need it. You don’t have to use super. myPoint2. At the end.Främling Page 31 This name is fixed.*.setSize(250. private MyPoint myPoint1.Introduction to Java programming K. you have to use that name.exit(0)” statement means to stop the Java virtual machine right now with an exit value of 0.toString if you don't want to. public class CircleExample extends Applet { private final int RADIUS_INCREMENT = 6.println("a=" + a). in fact. The word “super” is a keyword in the Java language. we notice something like “super. it is essential to use existing class libraries as much as possible. and it says that the super class' “toString” is going to be invoked. but it is very useful for exiting the program in severe error situations. Example 9. f.applet. It is the function that is used in the operation “System.” that writes out a string describing the object. and then the address of the object. This also guarantees that you can use the string concatenation operator “+” for all objects. since it reduces the programming work needed and simplifies maintenance. f. The “toString” method of class “Object” actually returns the class name.7 Class Hierarchies and Inheritance When developing an object oriented program. myPoint3. f = new Frame().toString”. the “System. @. the class “Object” is implicitly used as base class. import java. f. It cannot take any parameters and it must return a String value. . 4. Since we have not defined any superclass for “BankAccount”. This statement is not necessary here. If we look a little closer at the toString method. import java.Applet.add(new CircleExample()). 200).setLayout(new GridLayout()). 50.sqrt(d.Introduction to Java programming K. y . d. } public void setFilled(boolean b) { isFilled = b.Främling Page 32 } CircleExample() { myPoint1 = new MyPoint(20). myPoint3 = new MyPoint(d. } public void paint(Graphics g) { myPoint1. 2*radius. 2*radius).height/2. Dimension d = size(). } public void drawIt(Graphics g) { if ( isFilled ) g. } . } } } class MyPoint extends Point { private int radius. y).height) ) { myPoint3. 50).height*d.radius. MyPoint(int r) { radius = r. 2*radius.drawIt(g).drawIt(g). radius = r. int r = 1. myPoint2 = new MyPoint(50.radius. 2*radius). y .setLocation(50. myPoint2. myPoint3. r += RADIUS_INCREMENT. r).width*d.setFilled(false).fillOval(x . // Then we use some information about our size to draw a // centered figure. int r) { super(x. while ( r <= Math.width + d.setRadius(r). myPoint3.width/2.radius. myPoint2.radius.drawIt(g).drawOval(x . } MyPoint(int x. } public void setRadius(int r) { radius = r. private boolean isFilled = true. int y. else g. 10). there is a very convenient workaround for the problem. one for the global variables and one for general utility functions. Since having global constants and variables is very useful in most industry-scale applications.Introduction to Java programming K. In Example 9 we have used the standard class "Point" as a base class for our own class "MyPoint" (it should actually have been called "Circle" or simething alike). So it is impossible to declare global constants or variables anywhere you like as you would in "C" or C++. like a constructor for setting the initial position and a "setLocation()" method for changing it. 4.Främling Page 33 } This program gives the window shown in Figure 5. which contain these constant declarations and variables as static members. Figure 5. . Also notice that "MyPoint" is a private class.8 How to declare and use global constants and variables The only things that are "global" in Java are classes. One solution is to define a few special classes. This is sufficient since it is a class that is used only by the class "CircleExample" and since it is defined in the same source file as "CircleExample". Window of the CircleExample program. It might be a good solution to have one class for the global constants. This means that "MyPoint" inherits some useful properties and methods. int val2) {} . .Främling Page 34 Example: Classes for global constants.)". This convention requires some more writing for referencing global items. A_GLOBAL_CONSTANT". } public class GlobalVariables { public static int aGlobalVariable..aGlobalFunction(. .. This is extremely important for program documentation purposes and for program maintainability.Introduction to Java programming K.aGlobalVariable" and "GlobalFunctions. public class GlobalConstants { public static int A_GLOBAL_CONSTANT = 10.. } Now these are accessible from anywhere in the program as "GlobalConstants. .. variables and functions..... } public class GlobalFunctions { public static void aGlobalFunction(int val1. but it has the advantage of clearly indicating when global items are used and modified. "GlobalVariables. i.Introduction to Java programming K.Främling Page 35 5. usually small applications that are run inside a WWW browser like Netscape Navigator or Microsoft Internet Explorer.1 Passing parameters to applets from a HTML page Applet behaviour may be parameterised by passing parameters to them in the <applet> tag of the HTML page. Applets Most Java applications are still applets. . They are also used for animating Internet pages just in order to make them more interesting. Their main purposes are to present information in a user friendly and interactive way. These parameters correspond to command line parameters of classical programs. 5.e. y = 10 . private String private int theString. for ( i = 0.drawString(theString. We get the values of these parameters with the method “getParameter(“<paramName>”)”. import java. This method is defined in the Applet class. } } } This applet takes the text string to draw and the number of times to draw it as parameters.Applet. y += 20 ) { g.Introduction to Java programming K. public class AppletParam extends Applet { private final String DEFAULT_TEXT = new String("No text parameter!"). Passing parameter values from HTML to an Applet (compiled and run) import java. else theString = DEFAULT_TEXT. private final int DEFAULT_COUNT = 1.applet. } public void paint(Graphics g) { int i. String p2 = getParameter("Count"). if ( p2 != null ) repCount = new Integer(p2). y.intValue(). 0. // Second parameter is the number of repetitions. y). public void init() { // First parameter is the string to show. i++. else repCount = DEFAULT_COUNT. repCount. where “<paramName>” is the name of the parameter.awt.*. Corresponding HTML page: .Främling Page 36 Example 10. if ( p1 != null ) theString = p1. String p1 = getParameter("Text"). i < repCount . There is already an empty “init()” method defined in the class Applet.java">The source</a>. tag! </applet> <hr> <a href="AppletParam. . Netscape Navigator window for applet parameter passing example.Främling Page 37 <html> <head> <title>Applet parameters</title> </head> <body> <h1>Passing parameters from HTML to Applets</h1> <hr> <applet code=AppletParam.APPLET>.2 Animation We will first start off with a small example that just shows an image in our applet display area. What we did here was just to overload it and do what we needed to do. The “init()” method is a special method that is always called by the browser when the applet is loaded. tag but isn't running the applet.class width=350 height=150> <param name=Text <param name=Count alt="Your browser understands the <. 0. 0.Introduction to Java programming K.*. Figure 7. } public void paint(Graphics g) { // Just draw the image if we have finished loading it.applet. . */ import java. we again have a “init()” method.jpg"). /** * Simple applet that just displays an image. Showing an image in an applet (compiled and run).awt. } } } As in the previous example. public class AnimationExample1 extends Applet { privateImage animImage. this). animImage = getImage(getDocumentBase().drawImage(animImage. This time it loads the image that we want to display. Netscape window for applet animation Example 11.Främling Page 38 Example 11. import java. "anim1. if ( animImage != null ) { g. public void init() { // Read in the image to display.Applet. So. if ( animImage != null ) { imgw = animImage. which memorises the current position of the caveman: private Point imgPos = new Point(0. imgh.height.Främling Page 39 We leave it up to the reader to construct the corresponding HTML page.y. Dimension d = size().getWidth(this). We will speak more about threads later. Then we modify the “paint()” method to look like this: public void paint(Graphics g) { int imgw. This means that it is not notified about display area size changes. imgPos. For now it is enough to know that a thread is a process that gets execution time on regular intervals and has a certain time to do it.y = (imgPos. we have to use a thread which is activated on regular intervals and which avoids our applet to get blocked. imgPos. // This loop is not a very good idea!!! while ( true ) { g. In order to do this correctly. if ( imgw == -1 || imgh == -1 ) return. imgh = animImage.x = (imgPos.getHeight(this). nor any other user interaction. that is a handle to the thread: .drawImage(animImage. imgPos. Doing an animation like this is not a good idea!!! What happens now is that our applet is in an eternal loop. we will first add a “Point” (standard Java object) to the instance variables of our class.y + 1)%d. What our thread will do is to regularly “kick” our applet and make it move the animation forward.x + 1)%d. which means that it is no longer capable of reacting to events coming from outside. 0). we first add a new instance variable. this).width. imgPos. } } } This is a very simple way of getting the caveman to glide down from the upper left corner of the applet display area towards the lower right corner. Now we make the caveman move.Introduction to Java programming K.x. that looks like this: . “stop()” is called each time the browser exits from a page that contains the applet. we obviously have to have an “init()” method that sets up our thread object. animThread. "anim1.white). For our animation example. } public void start() { animThread = new Thread(this). “start()” also gets called each time that the browser gets to a page where the applet is included. “start()” and “stop()”.start().Introduction to Java programming K.// We use a Thread object for animation! We have already seen the “init()” method that gets called before an applet starts executing.stop(). The browser calls the “start()” method straight after having called the “init()” method. But this “kick” has to be realised by calling one of our methods. There is a standard method that is called “run()” for this purpose. setBackground(Color.Främling Page 40 private ThreadanimThread. a “start()” method that starts the animation and a “stop()” method which stops it.jpg"). We also have two other special methods. } Now we will have a thread running that knows it should “kick” us regularly. } public void stop() { animThread. These three methods now look like this: public void init() { animImage = getImage(getDocumentBase(). repaint().x + 1)%d. while ( true ) { d = size(). } } Java is a language that has a strict type control. if ( imgw == -1 || imgh == -1 ) return. imgPos. so we have to have a try-catch here. We have to change our class declaration line to look like this: public class AnimationExample3 extends Applet implements Runnable The “implements” keyword means that our class contains all the methods required by the “Runnable” interface. } try { Thread. The new “paint()” method looks like this: public void paint(Graphics g) { int imgw. imgPos. So we override the default “repaint()” method with our own: . Exception handling is compulsory in this case. The reason for this flickering is that each time we call the standard “repaint()” method. } catch ( InterruptedException e ) {} } } “Thread.x.getWidth(this). imgh. g. It even wipes out the previous image of the caveman. so that we don’t get a “trace”.Främling Page 41 // This is the method that makes the animation work correctly! public void run() { Dimension d. Now our applet works correctly.getHeight(this). this).sleep(10)” determines the animation speed by pausing the animation during 10 ms.x = (imgPos. Now we have moved the animation logic into the “run()” method instead of having it in the “paint()” method. it first clears the entire applet display area before calling our “paint()” method. if ( d != null ) { imgPos. imgh = animImage. However.height.Introduction to Java programming K.y + 1)%d. so we will try to reduce this.width.sleep(10).y = (imgPos. imgPos. if ( animImage != null ) { imgw = animImage.y.drawImage(animImage. This is why our class has to implement a standard interface called “Runnable” in order to compile (more about interfaces later). we notice that it flickers a lot. if ( d != null ) { if ( animImage != null ) { imgw = animImage. 0. } } } try { Thread.x + imgRect. imgh. Dimension d. imgw.getHeight(this). which requires quite a few modifications. So our applet just has to wait for the image to be loaded far enough before it knows the size of the image. imgh. This is necessary because the size of the image is not known immediately at load time. imgRect.y + imgRect.Introduction to Java programming K. 0. imgh). } catch ( InterruptedException e ) {} } } In addition to the turning logic. imgRect.x = (imgRect.y + 1)%d. Our “run()” method has now grown a lot bigger: public void run() { int imgw. We modify the “drawImage()” call in our “paint()” method correspondingly. imgw. 0. } We will also make the caveman turn while he is moving. imgRect.sleep(10).height.x. } else { imgRect. in separate threads. imgRect. } repaint(). if ( imgRect. imgRect.width. so that it scales the image on the fly to fit into the correct rectangle: g.x + 1)%d.width--.width.width == -imgw ) imgRect. // Rectangle instead of Point. We start by having an image display rectangle instead of just a point: private Rectangle imgRect = null. it now contains some extra tests for setting up the initial display rectangle.height.y. this).Främling Page 42 public void update(Graphics g) { paint(g). Java loads images asynchronously. while ( true ) { d = size().y = (imgRect.drawImage(animImage. if ( imgw != -1 && imgh != -1 ) { if ( imgRect == null ) { imgRect = new Rectangle(0. else imgRect. imgh = animImage.width = imgw. In fact.getWidth(this). . Rectangle imgRect = null. import java. // Needed for clearing. oldRect. What we do.Främling Page 43 Asynchronous image loading is extremely useful for internet purposes. oldRect.*.x + oldRect. // Needed for clearing.width.Introduction to Java programming K. setBackground(Color. Animation example with a turning image that bounds against the sides of the applet display area (compiled and run).height).awt. else g.width > 0 ) g. -oldRect.jpg").Applet. is that we memorise the previous display rectangle of the caveman image and clear only that instead of clearing the entire applet display area. but now there is no longer anything that would clear the previous image.clearRect(oldRect. we first need a new instance variable that stores the old rectangle: private Rectangle oldRect = null. } Our final touch to the animation is to make the caveman bounce against the borders of the applet display area. oldRect. We notice that the flicker disappeared.width. This means modifying the “run()” method accordingly. Rectangle oldRect = null. oldRect. Then we add the following code into our “paint()” method just before the call to “drawImage()” for clearing the previous rectangle: if ( oldRect == null ) { oldRect = new Rectangle(imgRect). "anim1.y. For doing this. where image loading might be long and where there may be several images to display in the same page. Thread animThread. Example 12.white).width.setBounds(imgRect). } .height). oldRect.x.clearRect(oldRect. public void init() { animImage = getImage(getDocumentBase(). } else { if ( oldRect. Example 12 shows the entire applet code.y.applet. public class AnimationExample5 extends Applet implements Runnable { private private private private Image animImage. import java. oldRect. this). animThread.x + oldRect. wincr = -1.height. oldRect. if ( animImage != null ) { imgw = animImage. imgRect.getWidth(this).getHeight(this). -oldRect.setBounds(imgRect). oldRect. imgh. else g.height).x + imgRect. oldRect. imgh). oldRect. imgh.y. } g.Främling Page 44 public void start() { animThread = new Thread(this).width. if ( imgw != -1 && imgh != -1 ) { if ( imgRect == null ) { imgRect = new Rectangle(0.width.height). } . 0. // Here we clear what has to be cleared from previous // animation step. } public void paint(Graphics g) { int imgw.x. imgRect. 0.drawImage(animImage. } public void stop() { animThread.width > 0 ) g. oldRect.width. imgh = animImage. while ( true ) { d = size().getHeight(this). } else { if ( oldRect.clearRect(oldRect.y. imgh = animImage. } } public void update(Graphics g) { paint(g).y. imgRect. } public void run() { int imgw.clearRect(oldRect.Introduction to Java programming K. Dimension d. yincr = 1.y + imgRect.width. imgRect. imgw. if ( imgw == -1 || imgh == -1 ) return.x. imgh. oldRect. if ( oldRect == null ) { oldRect = new Rectangle(imgRect). if ( d != null && animImage != null ) { imgw = animImage.stop().start().getWidth(this). imgw. int xincr = 1. 0. x <= 0 || imgRect. } else if ( imgRect.height >= d.y += yincr.width ) xincr = -1.sleep(10). if ( imgRect. We also add two new instance variables to our class for storing the references to the two audio clips that we use: private AudioClip private AudioClip bounceSnd.width || imgRect.Introduction to Java programming K.width >= d. imgRect. which plays continuously. There will also be a sound when the caveman bounces against the walls. } } try { Thread.width >= imgw ) { wincr = -1.x >= d. "spacemusic. 5.applet.x + imgRect. } imgRect.au"). if ( imgRect. which makes the background sound play continuously (“loop()” is a method of the class AudioClip): . if ( imgRect. Doing this requires that we import the standard Java class AudioClip: import java.Främling Page 45 else { if ( imgRect.width <= 0 ) xincr = 1.width <= -imgw ) { wincr = 1.height ) yincr = -1. if ( imgRect. In the “init()” method we add the following lines for initially loading the two sounds: bgSnd = getAudioClip(getCodeBase(). bounceSnd = getAudioClip(getCodeBase(). "0. } repaint().x + imgRect.AudioClip.y + imgRect. We will improve this while adding a few sound effects.au").3 Sound effects We will add a background sound to our applet. } catch (InterruptedException e) {} } } } The animation still flickers quite badly. In the “start()” method we add this line. imgRect.x += xincr.width += wincr.y <= 0 ) yincr = 1. bgSnd. clearRect(oldr.4. Now we have the sound effects that we wanted. 4.height).play(). 4).y.x + oldr. Rectangle newRect. oldRect. Rectangle oldRect) { Rectangle oldr.stop(). } Then we replace the clearing code of our “paint()” method with the following: if ( oldRect == null ) { oldRect = new Rectangle(imgRect). Another quite common way is to have an off screen image.width. In our “stop()” method we add lines for stopping the sounds when the browser leaves the page: bgSnd.Främling Page 46 bgSnd.y. oldr. It is possible to reduce or eliminate animation flicker in many ways. so we will work a bit more on reducing screen flicker. g.width .x. oldRect).Introduction to Java programming K. Then this off screen image just gets copied onto the screen. which is rapid and makes the transition from one animation step to the next one very fluent.clearRect(oldr.width.clearRect(oldr.clearRect(oldr. if ( oldRect.y. } clearOldRect(g.height . We introduce a new method for doing it: private void clearOldRect(Graphics g. . We do it just by clearing the borders of the old rectangle instead of clearing the entire rectangle.4. oldr. else oldr = new Rectangle(oldRect). oldRect. newr. but at least we reduce flicker. 4). // Flip coordinates to make it easier. 4.x. g. imgRect.loop(). oldr.y. oldr.width. Each time that the caveman changes his direction in the “run()” method.stop().height). -oldRect. g.x. oldRect.y + oldr. bounceSnd. oldr. This is just one simple way of doing it. where the graphical operations take place. oldr.width < 0 ) oldr = new Rectangle(oldRect. oldr. we call the “play()” method of the bounce sound: bounceSnd.height). g.width.setBounds(imgRect). oldr. This is not a very sophisticated solution.x + oldRect. As usual.Främling Page 47 5.width. What we do here is to set up an off-screen image of exactly the same size as the applet display area. where the graphical operations take place.height).Introduction to Java programming K. if ( d != null && animImage != null ) { // Set up offscreen buffer. Then this off screen image just gets copied onto the screen. Then we modify the “paint()” method to look like this: . What we need to do first is to declare an instance variable to contain the off-screen image: private Image offscreen = null.getWidth(this). since the size of its’ display area never changes. which is rapid and makes the transition from one animation step to the next one very fluent. we set it to null so that we can easily test if it has been initialised or not. It would be more complex for a normal window. An applet is an easy case. if ( offscreen == null ) offscreen = createImage(d. d. imgw = animImage. … “createImage()” is a method that is defined in the “Component” class that is one of the base classes of “Applet”.4 Double-buffered animation Another quite common way to avoid flicker in animations is to have an off screen image. We set up the off-screen image in the “run()” method: while ( true ) { d = size(). imgw = animImage.width. oldRect). The final call to “drawImage()” just copies the off-screen image onto the screen. if ( oldRect == null ) { oldRect = new Rectangle(imgRect).getWidth(this). imgh = animImage. 0. if the animation itself is slower than this delay.setBounds(imgRect). We could even use clearing of the entire old image area again. . offscreen_g = offscreen.x.y + imgRect. g. imgRect.getHeight(this). imgRect. then the classical method is to increase the animation step length (instead of one pixel. Just clearing the borders sometimes runs into synchronisation problems and “leaves behind” a small part of the image. so it is difficult to see the transition. this). This change only slightly affects animation speed. instead of just clearing the borders. this). // Clear the needed areas of old display. 0. The call “offscreen. } We first check that we have both a valid animated image and a valid off-screen. imgh.y. } clearOldRect(offscreen_g.getGraphics(). imgRect.drawImage(animImage.drawImage(offscreen. 0. This is a very rapid and flicker-free operation since it happens scanline by scanline. oldRect.x + imgRect. Then all drawing which previously went directly to the screen now goes into the off-screen image. 0. stepping two or more). if ( animImage == null || offscreen == null ) return. imgh.” returns a “Graphics” object which allows us to draw into the image just like we would draw onto the computer screen. offscreen_g. However. “getGraphics()” is a method defined in the class “Image”. Animation speed depends on the delay that we define in the call to “ Thread.getGraphics(). if ( imgw == -1 || imgh == -1 ) return.Introduction to Java programming K. imgRect. imgw. imgRect.Främling Page 48 public void paint(Graphics g) { int imgw.height.sleep()”. Graphics offscreen_g. we will stick to the 1. The new model is much more flexible and simplifies writing well-structured.2 For User interface elements this chapter.x event model in this course. imgRect.1 Reacting to a user click inside the applet display area All we need to do in order to react to a mouse click inside the applet display area is to override the “mouseDown()” method: public boolean mouseDown(Event evt. which is accessible through links in the JDK documentation.sun. is that if the execution of the “mouseDown()” method is not finished when the animation thread interrupts it.width. there is no big danger. int x. return true. int y) { imgRect. Although version 1.Främling Page 49 6. when we already have to repaint. This would make our class “thread-safe”. modular programs. What we do is that we flip around the caveman each time that the user clicks inside the applet display area. 6. It might be a good idea to add the “synchronized” (more about this together with threads) keyword to the method declaration. This especially concerns the handling of events. we might just be in the middle of the turning operation. . This is to be sure that our applets will work fine even with older internet browsers. 6.width.x. we will use the existing course at “. the program may end up in a weird state and start to behave strangely.0.com/developer/onlineTraining/GUI/AWT ”.0.java. } Here we are still working with our animation example from the previous chapter. What could happen now. In the current case.1.x virtual machines have become a great majority.Introduction to Java programming K. The caveman always ends up by being flipped correctly.1. User Interaction User interaction has changed greatly from version 1. But in more complex situations.x to 1.x += imgRect.width = -imgRect. This is a public course. Menus contain "MenuItem". First. public static void main(String argv[]) { MenuExampleFrame f = new MenuExampleFrame("Menu example"). minimising. there is a "MenuBar" object associated with the frame. a window also has some buttons for closing it. . Usually. Example 13. testMenu. It is generally a good idea to subclass the "Frame" class if the application uses menus. f. so we could say that a menu belongs to a window. since menu events end up in the "action()" method of the frame that contains them. from which the various menus can be accessed. a window has a menu bar.show().Introduction to Java programming K. 6.awt. activating it. Menu fileMenu. f.Främling Page 50 Accessing this course requires registering to the Java Developer Connection (JDC).3 Window-related user interface elements Menus are connected to a certain window (or a certain application on some operating systems). } MenuExampleFrame(String title) { super(title). Only the chapters that are grouped together under the title “Widgets” are considered here. This menu bar contains "Menu" object.*. Menu and window event handling (compiled and run) import java. class MenuExampleFrame extends Frame { MenuBarmyMenubar. maximising and restoring it etc.pack(). Menus are organised in a hierarchical fashion. "CheckboxMenuItem" or other "Menu" objects (for creating submenus). Example 13 shows how to add a menu bar and menus to a window and how to handle the window closing event. It is also possible to associate menu shortcuts to menu items. Actually. which (at least for the moment) is free. Various events are generated and sent to the window when the user uses one of these. add(new MenuItem("Save".Främling Page 51 Menu sub_menu.arg). */ public boolean action(Event evt.add(new MenuItem("-")). add(c).target instanceof CheckboxMenuItem ) System.println(evt. testMenu = new Menu("Test"). if ( evt. It is usually a good idea to call the super-class' method for all standard event handling methods ("super..add(new MenuItem("New")). If we forget to do this for "handleEvent()".out. The type of the event can then be tested against some event codes that are defined in the "Event" class. c. fileMenu.exit(1).add(fileMenu). . then "action()" never gets called.action(evt. return super..add(new CheckboxMenuItem("test2")).WINDOW_DESTROY ) System.add(testMenu).add(new MenuItem("Exit")). new MenuShortcut('s'))). myMenubar.add(new MenuItem("Close")). fileMenu. fileMenu. Otherwise we might interrupt the event propagation chain. Canvas c = new Canvas(). myMenubar. testMenu.add(sub_menu). fileMenu = new Menu("File"). fileMenu.equals("Exit") ) System.")).println(((CheckboxMenuItem) evt.handleEvent(evt)" for instance).Introduction to Java programming K. // Set up the menus. } } Window events are sent to the "handleEvent()" method. Object what) { if ( evt. for instance. fileMenu.add(new MenuItem("Open. // Just so we get a size.add(new CheckboxMenuItem("test1")). } /** Catch window events.arg. sub_menu = new Menu("SubMenu").target).out. else System.id == Event.add(new CheckboxMenuItem("test3")).resize(300. } /** Catch menu events.getState()). what). testMenu. setMenuBar(myMenubar). sub_menu. fileMenu. return super. myMenubar = new MenuBar().handleEvent(evt). sub_menu. */ public boolean handleEvent(Event evt) { if ( evt. 100).exit(1). Window Layout Java applications should run in a similar way on any operating system. Java window layout managers are used for avoiding these problems.sun. Only the chapters that are grouped together under the titles “Layout Managers”. prefers controlling the size and location of the contents of a panel in absolute co-ordinates. Unfortunately. Accessing this course requires registering to the Java Developer Connection (JDC). do not have the same window border widths or there might be other differences. "Events". which (at least for the moment) is free. All these factors make it difficult to know exactly how big our user interface should be and where they should be positioned. different operating systems do not use exactly the same fonts.2 The "null" layout If the programmer.1 For Window layout managers this chapter. we will use the existing course at “. 7. which is accessible through links in the JDK documentation. it is possible using the "null" layout.Främling Page 52 7.java. The programmer just defines some rules for the positioning and sizing of the elements in relation to each other and/or to the window and the manager respects this as well as possible.Introduction to Java programming K. "Colors" and "Fonts" are considered here. "Nested Panels". for some reason. This means that the user interface should look about the same in all cases.com/developer/onlineTraining/AWT/AWT . . 7. This is a public course.html”. add(new NullLayoutExample()). 150). b = new Button("Button 4"). f. b.move(50. f. 30). 25).resize(60.Främling Page 53 Example 14. b. b. add(b). } public Dimension getPreferredSize() { return new Dimension(200. 10). add(b). 50). Figure 8. Window created using a panel with "null" layout. f. b.*. add(b). In order to use a "null" layout we have to do at least the following: • Create a subclass that extends panel.show(). Using the "null" layout for absolute positioning of window elements (compiled and run). 100).resize(80. 20). b = new Button("Button 1").Introduction to Java programming K. b = new Button("Button 2").move(10.pack(). b. b. . b = new Button("Button 5").setLayout(new GridLayout()). b. 20). add(b).move(80.resize(45.resize(50. } NullLayoutExample() { Button b. 20). b. b. b.move(100. import java. setLayout(null). b = new Button("Button 3").resize(60. public class NullLayoutExample extends Panel { public static void main(String[] argv) { Frame f = new Frame().awt. add(b). 40). 50).move(30. f. } } This program gives the window shown in Figure 8. We will continue to develop the example from the previous example.Främling Page 54 • • Set the layout of this panel to "null" with the "setLayout()" method. new Label("Java Basics Course")). then add other user interface elements into the panel. "About me. new Button("Close")).. Object arg) { dispose(). } Now.. especially modal such (which prevent input from all other windows of the application). It is a good advice to never add any user interface elements directly into a frame! Just add a panel into it instead. pack(). true). we get a dialog window like the one in Figure 9. Override the "getPreferredSize()" method so that it returns the size that you want the panel to be. This is the best way to avoid problems due to different window styles on different operating systems. } } Then we add the following method to our "NullLayoutExample" class: public boolean action(Event evt.target instanceof Button ) { (new AboutDialog(new Frame())).action(evt.Introduction to Java programming K. 7.3 Dialog windows Most applications need to be able to display dialog windows. } return super. Clicking on the "Close" button closes the dialog window.show().". • Set the size and location of all user interface elements that you add into the panel. } public boolean action(Event evt. every time that we click on a button in our "null" layout window. // "true" because modal. Object arg) { if ( evt. add("South". return true. . add("Center". arg). So we add the foloowing class definition to our existing source code: class AboutDialog extends Dialog { AboutDialog(Frame f) { super(f. return true. It is essential to call the constructor of Dialog in the constructor of AboutDialog. which we have used here. The default layout for dialogs is BorderLayout.Introduction to Java programming K.Främling Page 55 Figure 9. . Otherwise frame management and display will not work correctly. Example dialog window. we chain them together.1 File dialogs for opening and saving files The AWT library contains standard dialogs for letting the user browse the hard disks for files to open or save. They are implemented by the class “FileDialog”. Using the standard “Open” dialog (compiled and run).*. It is. Using these classes directly is hardly ever practical nor efficient. This is how we achieve buffered file reading. however.awt. They return the directory path (with and ending ‘/’ character) and the name of the file.getFile()). The implementation is still quite different from that of C++.io.. public class FileOpenDlg { public static void main(String[] argv) { FileDialog fd = new FileDialog(new Frame(). 8. Before looking at the actual file reading/writing classes. for instance. for instance.*.println(fd.getFile() != null ) System. if ( fd. we will have a look at the standard facilities of Java for letting the user specify what file to create/open/write.". "Open file.. . The principle is that we first have very low-level and simple classes for opening.show(). else System. import java. then “getFile()” returns “null”. just like C++.out.println("Open cancelled!"). import java. File Reading and Writing File reading and writing is done in quite a different way from how it is done in “C”. which is derived from the standard class “Dialog”.Introduction to Java programming K.LOAD). FileDialog.out.getDirectory() + fd. If the user cancels the dialog. fd. Example 15. reading and writing files. based on the notion of streams. In order to read/write input streams more efficiently.Främling Page 56 8. } } The methods “getDirectory()” and “getFile()” are defined for the “FileDialog” class. fd.*.length != 2 ) { System.out. } } The standard “Save as” dialog has the interesting feature of asking the user if he wants to replace an existing file.0.".io. import java.println("Syntax: java TextFileCopy <file1> <file2>"). One limitation of this example is that it requires Java 1. "Save as.Introduction to Java programming K. Example 17. FileDialog. import java. else System.awt.1. public class TextFileCopy { public static void main(String[] argv) { String line. if ( argv.Främling Page 57 Example 16.. Using the standard “Save as” dialog (compiled and run).getFile()). import java.2 Reading and writing text files It would be possible to read and write text files in many different ways with the standard class libraries of the “io” package. This class library has actually changed and evolved a lot since the first version of it. since the “Reader” and “Writer” classes did not exist in Java 1. Copying a text file into another (compiled and run).SAVE). especially when it should be done line by line. 8. Example 17 shows one of the easiest and most efficient ways of reading and writing text files.io.getDirectory() + fd.*.out.exit(1).println(fd.x.x in order to work.println("Save cancelled!"). if ( fd. System.out.show().getFile() != null ) System. } . This means that the programmer does not have to test for existing files. public class FileSaveDlg { public static void main(String[] argv) { FileDialog fd = new FileDialog(new Frame().*.. The try-catch mechanism is very useful here. out.out. just print out the exception. Example 18 illustrates a simple way of doing this.Introduction to Java programming K.println(e). } in.println(line). } catch ( IOException e ) { // An error happened. } } } The program first checks that we have both the name of the file to read and the file to write and exits if both are not present.Främling Page 58 try { BufferedReader in = new BufferedReader(new FileReader(argv[0])). while ( (line = in. . Then it creates a buffered reader for the given input file and a suitable writer (the “PrintWriter” class) for the given output file. PrintWriter out = new PrintWriter(new FileWriter(argv[1])).close().close(). Otherwise the buffer may not be flushed correctly at the end.readLine()) != null ) { out. 8. After this the while loop does the actual copy. error creating output file and all potential read/write errors.3 Reading a file using a URL It is possible for an applet to open an “InputStream” object on any file that is located in its’ own code base directory or a subdirectory of it. */ System. When using buffered input/output it is often important to call the “close()” method for them. With one single try-catch block we treat the case of non-existing input file. java. while ( (line = dinp. Otherwise it does not establish the connection to the file. add(fileDisplay).appendText(line + '\n'). public URLread() { setLayout(new GridLayout()).Introduction to Java programming K.net. Reading a file inside an applet (compiled and run).applet. private TextArea fileDisplay. java. if ( fileName != null ) { // Get an input stream and put in everything into TextArea. When running this example it is essential that the browser being used is already started up.*.readLine()) != null ) { fileDisplay.println(e).io. fileName).*. } public void init() { // Get the neme of the file to show.out.close(). } public void start() { String line. public class URLread extends Applet { private String fileName. java. import import import import java. } catch ( Exception e ) { System. Then it shows the contents of the file inside of the text area.Applet. fileName = getParameter("FileName"). . This seems to be a bug at least in certain versions of Netscape Navigator.awt. fileDisplay = new TextArea(). } dinp.Främling Page 59 Example 18. } } } } This example reads a file whose name is given as a parameter to the applet from the HTML page that invokes it. DataInputStream dinp = new DataInputStream(fileURL.openStream()).*. try { URL fileURL = new URL(getCodeBase(). It has methods both for formatted input and output. . For correct character output. The same structure applies to output classes.Introduction to Java programming K.4 Other input/output classes As shown by the examples on file input/output. "readFloat()" etc. If we then pile a "BufferedInputStream" on it.separator) and for separating several paths (File. If we still pile a "DataInputStream" on it. 8. Random access input/output is provided by the class "RandomAccessFile".5 The “File” class Functions for testing the existence of a file. deleting and renaming files and performing other file system related operations are provided by the standard class "File". the most basic input behaviour is provided by the "InputStream" class. It is recommended to use these classes for all character input whenever it is possible. we get access to methods like "readLine()".Främling Page 60 8. The "File" class also has public variables. for retrieving the list of files in a directory. it is possible to "pile" stream objects after each other in order to achieve supplementary behaviour. Most output classes are derived from the class "OutputStream". These classes are derived from the "Reader" class. we get more efficient reading. Classes derived from "InflaterInputStream" and "DeflaterOutputStream" provide support for reading and writing ZIP and GZIP format compressed files. For instance. including the method "readLine()". All these classes are derived classes from "InputStream" and belong to the first generation of data input classes. it is recommended to use classes that are derived from the more recent class "Writer".pathSeparator). There is a new generation of classes for reading character input. since they treat Unicode characters correctly. which contain the system-dependent constants for separating directories in a file path (File. out.").io.getName() + " exists. } } File objects may be used when creating input/output streams as well as using the direct file names.").Främling Page 61 Example 19. Using the "File" class for testing the existence of a file (compiled and run). else System.File. public class FileExample { public static void main(String[] argv) { File f = new File("FileExample.out.exists() ) System.println("File " + f. . if ( f.java").getName() + " does not exist. import java.Introduction to Java programming K.println("File " + f. Object o2). Object o2). // Some sort logic here. where the benchmarking logic itself is defined in the abstract class "Benchmark". So the class "IntSorter" would have to provide an implementation for the methods that are declared abstract. list[j]) < 0 ) swap(list[i]. The following example shows an implementation of a benchmarking program. Now implementing other benchmark tests simply requires creating a new derived class that implements the "benchmark()" method. One example of an abstract class could be a class for sorting objects (class "Sorter" for instance). Abstract Classes and Interfaces An abstract class is a class which only implements a part of the functions that it is intended for. The main issue is that we have a partial implementation (the sort logic) while some parts of the implementation have to be provided by derived classes. list[j]).Främling Page 62 9. } } The sort logic is not written here. void sort(Object[] list) { int i = 0. Then a class "IntSorter" would only need to provide one method for comparing two integers and another method for swapping those that are out of order. if ( compare(list[i]. then call to compare and swap // methods. but that is not the main issue. The following class definition compiles alright: abstract class AbstractSort { abstract int compare(Object o1. .Introduction to Java programming K. j = 0. which provides the sorting logic itself. The method that performs the calculation used for benchmarking is then defined in the derived class "MethodBenchmark". abstract void swap(Object o1. start).. So it is not possible to create objects of interface classes. i < count .Introduction to Java programming K.currentTimeMillis(). just like it is not possible to create objects of abstract classes neither. for ( int i = 0 . System. i++ ) benchmark()..parseInt(argv[0]).repeat(count). public long repeat(int count) { long start = System. long time = new MethodBenchmark(). Abstract class for benchmarking (compiled and run). } } Program output: C:\>java MethodBenchmark 1000 1000 methods in 60 milliseconds An interface is a class definition that only contains abstract methods (no method implementations at all).out. } } public class MethodBenchmark extends Benchmark { void benchmark() {} // Does not do much. . abstract class Benchmark { abstract void benchmark(). public static void main(String[] argv) { int count = Integer.Främling Page 63 Example 20.println(count + " methods in " + time + " milliseconds"). return (System.currentTimeMillis() . awt.x.setLocation(x. 3). public void drawIt(Graphics g) { g.clearRect(oldPos.event. y++. interface AnimatedObject { void move(). oldPos. y.*. import java.Introduction to Java programming K. 3. } public abstract void move().fillOval(x. * We only react to "WindowClosing" events for exiting the program.1. y). which * was included in Java 1.awt. 3. } } /** * This class implements the "WindowListener" interface. void drawIt(Graphics g). } } class XMovingPoint extends AnimatedPoint { public void move() { if ( oldPos == null ) oldPos = new Point(x. y). public static void main(String[] argv) { . 3). void clearOld(Graphics g). AnimatedPoint() { x = y = 10. else oldPos.y. else oldPos.Främling Page 64 Example 21.*. y). x++. y). } } class YMovingPoint extends AnimatedPoint { public void move() { if ( oldPos == null ) oldPos = new Point(x.*. } abstract class AnimatedPoint extends Point implements AnimatedObject { protected Point oldPos = null.setLocation(x. */ public class AnimationInterface extends Canvas implements WindowListener { AnimatedObject[] points = new AnimatedObject[2]. } public void clearOld(Graphics g) { if ( oldPos != null ) g. Interfaces (compiled and run). import java. p. "AnimatedPoint" both extends the "Point" class and implements the "AnimatedObject" interface.resize(300. p.setLayout(new GridLayout()). f.Introduction to Java programming K.move(). In fact.add(c). which declares that all classes that implement it should implement at least the methods "move". i < 50 .setLayout(new GridLayout()). points[0]. AnimationInterface c = new AnimationInterface(). } public public public public public public public } void void void void void void void windowOpened(WindowEvent e) {} windowClosing(WindowEvent e) { System. } windowClosed(WindowEvent e) {} windowIconified(WindowEvent e) {} windowDeiconified(WindowEvent e) {} windowActivated(WindowEvent e) {} windowDeactivated(WindowEvent e) {} This example first declares the interface "AnimatedObject". but it can implement any number of interfaces. points[1]. } catch ( Exception e ) {} points[0]. so it is possible to create objects of these classes.drawIt(g).add(p). } AnimationInterface() { points[0] = new XMovingPoint(). 200). which is the reason why it has to be declared abstract. i++ ) { points[0].drawIt(g). Interfaces are Java's way of doing multiple inheritance.sleep(50).drawIt(g).clearOld(g). } public void paint(Graphics g) { // Make the points move 50 steps. f.pack(). f. } points[0]. c. points[1].Främling Page 65 Frame f = new Frame(). points[1]. Finally. the classes derived from "AnimatedPoint" implement the "move" method.clearOld(g). try { Thread.drawIt(g). "drawIt" and "clearOld". Then the class "AnimatedPoint" implements most of this interface. points[1]. f.addWindowListener(c). Panel p = new Panel().move(). f.exit(0). . except for the method "move".show(). for ( int i = 0 . A class can extend only one base class. points[1] = new YMovingPoint(). x event model. we use a feature of the Java 1. .1.0. which would override the "handleEvent" method. With the Java 1. For closing the application window.Främling Page 66 As shown by this example. which makes it possible for any class to receive window-related events. This is implementing the "WindowListener" interface. including window closing events.Introduction to Java programming K. it is possible to declare variables whose type is an interface class. this means that we can only use methods defined in the "AnimatedObject" interface for these objects. we would have had to create a derived class from "Frame".x event model. This is why it is possible to declare "AnimatedObject[] points". However. This action might not be possible to undo. Are you sure you want to continue?
https://www.scribd.com/doc/95268319/10-1-1-167-9827
CC-MAIN-2016-07
refinedweb
14,053
61.22
=head1 NAME perldelta - what's new for perl v5.6 (as of v5.005_64) =head1. =head1 Incompatible Changes =head2 Perl Source Incompatibilities Beware that any new warnings that have been added or old ones that have been enhanced are B<not> considered incompatible changes. Since all new warnings must be explicitly requested via the C<-w> switch or the C<warnings> pragma, it is ultimately the programmer's responsibility to ensure that warnings are enabled judiciously. =over 4 =item CHECK is a new keyword In addition to C<BEGIN>, C<INIT>, C<END>, C<DESTROY> and C<AUTOLOAD>, subroutines named C<CHECK> are now special. These are queued up during compilation and behave similar to END blocks, except they are called at the end of compilation rather than at the end of execution. They cannot be called directly. =item Treatment of list slices of undef has changed'}; See L<perldata>. . =item C<undef> fails on read only values Using the C<undef> operator on a readonly value (such as $1) has the same effect as assigning C<undef> to the readonly value--it throws an exception. =item. =item vec(EXPR,OFFSET,BITS) enforces powers-of-two BITS vec() generates a run-time error if the BITS argument is not a valid power-of-two integer. =item Text of some diagnostic output has changed Most references to internal Perl operations in diagnostics have been changed to be more descriptive. This may be an issue for programs that may incorrectly rely on the exact text of diagnostics for proper functioning. =item C<%@> has been removed The undocumented special variable C<%@> that used to accumulate "background" errors (such as those that happen in DESTROY()) has been removed, because it could potentially result in memory leaks. =item Parenthesized not() behaves like a list operator The C<not> operator now falls under the "if it looks like a function, it behaves like a function" rule. As a result, the parenthesized form can be used with C<grep> and C<map>. The following construct used to be a syntax error before, but it works as expected now: grep not($_), @things; On the other hand, using C<not> with a literal list slice may not work. The following previously allowed construct: print not (1,2,3)[0]; needs to be written with additional parentheses now: print not((1,2,3)[0]); The behavior remains unaffected when C<not> is not followed by parentheses. =item Semantics of bareword prototype C<(*)> have changed.6, these preprocessor definitions are not available by default. You need to explicitly compile perl with C<-DPERL_POLLUTE> to get these definitions. For extensions still using the old symbols, this option can be specified via MakeMaker: perl Makefile.PL POLLUTE=1 =item C<PERL_IMPLICIT_CONTEXT> PERL_IMPLICIT_CONTEXT is automatically enabled whenever Perl is built with one of -Dusethreads, -Dusemultiplicity, or both. It is not intended to be enabled by users at this time. This new build option provides a set of macros for all API functions such that an implicit interpreter/thread context argument is passed to every API function. As a result of this, something like C<sv_setsv(foo,bar)> amounts to a macro invocation that actually translates to something like C<Perl_sv_setsv(my_perl,foo,bar)>. While this is generally expected to not have any significant source compatibility issues, the difference between a macro and a real function call will need to be considered. This means that there B L<perlguts/"The Perl API"> for detailed information on the ramifications of building Perl using this option. =item C<-DPERL_POLLUTE_MALLOC> to get the older behaviour. HIDEMYMALLOC and EMBEDMYMALLOC have no effect, since the behaviour they enabled is now the default. Note that these functions do B<not> constitute Perl's memory allocation API. See L<perlguts/"Memory Allocation"> for further information about that. =back =head2 Compatible C Source API Changes =over =item C<PATCHLEVEL> is now C<PERL_VERSION> The cpp macros C<PERL_REVISION>, C<PERL_VERSION>, and C<PERL_SUBVERSION> are now available by default from perl.h, and reflect the base revision, patchlevel, and subversion respectively. C<PERL_REVISION> had no prior equivalent, while C<PERL_VERSION> and C<PERL_SUBVERSION> were previously available as C<PATCHLEVEL> and C<SUBVERSION>. The new names cause less pollution of the B<cpp> namespace and reflect what the numbers have come to stand for in common practice. For compatibility, the old names are still supported when F<patchlevel.h> is explicitly included (as required before), so there is no source incompatibility from the change. =item Support for C++ exceptions change#3386, also needs perlguts documentation [TODO - Chip Salzenberg <chip@perlsupport.com>] =back =head2 Binary Incompatibilities L<perlapi>. =head1. See also L<"64-bit support">. =head2 Long Doubles Some platforms have "long doubles", floating point numbers of even larger range than ordinary "doubles". To enable using long doubles for Perl's scalars, use -Duselongdouble. =head2 -Dusemorebits You can enable both -Duse64bits and -Dlongdouble by -Dusemorebits. See also L<"64-bit support">. =head2 -Duselargefiles Some platforms support large files, files larger than two gigabytes. See L<"Large file support"> for more information. =head2. =head2 SOCKS support You can use "Configure -Dusesocks" which causes Perl to probe for the SOCKS (v5, not v4) proxy protocol library, =head2 C<-A> flag You can "post-edit" the Configure variables using the Configure C<-A> flag. The editing happens immediately after the platform specific hints files have been processed but before the actual configuration process starts. Run C<Configure -h> to find out the full C<-A> syntax. =head2. Perl 5.005_63 Windows, this feature is used to emulate fork() at the interpreter level. See L<perlfork>. macros USE_ITHREADS by default, which enables Perl source code changes that provide a clear separation between the op tree and the data it operates with. The former is considered B<independent> interpreters concurrently in different threads. -Dusethreads only provides the additional functionality of the perl_clone() API call and other support for running B<cloned> interpreters concurrently. >)] =head2 "our" declarations An "our" declaration introduces a value that can be best understood as a lexically scoped symbolic alias to a global variable in the package that was current where the variable was declared. This is mostly useful as an alternative to the C<vars> pragma, but also provides the opportunity to introduce typing and other attributes for such variables. See L<perlfunc/our>. =head2 Support for C<sprintf> and C<printf> support the Perl-specific format type C<%v> to print arbitrary strings as dotted tuples. printf "v%v", $^V; # prints current version, such as "v5.5.650" =head2 Weak references WARNING: This is an experimental feature. WeakRef package from CPAN, which contains additional documentation."); =head2 Some arrows may be omitted in calls through references Perl now allows the arrow to be omitted in many constructs involving subroutine calls through references. For example, C<$foo[10]->('foo')> may now be written C<$foo[10]('foo')>. This is rather similar to how the arrow may be omitted from C<$foo[10]->{'foo'}>. Note however, that the arrow is still required for C<foo(10)->('bar')>. =head2 exists() is supported on subroutine names The exists() builtin now works on subroutine names. A subroutine is considered to exist if it has been declared (even if implicitly). See L<perlfunc/exists> for examples. =head2. =head2 File and directory handles can be autovivified Similar to how constructs such as C<open(my $fh, ...)> and } [TODO - this idiom needs more pod penetration] =head2 64-bit support All platforms that have 64-bit integers either (a) natively as longs or ints (b) via special compiler flags (c) using long long are able to use "quads" (64-integers) as follows: =over 4 =item * constants (decimal, hexadecimal, octal, binary) in the code =item * arguments to oct() and hex() =item * arguments to print(), printf() and sprintf() (flag prefixes ll, L, q) =item * printed as such =item * pack() and unpack() "q" and "Q" formats =item * in basic arithmetics: + - * / % . =head2 Long doubles In some systems you may be able to use long doubles to enhance the range and precision of your double precision floating point numbers (that is, Perl's numbers). Use Configure -Duselongdouble to enable this support (if it is available). =head2 "more bits" You can "Configure -Dusemorebits" to turn on both the 64-bit support and the long double support. =head2 Enhanced support for sort() subroutines Perl subroutines with a prototype of C<($$)> and XSUBs in general can now be used as sort subroutines. In either case, the two elements to be compared are passed as normal parameters in @_. See L<perlfunc/sort>. For unprototyped sort subroutines, the historical behavior of passing the elements to be compared as the global variables $a and $b remains unchanged. =head2 L<perlop>. =head2 POSIX character class syntax [: :] supported For example to match alphabetic characters use /[[:alpha:]]/. See L<perlre> for details. =head2 Improved C<qw//> operator The C<qw//> operator is now evaluated at compile time into a true list instead of being replaced with a run time call to C<split()>. This removes the confusing misbehaviour of C<qw//> in scalar context, which had inherited that behaviour from split(). Thus: $foo = ($bar) = qw(a b c); print "$foo|$bar\n"; now correctly prints "3|a", instead of "2|a". =head2 pack() format 'Z' supported The new format type 'Z' is useful for packing and unpacking null-terminated strings. See L<perlfunc/"pack">. =head2 pack() format modifier '!' supported The new format type modifier '!' is useful for packing and unpacking native shorts, ints, and longs. See L<perlfunc/"pack">. =head2 pack() and unpack() support counted strings The template character '/' can be used to specify a counted string type to be packed or unpacked. See L<perlfunc/"pack">. =head2 Comments in pack() templates The '#' character in a template introduces a comment up to end of the line. This facilitates documentation of pack() templates. =head2 $^X variables may now have names longer than one character Formerly, $^X was synonymous with ${"\cX"}, but $^XY was a syntax error. Now variable names that begin with a control character may be arbitrarily long. However, for compatibility reasons, these variables I<must> be written with explicit braces, as C<${^XY}> for example. C<${^XYZ}> is synonymous with ${"\cXYZ"}. Variable names with more than one control character, such as C<${^XY^Z}>, are illegal. The old syntax has not changed. As before, `^X' may be either a literal control-X character or the two-character sequence `caret' plus `X'. When braces are omitted, the variable name stops after the control character. Thus C<"$^XYZ"> continues to be synonymous with C<$^X . "YZ"> as before. As before, lexical variables may not have names beginning with control characters. As before, variables whose names begin with a control character are always forced to be in package `main'. All such variables are reserved for future extensions, except those that begin with C<^_>, which may be used by user programs and are guaranteed not to acquire special meaning in any future version of Perl. =head2 C<use attrs> implicit in subroutine attributes Formerly, if you wanted to mark a subroutine as being a method call or as requiring an automatic lock() when it is entered, you had to declare that with a C<use attrs> pragma in the body of the subroutine. That can now be accomplished with declaration syntax, like this: sub mymethod : locked method ; ... sub mymethod : locked method { ... } sub othermethod :locked :method ; ... sub othermethod :locked :method { ... } (Note how only the first C<:> is mandatory, and whitespace surrounding the C<:> is optional.) F<AutoSplit.pm> and F<SelfLoader.pm> have been updated to keep the attributes with the stubs they provide. See L<attributes>. =head2>] =head2 C<require> and C<do> may be overridden C<require> and C<do 'file'> operations may be overridden locally by importing subroutines of the same name into the current package (or globally by importing them into the CORE::GLOBAL:: namespace). Overriding C<require> will also affect C<use>, provided the override is visible at compile-time. See L<perlsub/"Overriding Built-in Functions">. =head2 New variable $^C reflects C<-c> switch C<$^C> has a boolean value that reflects whether perl is being run in compile-only mode (i.e. via the C<-c> switch). Since BEGIN blocks are executed under such conditions, this variable enables perl code to determine whether actions that make sense only during normal running are warranted. See L<perlvar>. =head2 New variable $^V contains Perl version in v5.6.0 format C<$^V> contains the Perl version number as a version tuple that can be used in string or numeric comparisons. See C<Support for version tuples> for an example. =head2 Optional Y2K warnings If Perl is built with the cpp macro C<PERL_Y2KWARN> defined, it emits optional warnings when concatenating the number 19 with another number. This behavior must be specifically enabled when running Configure. See L<INSTALL> and L<README.Y2K>. =head1 Significant bug fixes =head2 E<lt>HANDLEE<gt> on empty files With C<$/> set to C<undef>, "slurping" an empty file returns a string of zero length (instead of C<undef>, as it used to) the first time the HANDLE is read after C<$/> is set to C<undef>. Further reads yield C<undef>. This means that the following will append "foo" to an empty file (it used to do nothing): perl -0777 -pi -e 's/^/foo/' empty_file The behaviour of: perl -pi -e 's/^/foo/' empty_file is unchanged (it continues to leave the file empty). =head2 C<eval '...'> improvements Line numbers (as reflected by caller() and most diagnostics) within C<eval '...'> were often incorrect when here documents were involved. This has been corrected. Lexical lookups for variables appearing in C<eval '...'> within functions that were themselves called within an C<eval '...'> were searching the wrong place for lexicals. The lexical search now correctly ends at the subroutine's block boundary. Parsing of here documents used to be flawed when they appeared as the replacement expression in C<eval 's/.../.../e'>. This has been fixed. =head2 All compilation errors are true errors Some "errors" encountered at compile time were by neccessity C<eval STRING>, and also allows such errors to be reliably trapped using __DIE__ hooks. =head2 Automatic flushing of output buffers fork(), exec(), system(), qx//, and pipe open()s now flush buffers of all files opened for output when the operation was attempted. This mostly eliminates confusing buffering mishaps suffered by users unaware of how Perl internally handles I/O. >&OLD")> now attempts to discard any data that was previously read and buffered in C<OLD> before duping the handle. On platforms where doing this is allowed, the next read operation on C<NEW> will return the same data as the corresponding operation on C<OLD>. Formerly, it would have returned the data from the start of the following disk block instead. =head2 eof() has the same old magic as <> C<eof()> would return true if no attempt to read from C<E<lt>E<gt>> had yet been made. C<eof()> has been changed to have a little magic of its own, it now opens the C<E<lt>E<gt>> files. =head2 system(), backticks and pipe open now reflect exec() failure $!. =head2. =head2 Pseudo-hashes work better Dereferencing some types of reference values in a pseudo-hash, such as L<perlref/"Pseudo-hashes: Using an array as a hash">. =head2 C<goto &sub> and AUTOLOAD The C<goto &sub> construct works correctly when C<&sub> happens to be autoloaded. =head2 C<-bareword> allowed under C<use integer> The autoquoting of barewords preceded by C<-> did not work in prior versions when the C<integer> pragma was enabled. This has been fixed. =head2 Boolean assignment operators are legal lvalues Constructs such as C<($a ||= 2) += 1> are now allowed. =head2 C<sort $coderef @foo> allowed sort() did not accept a subroutine reference as the comparison function in earlier versions. This is now permitted. =head2 Failures in DESTROY() When code in a destructor threw an exception, it went unnoticed in earlier versions of Perl, unless someone happened to be looking in $@ just after the point the destructor happened to run. Such failures are now visible as warnings when warnings are enabled. =head2 Locale bugs fixed. The warnings are gone. =head2 Memory leaks The C<eval 'return sub {...}'> construct could sometimes leak memory. This has been fixed. Operations that aren't filehandle constructors used to leak memory when used on invalid filehandles. This has been fixed. Constructs that modified C<@_> could fail to deallocate values in C<@_> and thus leak memory. This has been corrected. =head2 Spurious subroutine stubs after failed subroutine calls Perl could sometimes create empty subroutine stubs when a subroutine was not found in the package. Such cases stopped later method lookups from progressing into base packages. This has been corrected. =head2 Consistent numeric conversions change#3378,3318 [TODO - Ilya Zakharevich <ilya@math.ohio-state.edu>] =head2 Taint failures under C<-U> When running in unsafe mode, taint violations could sometimes cause silent failures. This has been fixed. =head2 END blocks and the C<-c> switch Prior versions used to run BEGIN B<and> END blocks when Perl was run in compile-only mode. Since this is typically not the expected behavior, END blocks are not executed anymore when the C<-c> switch is used. See L<CHECK blocks> for how to run things when the compile phase ends. =head2 Potential to leak DATA filehandles Using the C<__DATA__> token creates an implicit filehandle to the file that contains the token. It is the program's responsibility to close it when it is done reading from it. This caveat is now better explained in the documentation. See L<perldata>. =head2 Diagnostics follow STDERR Diagnostic output now goes to whichever file the C<STDERR> handle is pointing at, instead of always going to the underlying C runtime library's C<stderr>. =head2 Other fixes for better diagnostics. =head1 Performance enhancements =head2 Simple sort() using { $a <=> $b } and the like are optimized Many common sort() operations using a simple inlined block are now optimized for faster performance. =head2 Optimized assignments to lexical variables Certain operations in the RHS of assignment statements have been optimized to directly set the lexical variable on the LHS, eliminating redundant copying overheads. =head2. When given a pathname that consists only of a drivename, such as C<A:>, opendir() and stat() now use the current working directory for the drive rather than the drive root. The builtin XSUB functions in the Win32:: namespace are documented. See L<Win32>. $^X now contains the full path name of the running executable. A Win32::GetLongPathName() function is provided to complement Win32::GetFullPathName() and Win32::GetShortPathName(). See L<Win32>. POSIX::uname() is supported. system(1,...) now returns true process IDs rather than process handles. kill() accepts any real process id, rather than strictly return values from system(1,...).>. =item lib/io_const IO constants (SEEK_*, _IO*). =item lib/io_dir Directory-related IO methods (new, read, close, rewind, tied delete). =item lib/io_multihomed INET sockets with multi-homed hosts. =item lib/io_poll IO poll(). =item lib/io_unix UNIX sockets. =item op/attrs Regression tests for C<my ($x,@y,%z) : attrs> and <sub : attrs>. =item op/filetest File test operators. =item op/lex_assign Verify operations that access pad objects (lexicals and temporaries). =item op/exists_sub Verify C<exists &sub> operations. =back =head1 Modules and Pragmata =head2 Modules =over 4 =item attributes While used internally by Perl as a pragma, this module also provides a way to fetch subroutine and variable attributes. See L<attributes>. =item B The Perl Compiler suite has been extensively reworked for this release. [TODO - Vishal Bhatia <vishal@gol.com>, Nick Ing-Simmons <nick@ni-s.u-net.com>] =item ByteLoader The ByteLoader is a dedicated extension to generate and run Perl bytecode. See L<ByteLoader>. =item constant. See L<constant>. =item charnames change#4052 [TODO - Ilya Zakharevich <ilya@math.ohio-state.edu>] =item Data::Dumper A C<Maxdepth> setting can be specified to avoid venturing too deeply into deep data structures. See L<Data::Dumper>. Dumping C<qr//> objects works correctly. =item DB C<DB> is an experimental module that exposes a clean abstraction to Perl's debugging API. =item DB_File DB_File can now be built with Berkeley DB versions 1, 2 or 3. See C<ext/DB_File/Changes>. =item Devel::DProf Devel::DProf, a Perl source code profiler has been added. See L<Devel::DProf> and L<dprofpp>. =item Dumpvalue The Dumpvalue module provides screen dumps of Perl data. =item Benchmark Overall, Benchmark results exhibit lower average error and better timing accuracy. You can now run tests for I L<Benchmark>. =item. =item File::Compare A compare_text() function has been added, which allows custom comparison functions. See L<File::Compare>. =item File::Find C<follow> option is specified. Enabling the C<no_chdir> option will make File::Find skip changing the current directory when walking directories. The C<untaint> flag can be useful when running with taint checks enabled. See L<File::Find>. =item File::Glob This extension implements BSD-style file globbing. By default, it will also be used for the internal implementation of the glob() operator. See L<File::Glob>. =item. =item File::Spec::Functions The new File::Spec::Functions modules provides a function interface to the File::Spec module. Allows shorthand $fullname = catfile($dir1, $dir2, $file); instead of $fullname = File::Spec->catfile($dir1, $dir2, $file); =item Getopt::Long>. Note, however, that changing option starters is strongly deprecated. =item IO. L<Pod::Parser><gt>E<lt>> sequences) and B<Pod::Cache> (for caching information about pod files, e.g. link nodes). =item Pod::Select, podselect L<Pod::Select>. =item Pod::Usage, pod2usage L<Pod::Usage>. =item Pod::Text and Pod::Man [TODO - Russ Allbery <rra@stanford.edu>] =item. =item Sys::Syslog Sys::Syslog now uses XSUBs to access facilities from syslog.h so it no longer requires syslog.ph to exist. =item Time::Local The timelocal() and timegm() functions used to silently return bogus results when the date fell outside the machine's integer range. They now consistently croak() if the date falls in an unsupported range. =item Win32 The error return value in list context has been changed for all functions that return a list of values. Previously these functions returned a list with a single element C<undef> if an error occurred. Now these functions return the empty list in these situations. This applies to the following functions: Win32::FsType Win32::GetOSVersion The remaining functions are unchanged and continue to return C L<Win32>. =item L<perldbmfilter> for further information. =back =head2 Pragmata C<use attrs> is now obsolete, and is only provided for backward-compatibility. It's been replaced by the C<sub : attributes> syntax. See L<perlsub/"Subroutine Attributes"> and L<attributes>. C<use utf8> to enable UTF-8 and Unicode support. Lexical warnings pragma, C<use warnings;>, to control optional warnings. See L<perllexwarn>. C<use filetest> to control the behaviour of filetests (C<-r>. ). =item "my sub" not yet implemented (F) Lexically scoped subroutines are not yet implemented. Don't try that yet. =item "our" variable %s redeclared (W) You seem to have already declared the same global once before in the current lexical scope. =item '!' allowed only after types %s (F) The '!' is allowed in pack() and unpack() only after certain types. See L<perlfunc/pack>. =item / cannot take a count (F) You had an unpack template indicating a counted-length string, but you have also specified an explicit size for the string. See L<perlfunc/pack>. =item / must be followed by a, A or Z (F) You had an unpack template indicating a counted-length string, which must be followed by one of the letters a, A or Z to indicate what sort of string is to be unpacked. See L<perlfunc/pack>. =item / must be followed by a*, A* or Z* (F) You had a pack template indicating a counted-length string, Currently the only things that can have their length counted are a*, A* or Z*. See L<perlfunc/pack>. =item / must follow a numeric type (F) You had an unpack template that contained a '#', but this did not follow some numeric unpack specification. See L<perlfunc/pack>. =item /%s/: Unrecognized escape \\%c passed through ) You have used a pattern where Perl expected to find a string, as in the first argument to C<join>. Perl will treat the true or false result of matching the pattern against $_ as the string, which is probably not what you had in mind. =item %s() called too early to check prototype (W) L<perlsub>. =item %s argument is not a HASH or ARRAY element (F) The argument to exists() must be a hash or array element, such as: $foo{$bar} $ref->[12]->["susie"] =item "} =item %s argument is not a subroutine name (F) The argument to exists() for C<exists &sub> must be a subroutine name, and not a subroutine call. C<exists &sub()> will generate this error. =item L<attributes>. =item (in cleanup) %s (W) C<G_KEEPERR> flag could also result in this warning. See L<perlcall/G_KEEPERR>. =item <> should be quotes (F) You wrote C<require E<lt>fileE<gt>> when you should have written C<require 'file'>. =item Attempt to join self (F) You tried to join a thread from within itself, which is an impossible task. You may be joining the wrong thread, or you may need to move the join() to some other thread. =item Bad evalled substitution pattern (F) You've used the /e switch to evaluate the replacement for a substitution, but perl found a syntax error in the code to evaluate, most likely an unexpected right brace '}'. =item Bad realloc() ignored (S) An internal routine called realloc() on something that had never been malloc()ed in the first place. Mandatory, but can be disabled by setting environment variable C<PERL_BADFREE> to 1. =item) A warning peculiar to VMS. While Perl was preparing to iterate over %ENV, it encountered a logical name or symbol definition which was too long, so it was truncated to the string shown. =item Can't check filesystem of script "%s" (P) For some reason you can't check the filesystem of the script for nosuid. =item Can't declare class for non-scalar %s in "%s" (S) Currently, only scalar variables can declared with a specific class qualifier in a "my" or "our" declaration. The semantics may be extended for other types of variables in future. =item Can't declare %s in "%s" (F) Only scalar, array, and hash variables may be declared as "my" or "our" variables. They must have ordinary identifiers as names. =item Can't ignore signal CHLD, forcing to default (W). =item Can't modify non-lvalue subroutine call (F) Subroutines meant to be used in lvalue context should be declared as such, see L<perlsub/"Lvalue subroutines">. =item Can't read CRTL environ (S) A warning peculiar to VMS. Perl tried to read an element of %ENV from the CRTL's internal environment array and discovered the array was missing. You need to figure out where your CRTL misplaced its environ or define F<PERL_ENV_TABLES> (see L<perlvms>) so that environ is not searched. =item Can't remove %s: %s, skipping file (S) You requested an inplace edit without creating a backup file. Perl was unable to remove the original file to replace it with the modified file. The file was left unmodified. =item Can't return %s from lvalue subroutine (F) Perl detected an attempt to return illegal lvalues (such as temporary or readonly values) from a subroutine used as an lvalue. This is not allowed. =item Can't weaken a nonreference (F) You attempted to weaken something that was not a reference. Only references can be weakened. =item Character class [:%s:] unknown (F) The class in the character class [: :] syntax is unknown. See L<perlre>. =item Character class syntax [%s] belongs inside character classes (W) The character class constructs [: :], [= =], and [. .] go I<inside> character classes, the [] are part of the construct, for example: /[012[:alpha:]345]/. Note that [= =] and [. .] are not currently implemented; they are simply placeholders for future extensions. =item Constant is not %s reference (F) A constant value (perhaps declared using the C<use constant> pragma) is being dereferenced, but it amounts to the wrong type of reference. The message indicates the type of reference that was expected. This usually indicates a syntax error in dereferencing the constant value. See L<perlsub/"Constant Functions"> and L<constant>. =item constant(%s): %%^H is not localized (F) When setting compile-time-lexicalized hash %^H one should set the corresponding bit of $^H as well. =item constant(%s): %s (F) Compile-time-substitutions (such as overloaded constants and character names) were not correctly set up. =item defined(@array) is deprecated (D) defined() is not usually useful on arrays because it checks for an undefined I<scalar> value. If you want to see if the array is empty, just use C<if (@array) { # not empty }> for example. =item defined(%hash) is deprecated (D) defined() is not usually useful on hashes because it checks for an undefined I<scalar> value. If you want to see if the hash is empty, just use C<if (%hash) { # not empty }> for example. =item Did not produce a valid header See Server error. =item Did you mean "local" instead of "our"? (W) Remember that "our" does not localize the declared global variable. You have declared it again in the same lexical scope, which seems superfluous. =item Document contains no data See Server error. =item entering effective %s failed (F) While under the C<use filetest> pragma, switching the real and effective uids or gids failed. =item false [] range "%s" in regexp filehandle you're attempting to flock() got itself closed some time before now. Check your logic flow. flock() operates on filehandles. Are you attempting to call flock() on a dirhandle by the same name? =item Global symbol "%s" requires explicit package name (F) You've said "use strict vars", which indicates that all variables must either be lexically scoped (using "my"), declared beforehand using "our", or explicitly qualified to say which package the global variable is in (using "::"). =item Hexadecimal number > 0xffffffff non-portable . =item Illegal binary digit %s (F) You used a digit other than 0 or 1 in a binary number. =item Illegal binary digit %s ignored (W) You may have tried to use a digit other than 0 or 1 in a binary number. Interpretation of the binary number stopped before the offending digit. =item Illegal number of bits in vec (F) The number of bits in vec() (the third argument) must be a power of two from 1 to 32 (or 64, if your platform supports that). =item Integer overflow in %s number (W). =item Invalid %s attribute: %s The indicated attribute for a subroutine or variable was not recognized by Perl or by a user-supplied handler. See L<attributes>. =item Invalid %s attributes: %s The indicated attributes for a subroutine or variable were not recognized by Perl or by a user-supplied handler. See L<attributes>. =item invalid [] range "%s" in regexp The offending range is now explicitly displayed. =item Invalid separator character %s in attribute list (F) Something other than a colon or whitespace was seen between the elements of an attribute list. If the previous attribute had a parenthesised parameter list, perhaps that list was terminated too soon. See L<attributes>. =item Invalid separator character %s in subroutine attribute list (F) Something other than a colon or whitespace was seen between the elements of a subroutine attribute list. If the previous attribute had a parenthesised parameter list, perhaps that list was terminated too soon. =item leaving effective %s failed (F) While under the C<use filetest> pragma, switching the real and effective uids or gids failed. =item Lvalue subs returning %s not implemented yet (F) Due to limitations in the current implementation, array and hash values cannot be returned in subroutines used in lvalue context. See L<perlsub/"Lvalue subroutines">. =item Method %s not permitted See Server error. =item Missing %sbrace%s on \N{} (F) Wrong syntax of character name literal C<\N{charname}> within double-quotish context. =item Missing command in piped open (W) You used the C<open(FH, "| command")> or C<open(FH, "command |")> construction, but the command was missing or blank. =item Missing name in "my sub" (F) The reserved syntax for lexically scoped subroutines requires that they have a name with which they can be found. =item No %s specified for -%c (F) The indicated command line switch needs a mandatory argument, but you haven't specified one. =item No package name allowed for variable %s in "our" (F) Fully qualified variable names are not allowed in "our" declarations, because that doesn't make much sense under existing semantics. Such syntax is reserved for future extensions. =item No space allowed after -%c (F) The argument to the indicated command line switch must follow immediately after the switch, without intervening spaces. =item no UTC offset information; assuming local time is UTC (S) A warning peculiar to VMS. Perl was unable to find the local timezone offset, so it's assuming that local system time is equivalent to UTC. If it's not, define the logical name F<SYS$TIMEZONE_DIFFERENTIAL> to translate to the number of seconds which need to be added to UTC to get local time. =item Octal number > 037777777777 non-portable (W) The octal number you specified is larger than 2**32-1 (4294967295) and therefore non-portable between systems. See L<perlport> for more on portability concerns. See also L<perlport> for writing portable code. =item panic: del_backref (P) Failed an internal consistency check while trying to reset a weak reference. =item panic: kid popen errno read (F) forked child returned an incomprehensible message about its errno. =item panic: magic_killbackrefs (P) Failed an internal consistency check while trying to reset all weak references to an object. =item Parentheses missing around "%s" list . =item Premature end of script headers See Server error. =item Repeat count in pack overflows (F) You can't specify a repeat count so large that it overflows your signed integers. See L<perlfunc/pack>. =item Repeat count in unpack overflows (F) You can't specify a repeat count so large that it overflows your signed integers. See L<perlfunc/unpack>. =item realloc() of freed memory ignored (S) An internal routine called realloc() on something that had already been freed. =item Reference is already weak (W) You have attempted to weaken a reference that is already weak. Doing so has no effect. =item setpgrp can't take arguments (F) Your system has the setpgrp() from BSD 4.2, which takes no arguments, unlike POSIX setpgid(), which takes a process ID and process group ID. =item Strange *+?{} on zero-length expression (W) C</abc(?=(?:xyz){3})/>, not C</abc(?=xyz){3}/>. =item switching effective %s is not implemented (F) While under the C<use filetest> pragma, we cannot switch the real and effective uids or gids. =item This Perl can't reset CRTL environ elements (%s) =item This Perl can't set CRTL environ elements (%s=%s) (W) F<PERL_ENV_TABLES> (see L<perlvms>) so that the environ array isn't the target of the change to %ENV which produced the warning. =item Unknown open() mode '%s' (F) The second argument of 3-argument open() is not among the list of valid modes: C<E<lt>>, C<E<gt>>, C<E<gt>E<gt>>, C<+E<lt>>, C<+E<gt>>, C<+E<gt>E<gt>>, C<-|>, C<|E<45>>. =item. =item Unrecognized escape \\%c passed through (W) You used a backslash-character combination which is not recognized by Perl. The character was understood literally. =item L<attributes>. =item Unterminated attribute list (F) The lexer found something other than a simple identifier at the start of an attribute, and it wasn't a semicolon or the start of a block. Perhaps you terminated the parameter list of the previous attribute too soon. See L<attributes>. =item. =item. =item. =item Version number must be a constant number (P) The attempt to translate a C<use Module n.n LIST> statement into its equivalent C<BEGIN> block found an internal inconsistency with the version number. =back =head1 Obsolete Diagnostics =over 4 =item ":\]". =item Ill-formed logical name |%s| in prime_env_iter . =item regexp too big L<perl. =back =head1 BUGS If you find what you think is a bug, you might check the articles recently posted to the comp.lang.perl.misc newsgroup. There may also be information at, the Perl Home Page. If you believe you have an unreported bug, please run the B<perlbug> program included with your release. Make sure to trim your bug down to a tiny but sufficient test case. Your bug report, along with the output of C<perl -V>, will be sent off to perlbug@perl.com to be analysed by the Perl porting team. =head1 SEE ALSO The F<Changes> file for exhaustive details on what changed. The F<INSTALL> file for how to build Perl. The F<README> file for general stuff. The F<Artistic> and F<Copying> files for copyright information. =head1 HISTORY Written by Gurusamy Sarathy <F<gsar@activestate.com>>, with many contributions from The Perl Porters. Send omissions or corrections to <F<perlbug@perl.com>>. =cut
https://metacpan.org/changes/release/GSAR/perl5.5.650
CC-MAIN-2016-50
refinedweb
6,254
55.74
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo You can subscribe to this list here. Showing 2 results of 2 Alex Ott writes: > Today I found following problem with name completions for C++ code: > - I have a number of abbreviated namespace names, like 'namespace ba > = boost::asio;', 'namespace bs = boost::system;', etc. > - When I'm trying to complete name from one of these namespaces, then > I get only one completion that is equal to full namespace name, so > 'ba::<complete>' => 'ba::boost::asio::' (that's actually a error) > > I'm not sure, that I know enough internals of C++ name completions, > but maybe we need to detect that we have abbreviated namespace name, > and then lookup symbols in full namespace name? I actually remember that one from when I implemented the namespace aliasing und using thingies, but I was so fed up with implementing that stuff that I couldn't bring myself to fix it (just look into testusing.cpp to get an impression of what I had to deal with). I just hoped nobody would notice. ;-) Anyway, I just pushed something that should solve this. I'm not particularly happy with this fix. One could argue that this is a C++ specific problem, but I put it into the default code because I think it's still general enough. Also, I had to fix this in the context calculation because IMO doing this during completion will just make things harder. Just give it a shot and let me know if it works for you. -David > From: stephen_leake@... > To: cedet-semantic@... > Date: Tue, 23 Oct 2012 17:29:15 -0400 > Subject: Re: [cedet-semantic] Make with Windows_NT cmd.exe and other things > > vincent.belaiche@... (Vincent Belaïche) writes: > > > OK, I know that somebody is going to say "anyway you can build with > > cedet-build.el". But the discussion point is not just to build CEDET, > > but to build any project in a portably, and about this I am still in the > > opinion that if GNUMake had more shell-like builtins (to do things like > > cp, mkdir, rmdir, rm, and find ... -exec) that would make this easier. > > Gnu Make and Gnu Bash run everywhere you need them; that is the most > portable solution. > That was also my opinion, but you get into troubles when the makefile contains some command that do not understand the file path syntax of the bash port to MSWindows. This is where from I started: CEDET makefiles use emacs to byte-compile EMACS lisp code, if you use an MS-Windows port of emacs and the MSYS bash then you are in trouble when EMACS gets file path from MSYS GNU make. This can be circumvented by some tricks which I proposed. But when I did that I was replied to that this is not the correct way to proceed, and on MSWindows one should you mingw make, not msys make, and do with cmd.exe rather than bash. > -- > -- Stephe > Vincent.
http://sourceforge.net/p/cedet/mailman/cedet-semantic/?viewmonth=201210&viewday=24
CC-MAIN-2015-22
refinedweb
505
76.56
This is a small article which describes small code snippet which can be used to get access to the Html Form Control of an Aspx Page. Given below is code for a class by name BasePage. using using namespace { } _pageform = control This class is derived from the Page class of System.Web.UI.WebControls namespace. Here we are overiding the AddedControl method of the base class and verfying if the control being added is a HtmlForm control and if it is then we are assigning the control to the _pageform variable. Also the property PageForm allows us to access the Form Control from any class derived from the BasePage Class. Access a Form Control in Code Behind Attributes in C# Yes, I see the idea... But I bet it would have been easier to read the code if it was made a bit more readable... At least I prefere if the code is properly indented... And that "using" statements that are not used anyway, are removed, it make it easier to see what it is working with... And some comment (You know, lines starting with //) describing the thoughts behind the code, is nice to have...
http://www.c-sharpcorner.com/UploadFile/ChandraVedantham/AccessingHTMLFORM03142006085758AM/AccessingHTMLFORM.aspx
crawl-003
refinedweb
195
68.91
Security Updates: Fixed ReDoS vulnerability in the Autolink plugin. Issue summary: It was possible to execute a ReDoS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted URL-like text into the editor and press Enter or Space. Fixed ReDoS vulnerability in the Advanced Tab for Dialogs plugin. Issue summary: It was possible to execute a ReDoS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted text into the Styles dialog. An upgrade is highly recommended! New Features: - #2800: Unsupported image formats are now gracefully handled by the Paste from Word plugin on paste, additionally showing descriptive error messages. - #2800: Unsupported image formats are now gracefully handled by the Paste from LibreOffice plugin on paste, additionally showing descriptive error messages. - #3582: Introduced smart positioning of the Autocomplete panel used by the Mentions and Emoji plugins. The panel will now be additionally positioned related to the browser viewport to be always fully visible. - #4388: Added the option to remove an iframe created with the IFrame Dialog plugin from the sequential keyboard navigation using the tabindexattribute. Thanks to Timo Kirkkala! Fixed Issues: - #1134: [Safari] Fixed: Paste from Word does not embed images. - #2800: Fixed: No images are imported from Microsoft Word when the content is pasted via the Paste from Word plugin if there is at least one image of unsupported format. - #4379: [Edge] Fixed: Incorrect detection of the high contrast mode. - #4422: Fixed: Missing space between the button name and the keyboard shortcut inside the button label in the high contrast mode. - #2208: [IE] Fixed: The Autolink plugin duplicates the native browser implementation. - #1824: Fixed: The Autolink plugin should require the Link plugin. - #4253: Fixed: The Editor Placeholder plugin throws an error during the editor initialization with config.fullPageenabled when there is no <body>tag in the editor content. - #4372: Fixed: The Autogrow plugin changes the editor's width when used with an absolute config.widthvalue. API Changes: - #4358: Introduced the CKEDITOR.tools.colorclass which adds colors validation and methods for converting colors between various formats: named colors, HEX, RGB, RGBA, HSL and HSLA. - #3782: Moved the CKEDITOR.plugins.pastetools.filters.word.imagesfilters to the CKEDITOR.plugins.pastetools.filters.imagenamespace. - #4297: All CKEDITOR.plugins.pastetools.filtersare now available under the CKEDITOR.pasteToolsalias. - #4394: Introduced CKEDITOR.ajaxspecialized loading methods for loading binary ( CKEDITOR.ajax.loadBinary()) and text ( CKEDITOR.ajax.loadText()) data. Other Changes: - The WebSpellChecker (WSC) plugin is now disabled by default in Standard and Full presets. It can be enabled via extraPluginsconfiguration option. Security Updates: Fixed XSS vulnerability in the Color History feature reported by Mark Wade. Issue summary: It was possible to execute an XSS-type attack inside CKEditor 4 by persuading a victim to paste a specially crafted HTML code into the Color Button dialog. An upgrade is highly recommended! Fixed Issues: - #4293: Fixed: The CKEDITOR.inlineAll()method tries to initialize inline editor also on elements with an editor already attached to them. - #3961: Fixed: The Table Resize plugin prevents editing of merged cells. - #3649: Fixed: Applying a block format should remove existing block styles. - #4282: Fixed: The script loader does not execute callback for scripts already loaded when called for the second time. Thanks to Alexander Korotkevich! - #4273: Fixed: A memory leak in the CKEDITOR.domReady()method connected with not removing loadevent listeners. Thanks to rohit1! - #1330: Fixed: Incomplete CSS margin parsing if an autoor 0value is used. - #4286: Fixed: The Auto Grow plugin causes the editor width to be set to 0on editor resize. - #848: Fixed: Arabic text not being "bound" correctly when pasting. Thanks to Thomas Hunkapiller and J. Ivan Duarte Rodríguez! API Changes: - #3649: Added a new stylesRemoveeditor event. Other Changes: - #4262: Removed the global reference to the stylesLoadedvariable. Thanks to Levi Carter! - Updated the Export to PDF plugin to 1.0.1version: - Improved external CSS support for classic editor by handling exceptions and displaying convenient error messages. New features: - #3940: Introduced the colorNameproperty for customizing foreground and background styles in the Color Button plugin via the config.colorButton_foreStyleand config.colorButton_backStyleconfiguration options. - #3793: Introduced the Editor Placeholder plugin. - #1795: The colors picked from the Color Dialog are now stored in the Color Button palette and can be reused easily. - #3783: The colors used in the document are now displayed as a part of the Color Button palette. Fixed Issues: - #4060: Fixed: The content inside a widget nested editable is escaped twice. - #4183: [Safari] Fixed: Incorrect image dimensions when using the Easy Image plugin alongside the IFrame Editing Area plugin. - #3693: Fixed: Incorrect default values for several Color Button configuration variables in the API documentation. - #3795: Fixed: Setting the config.dataIndentationCharsconfiguration option to an empty string is ignored and replaced by a tab ( \t) character. Thanks to Thomas Grinderslev! - #4107: Fixed: Multiple Autocomplete instances cause keyboard navigation issues. - #4041: Fixed: The selection.scrollIntoViewmethod throws an error when the editor selection is not set. - #3361: Fixed: Loading multiple custom editor configurations is prone to a race condition between these. - #4007: Fixed: Screen readers do not announce the Rich Combo plugin is collapsed or expanded. - #4141: Fixed: The styles are incorrectly applied when there is a <select>element inside the editor. Fixed Issues: - #2607: Fixed: The Emoji plugin SVG icons file is not loaded in CORS context. - #3866: Fixed: The config.readOnlyconfiguration option not considered for startup read-only mode of inline editor. - #3931: [IE] Fixed: An error is thrown when pasting using the Paste button after accepting the browser Clipboard Access Prompt dialog. - #3938: Fixed: Cannot navigate the Autocomplete panel with the keyboard after switching to source mode. - #2823: [IE] Fixed: Cannot resize the last table column using the Table Resize plugin. - #909: Fixed: The Table Resize plugin does not work when the editor is placed in an absolutely positioned container. Thanks to Roland Petto! - #1959: Fixed: The Table Resize plugin does not work in a maximized editor when the Div Editing Area feature is enabled. Thanks to Roland Petto! - #3156: Fixed: Autolink config.autolink_urlRegexand config.autolink_emailRegexoptions are not customizable. Thanks to Sergiy Dobrovolsky! - #624: Fixed: Notification does not work with the bottom toolbar location. - #3000: Fixed: Auto Embed does not work with the bottom toolbar location. - #1883: Fixed: The editor.resize()method does not work with CSS units. - #3926: Fixed: Dragging and dropping a widget sometimes produces an error. - #4008: Fixed: Remove Format does not work with a collapsed selection. - #3998: Fixed: An error is thrown when switching to the source mode using a custom Ctrl + Enter keystroke with the Widget plugin present. Other Changes: - Updated WebSpellChecker (WSC) and SpellCheckAsYouType (SCAYT) plugins: - Fixed: Active Autocomplete panel causes active suggestions to be unnecessarily checked by the SCAYT spell checking mechanism. Security Updates: Fixed XSS vulnerability in the HTML data processor reported by Michał Bentkowski of Securitum. or (i) copy the specially crafted HTML code, prepared by the attacker and (ii) paste it into CKEditor in WYSIWYG mode. Fixed XSS vulnerability in the WebSpellChecker plugin reported by Pham Van Khanh from Viettel Cyber Security. Issue summary: It was possible to execute XSS using CKEditor after persuading the victim to: (i) switch CKEditor to source mode, then (ii) paste a specially crafted HTML code, prepared by the attacker, into the opened CKEditor source area, then (iii) switch back to WYSIWYG mode, and (iv) preview CKEditor content outside CKEditor editable area. An upgrade is highly recommended! New features: - #2374: Added support for pasting rich content from LibreOffice Writer with the Paste from LibreOffice plugin. - #2583: Changed emoji suggestion box to show the matched emoji name instead of an ID. - #3748: Improved the color button state to reflect the selected editor content colors. - #3661: Improved the Print plugin to respect styling rendered by the Preview plugin. - #3547: Active dialog tab now has the aria-selected="true"attribute. - #3441: Improved widget.getClipboardHtml()support for dragging and dropping multiple widgets. Fixed Issues: - #3587: [Edge, IE] Fixed: Widget with form input elements loses focus during typing. - #3705: [Safari] Fixed: Safari incorrectly removes blocks with the editor.extractSelectedHtml()method after selecting all content. - #1306: Fixed: The Font plugin creates nested HTML <span>tags when reapplying the same font multiple times. - #3498: Fixed: The editor throws an error during the copy operation when a widget is partially selected. - #2517: [Chrome, Firefox, Safari] Fixed: Inserting a new image when the selection partially covers an existing enhanced image widget throws an error. - #3007: [Chrome, Firefox, Safari] Fixed: Cannot modify the editor content once the selection is released over a widget. - #3698: Fixed: Cutting the selected text when a widget is partially selected merges paragraphs. API Changes: - #3387: Added the CKEDITOR.ui.richCombo.select() method. - #3727: Added new textColorand bgColorcommands that apply the selected color chosen by the Color Button plugin. - #3728: Added new fontand fontSizecommands that apply the selected font style chosen by the Font plugin. - #3842: Added the editor.getSelectedRanges()alias. - #3775: Widget mask and parts can now be refreshed dynamically via API calls.
https://ckeditor.com/cke4/release-notes
CC-MAIN-2021-17
refinedweb
1,487
50.43
view raw I recently started learning ruby and i am confused between instance variable and local variable and class variable. so , i recently written code which will find the largest palindrome in 1000 prime numbers. code is: def prime_large(number) arr_prime = [] Prime.each(number) do |x| new_arr_prime = arr_prime.push(x.to_s) updated = new_arr_prime.select { |y| y.reverse == y } end p updated.max end p prime_large(1000) undefined local variable or method `updated' for main:Object (NameError) def prime_large(number) arr_prime = [] Prime.each(number) do |x| new_arr_prime = arr_prime.push(x.to_s) @updated = new_arr_prime.select { |y| y.reverse == y } end p @updated.max end p prime_large(1000) "929" "929" In your first example you created a local variable updated, that is only accessible within the scope of the block it is defined in. Meaning, it is available only within Prime.each(number) do end block. In your second example you created instance variable @updated. without creating a class how my instance variable ( @updated) is working It is because in Ruby everything occurs in the context of some object. Even though you did not created a class, you are being in the top-level context, in the context of object main. Thus, any instance variables defined within top-level are instance variables of this object main. So going back to your issue, to overcome it you'll want to just define the updated local variable outside the Prime.each(number) do end block: def prime_large(number) arr_prime = [] updated = nil # initialize local varialbe Prime.each(number) do |x| new_arr_prime = arr_prime.push(x.to_s) updated = new_arr_prime.select { |y| y.reverse == y } # assign new value end p updated.max end p prime_large(1000) To test it you can open irb or pry and check it yourself: self # the object in the context of which you are currently #=> main self.class # main is an instance of class Object, any methods defined # within main are added to Object class as instance methods #=> Object instance_variables # list of it's instance variables, none yet created #=> [] @variable = 1 # create and instance variable #=> 1 instance_variables # now created variable occurs in the list of current object's instance variables #=> [:@variable] def hello; :hello end # define method #=> :hello self.class.public_instance_methods(false) # list instance methods defined in Object #=> [:hello] What you now want to read about is lexical scopes in Ruby.
https://codedump.io/share/kAv0OYvzXoLq/1/confused-between-instance-variable-and-local-variable
CC-MAIN-2017-22
refinedweb
387
58.99
I recently started programming in PHP using the well-known Symfony framework. I wanted to keep my VS Code habits and proficiency I had from my previous projects in Node.js and Vue.js, so I tried to configure VS Code for PHP development as well. Moreover, I didn't want to invest €199 in the famous PHPStorm IDE… 😕 In this article, I will explain how I managed to make my development environment comparable to PhpStorm's. The commands will be detailed for Ubuntu 18.04, but they can be adapted for Mac OS and possibly for Windows. I will take an empty Symfony application as an example for this article. Let's start! To be able to run PHP code you obviously need to install PHP. You will also probably need Composer, a commonly used dependency manager for PHP. You can install them by running the following command: sudo apt install php-cli composer You can install php-all-dev instead of php-cli if you want to install some useful libraries as well. Let's now create an empty Symfony app. Then open VS Code and launch the development server: composer create-project symfony/website-skeleton my-symfony-website cd my-symfony-website code . bin/console server:run VS Code needs to watch for file changes to work correctly. That's why the following warning may appear because our Symfony project contains a lot of files: To fix it, you can run the following commands in your terminal, and then restart VS Code: echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf sudo sysctl -p Go to from your favorite web browser and check that your Symfony website works. Let's create a new route in our application. Just add an empty file HelloWorldController.php in the src/Controller folder. By default, VS Code provides some basic code suggestions but they are generic and quite useless. To get useful code suggestions as you type, I recommend installing the PHP Intelephense extension for VS Code. I also tried the PHP Intellisense extension but it's slower on big projects and provides fewer features (it doesn't gray out unused imports for example). Now that the PHP Intelephense extension is installed, we can start writing our HelloWorldController! As you can see, code suggestions are very relevant and VS Code auto imports the corresponding namespace when you validate a suggestion! PHP Intelephense can also auto-suggest relevant methods when typing $myVar->. The problem is that these suggestions are polluted by the default PHP suggestions. Basic PHP code suggestions we want to disable To fix that, you can disable these basic suggestions in VS Code settings. Simply open VS Code's settings.json file (press Ctrl + , then click on the top right {} icon) and add the following line: "php.suggest.basic": false, When it's done, you can see useful suggestions! Relevant suggestions when basic suggestions are disabled When you write PHP code, a good practice is to add PHPDoc annotations to make your code more understandable and to help your IDE provide you with relevant code suggestions. By default, VS Code doesn't suggest anything while writing annotations. To activate code suggestions in comments, open the settings.json file and add the following line: "editor.quickSuggestions": { "comments": true }, Code suggestions in annotations By default, PHP Intelephense excludes Symfony test folders from indexing because the default exclude settings contains a too generic pattern: "intelephense.files.exclude": [ "**/.git/**", "**/.svn/**", "**/.hg/**", "**/CVS/**", "**/.DS_Store/**", "**/node_modules/**", "**/bower_components/**", "**/vendor/**/{Test,test,Tests,tests}/**" ], To enable suggestions for Symfony test classes, all you need to do is edit your settings.json file and add: "intelephense.files.exclude": [ "**/.git/**", "**/.svn/**", "**/.hg/**", "**/CVS/**", "**/.DS_Store/**", "**/node_modules/**", "**/bower_components/**", "**/vendor/**/{Test,test,Tests,tests}/**/*Test.php" ], As you can see, the last line is more specific than in the default settings. The result 😉: Code completion enabled for tests When you want to get more information about a function, you can Ctrl+Click on it and VS Code will open the line where the function is declared! If you want VS Code to generate getters and setters for you, you can install this extension. Then, right-click on a class property and select Insert PHP Getter & Setter. Generate getter and setter Debugging your PHP code can be painful without a debugger. You can use dump($myVar); die(); (😕) but it's not very convenient... The best way to debug your PHP code is to use Xdebug, a profiler and debugger tool for PHP. Xdebug is not shipped with PHP, you need to install it on your development environment: sudo apt install php-xdebug Then run sudo nano /etc/php/7.2/mods-available/xdebug.ini and add the following lines: xdebug.remote_enable = 1 xdebug.remote_autostart = 1 Tip! If your PHP project runs in a Docker container, you need also to add the following line to the xdebug.ini file, where 172.17.0.1 is the IP address of the docker0 interface on your computer (on Mac OS you have to put host.docker.internal instead): xdebug.remote_host = 172.17.0.1 Check that Xdebug is successfully installed by running php -v. You should get something like: with Xdebug v2.6.0, Copyright (c) 2002-2018, by Derick Rethans To be able to use Xdebug in VS Code, you need to install the PHP debug extension. Then go to the debug tab in VS Code (accessible in the side menu) and click on Add configuration. Select PHP, and close the newly created launch.json file: Configure VS Code debugger to listen for Xdebug Tip! If your PHP project runs in a Docker container, you need to add the following path mapping to the launch.json file in the Listen for Xdebug section: "name": "Listen for XDebug", ... "port": 9000, "pathMappings": { "/path/to/app/in/docker": "${workspaceFolder}" }, Your debugging environment is now ready! 🕷🚀 Let's debug our HelloWorldController.php to see which are the query parameters given by the user. You can use the following code for example: <?php namespace App\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class HelloWorldController { /** * @Route("/hello") */ public function getHelloWorld(Request $request) { $name = $request->get('name'); return new Response('Hello '.$name.'!'); } } Press F5 in VS Code to start the debugging session. Uncheck the _Everything _option in the breakpoints list and put a breakpoint at line 18 by clicking left of the line number. Then go to. You can now see the value of local variables by hovering the mouse pointer over them: Request to paused in debugger You can do a lot of amazing things with the debugger 😃, like: For more information about the power of VS Code debugger, you can visit the official website. When you encounter an error, or when you use the Symfony debug toolbar or the profiler, you may want to open the desired file directly in your IDE with the cursor at the corresponding line. To be able to do that, you need to add the following line to your /etc/php/7.2/mods-available/xdebug.ini: xdebug.file_link_format = vscode://file/%f:%l Tip! If you run PHP in a Docker container, you can specify a path mapping between your host and your docker like this: xdebug.file_link_format = 'vscode://file/%f:%l&/path/to/app/in/docker/>/path/to/app/on/host/' Now, when an error occurs, you can click on it and go directly to the corresponding line in VS Code: When you visit a route, you can also jump to the corresponding controller by clicking on the debugging toolbar: Formatting and linting your code is a very good practice to keep it clean automatically, and to inform you about some errors. The best and commonly used linter for PHP is PHP CS Fixer. It provides a large number of rules to keep your code clean. You can visit this website for more information about the rules and the categories they belong to. To be able to auto-format your PHP files in VS Code, you need to install the php cs fixer extension. The most complete and safe category of rules is @PhpCsFixer. It's a good point to start. To enable this set of rules in VS Code, open settings.json and add the following line: "php-cs-fixer.rules": "@PhpCsFixer", To auto-format your PHP files on save, you also need to add the following lines to your settings.json: "[php]": { "editor.defaultFormatter": "junstyle.php-cs-fixer", "editor.formatOnSave": true }, Auto-format on save with PHP CS Fixer If you want to disable or enable some specific linting rules, you can do it in a .php_cs file at the root folder of your project. If this configuration file is present, VS Code takes it into account and overrides the configuration found in settings.json. You can find more information about the .php_cs file in the GitHub repository. A simple config file to use @PhpCsFixer category and disable some rules could be: <?php return PhpCsFixer\Config::create() ->setRules([ '@PhpCsFixer' => true, 'php_unit_internal_class' => false, 'php_unit_test_class_requires_covers' => false, ]) ; Prettier for PHP is a code formatter which makes some improvements that PHP CS Fixer does not do. It allows you, among other things, to configure a max line length and makes your code even cleaner. To add Prettier for PHP to your PHP CS Fixer configuration, you can follow these instructions. Depending on your computer's speed, the length of your files and the number of rules you activate, linting a file on save can be slow, causing VS Code to refuse it. To fix this behavior, change the formatOnSaveTimeout in your settings.json: "editor.formatOnSaveTimeout": 5000, To activate syntax highlighting for Twig files in VS Code, you need to install the Twig Language 2 extension. To enable emmet suggestions like in HTML files, add the following line to your settings.json: "emmet.includeLanguages": { "twig": "html" }, A good VS Code extension to manage your databases is SQLTools. Feel free to install it and manage your databases directly from your IDE! Enjoy coding in PHP with VS Code 🚀 and feel free to give me your feedback! 😉 Want to learn more about how Theodo can help bring your Symfony project to the next level? Learn more about our team of Symfony experts. Web Developer at Theodo
https://blog.theodo.com/2019/07/vscode-php-development/
CC-MAIN-2021-17
refinedweb
1,718
56.35
This is your resource to discuss support topics with your peers, and learn from each other. 03-19-2010 12:13 AM - edited 03-19-2010 12:18 AM hello I want to remove bottom panel (in red) from application screen. It appears when I extend MainScreen. How I can do it? Also I have complex layout on my screen and scrolling works incorrecly (it always scroll to the top of the screen) when I press any button on this panel. Solved! Go to Solution. 03-19-2010 04:29 PM What BlackBerry device software version are you testing on? You can find this under Options, About on the BlackBerry Smartphone. Can you provide some sample code for your custom MainScreen? 03-22-2010 12:15 AM Ok, simple example: import net.rim.device.api.ui.component.ButtonField; import net.rim.device.api.ui.container.MainScreen; /** * */ public class TestScreen extends MainScreen { public TestScreen() { super(); for (int i = 0; i < 20; i++) { add(new ButtonField("Btn " + i)); } } } When I use this code bottom panel appeared and I couldn't remove it. Also its behaviour is strange. I use 4.7. And simulator 9530. 03-22-2010 06:58 AM Does this happen on the device as well or only the simulator? I have never seen this happen before, often you need to add your own toolbar for something like that. 03-22-2010 08:16 AM This is a known issue on the 4.7 9530 simulator. The system toolbar will not show up on the device. 03-22-2010 11:34 PM I'd tried it only on the simulator. If it doesn't show up on the real device - it's great. thanks
https://supportforums.blackberry.com/t5/Java-Development/Removing-bottom-panel-from-application-touch-screen-devices/m-p/468172
CC-MAIN-2016-44
refinedweb
284
77.23
I want to print a number using the program below but it never prints it correctly and i can't find the problem, can you help me? #include <stdio.h> int main(){ int value=3; int mask=0x80000000; int byte=0; int bit=0; for(byte=0; byte<4; byte++){ for(bit=0; bit<8; bit++){ if(value&mask==1) printf("1"); else printf("0"); mask>>=1; } printf(" "); } printf("\n"); return 0; } There are other problems with your code, but the main one is your if statement. if (value & mask == 1) There are two problems: == hash higher precedence than &, so this is parsed as if you'd written value & (mask == 1). But you want to do the masking first, then the comparison, so you have to write (value & mask) == 1. When you do the masking, you won't usually get 1. When the masked bit is set, you'll get a number with 1 in that bit, not the lowest bit. Instead of using == 1, use != 0 to see if the bit is set. You could also use (value & mask) == mask. When you change that line to: if ((value & mask) != 0) it will generally work. However, your code has implementation-defined behavior because you're doing bit operations on signed integer variables. On a 32-bit system, 0x80000000 overflows the maximum value of int, and doing shifts of signed numbers is implementation-defined. Change value and mask to unsigned int and everything should be fine.
https://codedump.io/share/zDZU1nHC9bVu/1/why-can39t-i-print-the-number-in-binary-properly
CC-MAIN-2017-17
refinedweb
245
72.56
Hi I am trying to write a java program that lets me evaluate the value of x over the range x=0 to100, for the function y=a*(x*8))+b*((x*8)^-0.5))+c and then print the values of y into a file. However the attempt I made below does not work can someone help me out and show me where I am going wrong and what to do to make the code work. Code Java: public class javatest { public static void main(String[] args) { // Stream to write file FileOutputStream fout; try { // Open an output stream fout = new FileOutputStream ("output.txt"); double a = 5; double b = 10; double c = 15; double y; double x; y=(a*(x*8))((b)*Math.pow((x*8)),-0.5)+c; // for x returns y for 100 channels. for (x=0; x < 100; x+) { System.out.println( "The value of y is " y; // Print a line of text new PrintStream(fout).println (" The value of y is" y; // Close our output stream fout.close(); } } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/4674-help-need-math-java-program-printingthethread.html
CC-MAIN-2014-35
refinedweb
172
72.26
Jersey Module Reference Jersey. Our recommended approach to REST APIs is using RAML and exposing APIs through the API Manager. Jersey might still in some cases be the path of minimum resistance for when the API you want to expose was built in Java and lacks a RAML file that describes how to interface to it. In addition to the annotation capabilities, Jersey contains many useful features: Writing a Service Writing JAX-RS services is an expansive topic and is not covered in this guide. However, the Jersey website has an excellent set of samples, and the JAX-RS specification is helpful as well. This guide takes a look at a simple hello world service. This example requires the installation of Apache Xalan JARs. The first step to create a JAX-RS service is to create a class which represents your HTTP resource. In our case we create a "HelloWorldResource" class. Methods in this class are called in response to GET, POST, DELETE, and: @POST specifies that this method is only called on @POST requests to the URL. @Produces specifies that this method is producing a resource with a mime type of "text/plain". @Path binds this method to the URL "/helloworld/{name}". The {name} is a URI template. Anything in this portion of the URL maps After you run this configuration in Mule, use the following URL. You should see this response in your browser: 'Hello Dan': Exception Mappers It is possible to register exception mappers inside the resources element. Exception mappers allow mapping generic exceptions that may be thrown in the component class to HTTP response codes, you can add as many of these as you want. The following configuration maps a HelloWorldException that may be thrown during the execution of HelloWorldResource to HTTP error 503 (Service Unavailable): HelloWorldExceptionMapper.java Context Resolvers Context resolvers are injected into resource classes, and they provide context information to them, which can be useful in certain cases when you need specific metadata that is not available by default. When you use JAXB for your XML/JSON serialization, JAXB provides some annotations in case you would need to change the output format.ization,: {"name":"Alan","age":"26"} With the custom context resolver, the output changes to the following: {"name":"Alan","age":26}. Sending a Jersey Response to Other Flows You can use interface bindings to invoke completely separate Mule flows from your Jersey resource. Java Class To test, browse to. The result is: Hello World! by virtue of the Set Payload from the XML Configuration: Adding Custom Properties You can execute resources passing your own set of server properties. For example, the following configuration specifies its very own set of language mappings: Extension Autodiscovery Jersey owns a very extensible Java API that allows developers to modify almost every aspect of its inner working. Because Jersey provides so many extension points, these are exposed in Mule through auto discovery capabilities. Per Jersey’s own API, every class that you annotate with the @Provider annotation can be used as an extension point. A list of Java packages that contain this annotation and exist in the Mule namespace is shown, every discovered class automatically registers in the resource’s context. Here’s an example of how to register your own JAXB body writers and readers for an hypothetical Person class: Here, the packages com.my.project.jersey.readers and com.my.project.jersey.writers are being scanned and, for example, the following providers would be discovered:
https://docs.mulesoft.com/mule-user-guide/v/3.9/jersey-module-reference
CC-MAIN-2018-09
refinedweb
580
53.31
# Breadth/Depth First Search A graph is a kind of data structure that includes a set of vertices and edges. Graph traversing means a visit to each vertex of the graph precisely. The graph traversing is used to determine the order in which vertices are being visited throughout the search process. A graph traversing searches for the edges that will be used in the search operation without establishing loops. This means that using graph traversal, we will go to all the vertices of the graph without going into a looping path. There are two kinds of graph traversal methods. * Breadth-First Search * Depth First Search **Breadth-First Search (BFS)** Breadth-first search is also called a level order traversal. Breadth-first search is an algorithm to traverse the graph level by level. In the traversing process, we have to visit all vertices and edges. In this, we can take any node as a root node during traversal starting. For BFS, a queue data structure would be used that follows FIFO(First In First Out) principle. We visit nodes level wise. First, we complete the top level and then move on to lower levels. In breadth-first search, we identify the levels in the graph and then we visit or traverse all the vertices. Breadth-first search is level by level exploration of the graph. **Implementation of Breadth-First Search** The implementation of breadth-first search involves the following steps: * We take input as a graph to traverse it. * For all edges incident on that vertex, we are going to check to see whether it is undiscovered or not. If it is an undiscovered edge, we check the vertex follows the undiscovered edge. If that vertex is visited, we mark the edge as a cross edge. If that vertex is not visited then we mark the edge as a discovered edge. We visit that vertex and add that vertex to the next level. Once none of the vertex incidents on the vertex is undiscovered, we start to explore the next vertex. **Example** Let us consider a graph shown below to traverse. At the beginning of the breadth-first search, all the vertices are going to be unvisited and all the edges are going to be undiscovered. So, we will symbolize the unvisited vertex by ( O ) and the undiscovered edge by ( / ). ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/6e3/d82/4a2/6e3d824a237426ac365ef3643270026e.jpeg)Now we select an arbitrary vertex (A ) as a starting vertex and visit it. Then we set its level as 'Lo'. At zero level (Lo), we have one vertex (A). ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/1dc/258/d4b/1dc258d4b204d9e555bc0033b3f2ca38.jpeg)For all vertices in level zero, we will go to each undiscovered edge. Every undiscovered edge follows with another vertex. For the vertex that follows is unvisited, then we will visit that vertex and add it to the next level. And if that vertex is visited then we will set the edge to be a cross edge. Now we go to the first undiscovered edge 'B' and make it discover edge from the discovered vertex 'A'. Discovery edge is represented by black dotted lines. Similarly, we visit undiscover edges C and D and make them discovered edges.  Also, we add B, C and D edges to level 1 (L1). ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/1cf/003/b48/1cf003b4855caab7c26854e0bc836f82.jpeg)Now there are no more edges to traverse for Lo. So, we can go to the next level L1. Now we will go through each vertex of L1. At vertex B, we go to each of the undiscovered edges. From vertex B, we will reach vertex C which has already been visited. So now we will set edge C as a cross edge. The cross edge is represented by the blue line. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/4a1/676/c63/4a1676c63e1799a181cf1741f1dcd3c2.jpeg)Now, we go to undiscovered edge E from vertex B.E is the unvisited vertex. So we visit the vertex E and discover the edge. Then E has added to Level 2 ( L2 ) and comes back to B. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/691/d96/48a/691d9648a6653006484a4f73cfab59c0.jpeg)Then we go to vertex C where there are three undiscovered edges( E, F and D ). As E is already visited, so we make it cross edge with a blue line. Now we will go to vertex F that is unvisited, so we make this edge a discovery edge. Now we go to edge D that is already visited, so we make it cross edge. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/c97/981/1fc/c979811fce5e1d4d32ab90bba6033636.jpg)Now D has left one undiscovered edge F. It can be observed that F has been already visited so it will become cross-edged with D. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/c9d/3c7/c63/c9d3c7c63efcbbf540bdd658875d5401.jpg)Next, we go to level L2 that contains E and F vertices. On E, there are no undiscovered vertices. Now we go to F where there are also no undiscovered vertices. So now level L2 will also complete. So, now traversing has been completed. And the breadth-first search has been done. **Pseudocode** Let us consider Graph 'A' as input and called our algorithm BS. Firstly, we will define all vertices are unvisited and all edges are undiscovered. ``` BS(A){ for all v A.vertices{ setlabel( v , UV ) } for all e A.vertices{ setlabel( e , UD ) } for B A.vertices{ list.addEnd(B); setlabel(B,V); } while ( list.Notempty( ) ){ v = list.removeFront( ); } for e A.incident on v{ if ( e.label == UD ){ q = adjvertex(v,e); } if ( q.label = V ){ setlablel( e, cross); } if ( q.label == UV ){ setlablel( e, D); setlabel( q , V ); list.addEnd(q); } } } ``` **Time Complexity of Breadth-First Search** Its time complexity is  *b^x* Where b represents the branching factor and x is level. **Space Complexity of Breadth-First Search** Its space complexity is : *b^x* Where b represents the branching factor and x is level. **Advantages of Breadth-First Search** It has the following advantages: * BFS will not get trapped exploring visually impaired search. * If there are several solutions, then it will give a cost-efficient solution because a longer route is never investigated until all shorter paths are already available. * With this search method, we can find the final solution without examining very much of the search room at all. **Disadvantages of Breadth-First Search** It has the following disadvantages: * The amount of time required to produce all the nodes is to be taken into consideration because of time complexity. * It uses plenty of memory space. **Applications of Breadth-First Search** It has the following applications: * It is used to find the shortest path in the undirected graph. * It is used in cycle detection. * It is used in the bipartite check. * It is used in social networking websites and GPS navigation. **Depth First Search (DFS)** It is a way to traverse the graph. In this, we visit all the vertices and edges and traverse the graph. In depth-first search, the stack data structure is used that follows the LIFO( Last In and First Out) principle. Depth-first search produces a non-optimal solution. In depth-first search, we keep on exploring or visiting vertices till we reach a dead-end where there are no more edges to traverse from that vertex and then we backtrack. **Implementation of Depth First Search** Implementation of depth-first search involves following major steps: * Firstly select an arbitrary vertex and make it the current vertex by visiting it. * Then look for undiscovered edges corresponding to the current vertex. * On finding the undiscovered edge, we see whether the vertex that follows is an unvisited vertex or not. * If it is an unvisited vertex, we set a discovery edge and then go to that vertex. * If it is a visited vertex, we set it as a back edge. * If there is no undiscovered edge found, we must backtrack. **Example** Let us consider the graph shown below. Initially, all the vertices are unvisited, and all edges are undiscovered. In this graph, we have represented an unvisited vertex by a circle and undiscovered edge by a single line. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/c18/63f/355/c1863f355bd7d187496919d7c21e2ab1.jpg)Firstly, we choose an arbitrary vertex A and visit it. The visited vertex is represented by a green circle while the current vertex by a red circle. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/65f/e3f/1d1/65fe3f1d1c46c9d0c2af44423c1435b7.jpg)Now we look for corresponding edges of vertex A. Vertex A has four undiscovered edges B, D, C and E. From the current vertex A, we will take B as an undiscovered edge and visit it. Then we will set the edge traversed to discovered. Then B will become the current vertex after visiting it. And edge between A and B will become discovered edge that is represented by a dotted line. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/a9b/ac4/dcb/a9bac4dcbc68edd652b7e74d49fc3ec3.jpg)Now from current vertex B, there is one undiscovered edge C. So we will visit C and discovered it. Then C will become the current vertex. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/ccc/64e/7f6/ccc64e7f6c8457f76da9741a077faad1.jpeg)Now, we will look for undiscovered edges from current vertex C. If we consider a discovered edge from C to A, it can be seen that an undiscovered edge is leading to an already visited vertex. If the vertex that follows the undiscovered edge is visited, then mark the edge as the back edge. And back edges are represented by a blue colour line. So, the edge between A and C will become a back edge. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/bad/957/4d5/bad9574d5f4f8a0b4f9bd340626d19e0.jpg)From current vertex C, we move on to visit undiscovered edge D and make it visited. Now D will become the current vertex. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/c58/893/fa6/c58893fa6b993bdad6ff4de14dae1c38.jpg)From D, there is one undiscovered edge A, but it reaches the visited vertex. So we will convert this edge into a back edge. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/27a/372/4aa/27a3724aae10c17cafb37f35fa2e2d35.jpg)Now from current vertex D, there is left no undiscovered edge. So in such a case, we will set current vertex C which is the parent vertex of D. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/2b3/d1d/7dc/2b3d1d7dc0e1a2c1679ae53e71b524ea.jpg)From current vertex C, we have one undiscovered edge E. So we will visit vertex E and it will become the current vertex. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/596/de2/1c3/596de21c37fc1e04fad075c736a8aa9c.jpg)Now from vertex E, there is one undiscovered edge A. As vertex A has been already visited. So edge between E and A will become a back edge. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/925/277/726/9252777266ddd1b0ef31997632c598a4.jpg)Now we will backtrack from E to C because E has left no undiscovered edges. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/f45/148/4b8/f451484b861f214f701761b8927778ff.jpg)Now we will backtrack from C to B because C has left no undiscovered edge. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/769/3dc/f0c/7693dcf0c9a93386b8a15d0469694dfb.jpg)Now B has left with undiscovered edges so we will backtrack from B to A. Now all the vertices have been visited. And traversing has been completed. ![](https://habrastorage.org/r/w780q1/getpro/habr/upload_files/92d/eaa/590/92deaa5905152b64c81050ea0ae6d49f.jpg)**Pseudocode** Let us consider Graph 'A' as input and called our algorithm DS. Firstly, we will define all vertices are unvisited and all edges are undiscovered. ``` DS(A){ for v A.vertices{ setlabel ( v, UN ); } for e A.edges{ setlabel ( e, UD ); } for v A.vertices{ visit( v, A) ; } setlabel ( v , V ); for e v.incidentEdges{ if(e.label == UD){ q = adjacentVertex ( v, e ); } if(q.label == UV){ setlabel(e, D); visit( q, A); } if(q.label == V){ setlabel(e, B); } } } ``` **Time Complexity of Depth First Search** Its time complexity is  *O(n^x)* Where n represents the number of nodes at level x. **Space Complexity of Depth First Search** Its space complexity is *O(n\*x)* Where n represents the number of nodes at level x. **Advantages of Depth First Search** It has the following advantages: * It needs less amount of memory because just the nodes on the current path will be stored. * With this search method, we can find the final solution without investigating very much of the search space at all. **Disadvantages of Depth First Search** It has the following disadvantages: * DFS cannot find many a satisfactory solution if they exist. * Cut of depth, we have to define otherwise DFS goes in an infinite loop. **Applications of Depth First Search** It has the following applications: * It is used to find a minimum spanning tree. * It is used in cycle detection. * It is used in the bipartite check. * Also used to check the path between two nodes.
https://habr.com/ru/post/558806/
null
null
2,179
58.58
In a Grails project I have a command object to validate submitted forms. This command obj. also has custom validators. The data is submitted with jQuery ajax ($.post). My question is how can I now map the data send with jQuery Ajax to the properties listed in the Command object? For example: $.post('comment/save', {id: id, title: title}); and then in the controller: def save(saveCommand cmd){ if (!cmd.validate()){ ... } } class saveCommand { Comment comment_id // maps to: params.comment_id send with ajax String title // maps to: params.title send with ajax // constraints // validators } The comment_id attribute should be bound from a "comment_id" parameter in the parameter map you sent from jQuery, not as "id" as you have right now. Anyway, I guess you have a Comment domain class, and you expect to bind this entity from database. In this case, you should add a ".id" suffix to your parameter name. $.post('comment/save', {"comment_id.id": id, "title": title}); PS: maybe you want to rename the "comment_id" to "comment" in your command class. Doing that, you will have to change the parameter name in your ajax request as "comment.id".
http://databasefaq.com/index.php/answer/52270/ajax-validation-grails-grails-command-object-validation-with-ajax
CC-MAIN-2018-13
refinedweb
189
66.94
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location. How to: Write Characters to a String .NET Framework 3.5 The following code example writes a certain number of characters from a character array into an existing string, starting at a specified place in the array. Use StringWriter to do this, as demonstrated below. using System; using System.IO; using System.Text; public class CharsToStr { public static void Main(String[] args) { // Create an instance of StringBuilder that can then be modified. StringBuilder sb = new StringBuilder("Some number of characters"); // Define and create an instance of a character array from which // characters will be read into the StringBuilder. char[] b = {' ','t','o',' ','w','r','i','t','e',' ','t','o','.'}; // Create an instance of StringWriter // and attach it to the StringBuilder. StringWriter sw = new StringWriter(sb); // Write three characters from the array into the StringBuilder. sw.Write(b, 0, 3); // Display the output. Console.WriteLine(sb); // Close the StringWriter. sw.Close(); } } This example illustrates the use of a StringBuilder to modify an existing string. Note that this requires an additional using declaration, since the StringBuilder class is a member of the System.Text namespace. Also, instead of defining a string and converting it to a character array, this is an example of creating a character array directly and initializing it. This code produces the following output. Community Additions Show:
https://msdn.microsoft.com/en-us/library/windows/apps/z4kzt0dd(v=vs.90).aspx
CC-MAIN-2017-13
refinedweb
244
52.15
Mirror Repositories You can mirror repositories of a particular user or organization/group in GitHub, GitLab, and/or Bitbucket. You can mirror repositories to ensure that you are not dependent on a remote version control service being available at all times and to continue your build and release process even in the event of a denial of service attack (or similar). You can read more about this here. Each service has a unique way of naming a group of repositories: Bitbucket Cloud — "team" Bitbucket Server — "project" GitLab — "project" GitHub — "organisation" When a remote repository is mirrored, the local repository mirror is kept up-to-date when changes are made to the remote repository. This happens in one of the following ways: Installing a web hook into each remote repository. Then, the repository is updated when changes are pushed to the local Bitbucket repository. Polling the remote repositories for changes every five minutes. Once the mirroring process has begun, you cannot push to the local Bitbucket repository. The remote repository is assumed to be authoritative and removes any branches in the Bitbucket repository that do not exist in the remote repository. If the master branch is modified on both sides, synchronisation is broken. Remove the Bitbucket repository, and then rerun the setup. A pre-receive hook is automatically setup for the mirrored repository to block all changes to the local Bitbucket repository. If you want to push changes to the local Bitbucket repository, select the Remove option from View and Configure Mirrored Repositories. Mirroring Repositories Enter the Organization/Team/Group/User. Enter a Target Project. Typically this is an empty project, but it doesn’t have to be. For this example, it is named "Mirror." To fill out API Key, follow authentication steps outlined below: Authentication is necessary, even if you are syncing public repositories, because of the rate limiting on unauthenticated accounts for remote APIs. GitHub Authentication You need a GitHub API key so the plugin can list your repositories. If you do not already have one with at least the permissions shown in the image, you need to create one. Navigate to. Select Settings > Applications or click here. Under Personal Access Tokens select Generate New Token. Check that it has the correct permissions: GitLab Authentication You need to generate a GitLab personal access token so that ScriptRunner can authenticate with GitLab as your user. Navigate to. Select User Settings > Access Tokens. Configure the access token with a name and the scopes shown in the screenshot below: Bitbucket Cloud/Server Authentication Enter the username and password of a user who is permissioned on the remote repositories. Select an option for How to Synchronize. None If you select None, no synchronization is done. Install Hook If you install a web hook, the remote service calls your Bitbucket instance whenever there are changes to the repositories, which prompts the plugin to sync the repositories. This is the preferred approach because changes are reflected almost immediately, and there is no unnecessary polling. However, you can only use web hooks if your Bitbucket Server instance is accessible to the remote service over the internet. Poll If you choose polling, each remote repository is polled every 5 minutes. This is a lightweight process, and is perfectly acceptable if you can’t use web hooks. Enter a Regular Expression to check against the repository name (not the part that appears in the URL), and can be used to filter the set of repositories you wish to mirror. To choose all, leave the default regular expression as is. Check the Sync New checkbox to sync new repositories that are created or forked into your team/organization/user automatically. If you have set a Regular Expression, it is respected when creating new mirrored repositories. New repositories are created in Bitbucket up to ten minutes after they appear in the remote service. Click Preview. If your token or credentials are correct, you should see a listing of the organization/user repositories and if they are created or updated in the Bitbucket project. Click Run. This can take a while, depending on the number and size of the repositories you are mirroring. You can tail the application log file to see progress, and use the View and Configure Mirrored Repositories function to see what has been created. You see the same screen when it finishes, but it now displays Exists for the local repositories. Security If you are using web hooks for synchronization, GitHub calls a REST endpoint in your Bitbucket instance when it’s pushed to. To know that it’s GitHub that’s calling, the payload of the call is hashed with a secret token that you supply. Follow these steps to generate a random token: Run this code in Script Console. import java.security.SecureRandom SecureRandom random = new SecureRandom(); String str = new BigInteger(130, random).toString(32); Restart Bitbucket with the property -Dgithub.secret.token=<from above>. from aboveis where you add the generated code. If you already have remote repositories that are synced by web hooks, you need to update these hooks, by rerunning this script. If you do not have direct access to the internet, the web services calls respect your values of http.proxyHost and http.proxyPort. However, you must change your .gitconfig on the Bitbucket server to specify the proxy. There is useful information here on how to set a proxy only for certain sites:. Currently, authenticated proxy access is not supported. View and Configure Mirrored Repositories You can view the status of your mirrored repositories and projects, and you can modify the remote sync options. You can check whether your Bitbucket repository is up to date with the remote repository by clicking the Check or Check All links. A warning icon means repositories are not in sync. They do not mean that there is necessarily a problem. Warning icons should not appear if you are using a web hook trigger. If you are using polling, warnings catch up on the next scheduled task (every 5 minutes). If a repository is persistently out of sync, check the application log file. A warning icon is also displayed if the repository is empty or unavailable. Bitbucket and GitHub provide us with no option to distinguish between those two cases. If you previously set that repositories are automatically created, the projects set to do that are listed below the repositories. If you wish to stop this, check the checkbox under Stop Synchronization, and then click Run. To change the regular expression, stop synchronization as above, and then recreate the configuration. It’s fine to mirror into existing repositories, and this should not take very long.
https://docs.adaptavist.com/sr4bib/6.19.1/features/built-in-scripts/mirror-repositories
CC-MAIN-2021-17
refinedweb
1,109
55.13
File Typessuggest change Compiling C programs requires you to work with five kinds of files: - Source files: These files contain function definitions, and have names which end in .cby convention. Note: .ccand .cppare C++ files; not C files. e.g., foo.c - Header files: These files contain function prototypes and various pre-processor statements (see below). They are used to allow source code files to access externally-defined functions. Header files end in .hby convention. e.g., foo.h - Object files: These files are produced as the output of the compiler. They consist of function definitions in binary form, but they are not executable by themselves. Object files end in .oby convention, although on some operating systems (e.g. Windows, MS-DOS), they often end in .obj. e.g., foo.o fooeon Windows. e.g., foo foo.exe - Libraries: A library is a compiled binary but is not in itself an an executable (i.e., there is no main()function in a library). A library contains functions that may be used by more than one program. A library should ship with header files which contain prototypes for all functions in the library; these header files should be referenced (e.g; #include <library.h>) in any source file that uses the library. The linker then needs to be referred to the library so the program can successfully compiled. There are two types of libraries: static and dynamic. - Static library: A static library ( .afiles for POSIX systems and .libfiles for Windows — not to be confused with DLL import library files, which also use the .libextension) is statically built into the program . Static libraries have the advantage that the program knows exactly which version of a library is used. On the other hand, the sizes of executables are bigger as all used library functions are included. e.g., libfoo.a foo.lib - Dynamic library: A dynamic library ( .sofiles for most POSIX systems, .dylibfor OSX and .dllfiles for Windows) is dynamically linked at runtime by the program. These are also sometimes referred to as shared libraries because one library image can be shared by many programs. Dynamic libraries have the advantage of taking up less disk space if more than one application is using the library. Also, they allow library updates (bug fixes) without having to rebuild executables. e.g., foo.so foo.dylib foo.dll Found a mistake? Have a question or improvement idea? Let me know. Table Of Contents
https://essential-c.programming-books.io/file-types-4d5e893872e2461a8926daecbfe4ebd8
CC-MAIN-2021-25
refinedweb
407
69.07
okay, so my code is: import random money = 100 #Write your game of chance functions here def coin_flip(call, amount): if random.randint(1,2) == 1: coin_toss = "Heads" else: coin_toss = "Tails" if call == coin_toss: result = "won" total_amount = money + amount else: result = "lost" total_amount = money - amount print( "You flipped a %s and you called %s! You %s and now have $%.2f" %(coin_toss, call, result, total_amount) ) coin_flip("Heads", 10) and this actually works quite nicely, however I am struggling to figure out how to update the global variable “money” to represent the new amount. I’ve tried changing the code so that instead of “total_amount = money + amount” it shows “money = money + amount” in the hopes that it would update the global variable but instead it only returns an error message stating “the local variable money has been referenced before assignment”. Any general thoughts on the code? How do I incorporate into my function the ability to continually update the global variable “money”?
https://discuss.codecademy.com/t/games-of-chance-code-challenge-link-https-www-codecademy-com-practice-projects-games-of-chance/440370
CC-MAIN-2019-43
refinedweb
160
57.61
Python is one of those select languages that make functions first class object. Yet you can use it for years and never even notice that it is an object-oriented language. What makes functions as objects special? The Python function object is one of the reasons why programmers can completely miss the fact that Python is object-oriented. A Python function doesn’t give away the fact that it is an object as it can be used as if it was just a function, a function as you would find in almost any language. However, the Python function is an object and knowing this makes many things so much easier and so much more logical. Before we learn about function objects let’s look at some of the more basic features of Python functions. A function is defined using def: def sum(a,b): c=a+b return c This looks like a function definition in many other languages and this is the intent. You can call a function using the call operator () which is also used to specify arguments for the parameters. For example: print(sum(1,2)) prints the return value 3. Notice that a function is not executed when it is defined, only when it is explicitly executed, but as we will discover something does happen during a function definition. A function doesn’t need to have a return statement and doesn’t need to return a value. By default a function that doesn’t return a value returns the special value None which is generally discarded. Variables that are defined within the function are added to the function’s local table which is different from its dictionary object. They are local variables in the sense that they have nothing to do with any variables with the same names elsewhere in the program. Unlike attributes, local variables only exist while the function is executing. Parameters are added to the local table and hence behave like local variables. They are always passed by value but as the value of any variable in Python is a reference to an object this behaves more like pass by reference – sometimes called pass-by-object reference. To make this clear we need more than one example. First we need an object to use to pass to the function: class MyClass: a=0 The function simply attempts to change the value of its parameter: def myFunction(x): x=1 print(x) Now when we call the function: myFunction(MyClass) print(MyClass.a) what happens? The answer is that the reference in MyClass is copied into the parameter x, then this is overwritten by a reference to an integer object. This means that we see 1 printed by the function. When the function returns, MyClass still references the original object and its a attribute is unchanged and still zero. This means changes to parameters within functions have no effect on variables in the calling program. However, this doesn’t mean that functions cannot change things in the calling program. For example, consider: def myFunction(x): x.a = 1 print(x.a) When this is called using: the same things occur – the reference in MyClass is copied into x, but then x.a which is the attribute on the same object that MyClass references is changed to 1. So the print in the function prints 1 but so does the print in the calling program. Attributes of objects in the calling program can be changed by a function.
https://www.i-programmer.info/programming/python/12437-programmers-python-function-objects.html
CC-MAIN-2019-13
refinedweb
583
62.38
"Micro-services is the new black" - Splitting the project in to independently scalable services is the currently the best option to ensure the evolution of the code. In Python there is a Framework called "Nameko" which makes it very easy and powerful. Micro services The term "Microservice Architecture" has sprung up over the last few years to describe a particular way of designing software applications as suites of independently deployable services. - M. Fowler I recommend reading the Fowler's posts to understand the theory behind it. Ok I so what does it mean? In brief a Micro Service Architecture exists when your system is divided in small (single context bound) responsibilities blocks, those blocks doesn't know each other, they only have a common point of communication, generally a message queue, and does know the communication protocol and interfaces. Give me a real-life example The code is available on github: take a look at service and api folders for more info. Consider you have an REST API, that API has an endpoint receiving some data and you need to perform some kind of computation with that data, instead of blocking the caller you can do it asynchronously, return an status "OK - Your request will be processed" to the caller and do it in a background task. Also you want to send an email notification when the computation is finished without blocking the main computing process, so it is better to delegate the "email sending" to another service. Scenario Show me the code! Lets create the system to understand it in practice. Environment We need an environment with: - A running RabbitMQ - Python VirtualEnv for services - Python VirtualEnv for API Rabbit The easiest way to have a RabbitMQ in development environment is running its official docker container, considering you have Docker installed run: docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 -p 5672:5672 rabbitmq:3-management Go to the browser and access using credentials guest:guest if you can login to RabbitMQ dashboard it means you have it running locally for development. The Service environment Now lets create the Micro Services to consume our tasks. We'll have a service for computing and another for mail, follow the steps. In a shell create the root project directory $ mkdir myproject $ cd myproject Create and activate a virtualenv (you can also use virtualenv-wrapper) $ virtualenv service_env $ source service_env/bin/activate Install nameko framework and yagmail (service_env)$ pip install nameko (service_env)$ pip install yagmail The service code Now having that virtualenv prepared (consider you can run service in a server and API in another) lets code the nameko RPC Services. We are going to put both services in a single python module, but you can also split in separate modules and also run them in separate servers if needed. In a file called service.py import yagmail from nameko.rpc import rpc, RpcProxy class Mail(object): name = "mail" @rpc def send(self, to, subject, contents): yag = yagmail.SMTP('myname@gmail.com', 'mypassword') # read the above credentials from a safe place. # Tip: take a look at Dynaconf setting module yag.send(to=to.encode('utf-8'), subject=subject.encode('utf-8'), contents=[contents.encode('utf-8')]) class Compute(object): name = "compute" mail = RpcProxy('mail') @rpc def compute(self, operation, value, other, email): operations = {'sum': lambda x, y: int(x) + int(y), 'mul': lambda x, y: int(x) * int(y), 'div': lambda x, y: int(x) / int(y), 'sub': lambda x, y: int(x) - int(y)} try: result = operations[operation](value, other) except Exception as e: self.mail.send.async(email, "An error occurred", str(e)) raise else: self.mail.send.async( email, "Your operation is complete!", "The result is: %s" % result ) return result Now with the above services definition we need to run it as a Nameko RPC service. NOTE: We are going to run it in a console and leave it running, but in production it is recommended to put the service to run using supervisord or an alternative. Run the service and let it running in a shell (service_env)$ nameko run service --broker amqp://guest:guest@localhost starting services: mail, compute Connected to amqp://guest:**@127.0.0.1:5672// Connected to amqp://guest:**@127.0.0.1:5672// Testing it Go to another shell (with the same virtenv) and test it using nameko shell (service_env)$ nameko shell --broker amqp://guest:guest@localhost Nameko Python 2.7.9 (default, Apr 2 2015, 15:33:21) [GCC 4.9.2] shell on linux2 Broker: amqp://guest:guest@localhost >>> You are now in the RPC client testing shell exposing the n.rpc object, play with it >>> n.rpc.mail.send("name@email.com", "testing", "Just testing") The above should sent an email and we can also call compute service to test it, note that it also spawns an async mail sending with result. >>> n.rpc.compute.compute('sum', 30, 10, "name@email.com") 40 >>> n.rpc.compute.compute('sub', 30, 10, "name@email.com") 20 >>> n.rpc.compute.compute('mul', 30, 10, "name@email.com") 300 >>> n.rpc.compute.compute('div', 30, 10, "name@email.com") 3 Calling the micro-service through the API In a different shell (or even a different server) prepare the API environment Create and activate a virtualenv (you can also use virtualenv-wrapper) $ virtualenv api_env $ source api_env/bin/activate Install Nameko, Flask and Flasgger (api_env)$ pip install nameko (api_env)$ pip install flask (api_env)$ pip install flasgger NOTE: In api you dont need the yagmail because it is service responsability Lets say you have the following code in a file api.py from flask import Flask, request from flasgger import Swagger from nameko.standalone.rpc import ClusterRpcProxy app = Flask(__name__) Swagger(app) CONFIG = {'AMQP_URI': "amqp://guest:guest@localhost"} @app.route('/compute', methods=['POST']) def compute(): """ Micro Service Based Compute and Mail API This API is made with Flask, Flasgger and Nameko --- parameters: - name: body in: body required: true schema: id: data properties: operation: type: string enum: - sum - mul - sub - div email: type: string value: type: integer other: type: integer responses: 200: description: Please wait the calculation, you'll receive an email with results """ operation = request.json.get('operation') value = request.json.get('value') other = request.json.get('other') email = request.json.get('email') msg = "Please wait the calculation, you'll receive an email with results" subject = "API Notification" with ClusterRpcProxy(CONFIG) as rpc: # asynchronously spawning and email notification rpc.mail.send.async(email, subject, msg) # asynchronously spawning the compute task result = rpc.compute.compute.async(operation, value, other, email) return msg, 200 app.run(debug=True) Put the above API to run in a different shell or server (api_env) $ python api.py * Running on (Press CTRL+C to quit) and then access the url you will see the Flasgger UI and you can interact with the api and start producing tasks on queue to the service to consume. NOTE: You can see the shell where service is running for logging, prints and error messages. You can also access the RabbitMQ dashboard to see if there is some message in process there. There is a lot of more advanced things you can do with Nameko framework you can find more information on Let's Micro Serve!
http://brunorocha.org/python/microservices-with-python-rabbitmq-and-nameko.html
CC-MAIN-2017-47
refinedweb
1,209
52.09
Opened 4 years ago Closed 4 years ago Last modified 3 years ago #18769 closed Bug (invalid) Despite selected language, Forms still rely on LANGUAGE_CODE to format datetime (demo included) Description I have discussed this issue in stackoverflow and it seems to be a bug. Summary: In a nutshell, despite creating custom formats.py, only the templates react to the selected language while the forms still rely on LANGUAGE_CODE Details: I have created a small live demo to show the problem. Please open the demo here: When you click on British English, you can see how both the date- and time format within the template change accordingly, which is great. Now if you click on Add, you will see how both the current date and time are populated for you in the form. However they still carry the American date format, instead of the selected British language. The only way to fix this is to change LANGUAGE_CODE = 'en-us' to LANGUAGE_CODE = 'en-gb' in settings.py. This approach would be obviously useless as its no longer dynamic and favors one group over the other. LANGUAGE_CODE should be the last priority since the selected language should have a higher priority. But this doesn't work when having custom formats.py for each language. I have created custom formats.py to override the date and time formats for en and en_GB as described in the documentation so I am clueless what else I could do. Please be so kind and download my demo (22 kb) from my dropbox () or see attachment: All you have to do is to edit settings.py to adjust the path to sqlite.db. Attachments (1) Change History (4) Changed 4 years ago by houmie comment:1 Changed 4 years ago by houmie - Needs documentation unset - Needs tests unset - Patch needs improvement unset - Type changed from Uncategorized to Bug comment:2 Changed 4 years ago by kmtracey - Resolution set to invalid - Status changed from new to closed The form you are using hasn't specified to localize the fields. The forms.py file in the sandbox project has: from django.forms.models import ModelForm from Sandbox_App.models import Company class CompanyForm(ModelForm): def date_callback(self, field, **kwargs) : return field.date(localize=True, **kwargs) def time_callback(self, field, **kwargs) : return field.time(localize=True, **kwargs) class Meta: model = Company I gather it is expected that these callback functions will turn on localization for the fields, but I do not know where the idea for defining these callbacks came from. Django model forms do not call these functions, so they have no effect. Changing that forrms.py file to: from django import forms from Sandbox_App.models import Company class CompanyForm(forms.ModelForm): date = forms.DateField(localize=True) time = forms.TimeField(localize=True) class Meta: model = Company results in the form on initial display being localized as per the chosen language. comment:3 Changed 3 years ago by justinkhill@… I'm having trouble getting my Canadian and Australian sites to use the correct date formatting via the localize=True method mentioned here. My other international sites are working correctly. I've decided it is because there are no en_AU and en_CA formats.py files in the django core project: Am I left to create my own as described here: If so, so be it, but may I ask why such well know countries do not have their own formats.py in the core project? Am I doing it wrong? Sandbox demo (i18n problem)
https://code.djangoproject.com/ticket/18769
CC-MAIN-2016-30
refinedweb
582
64.2
Red Hat Bugzilla – Bug 439702 gdm is breaks when using pam_namespace Last modified: 2015-01-14 18:20:40 EST Description of problem: gdm-worker-thread goes to 100% cpu, probably when the /tmp directory disappears on it. (I can hear Nalin screaming in BRNO)... If you install the xguest package and try it out you will see the behaviour, I am seeing it on one laptop but not my own. Hi Dan. Can't reproduce this here because xguest won't install on rawhide: error: %pre(xguest-1.0.6-6.fc9.noarch) scriptlet failed, exit status 1 error: install: %pre scriptlet failed (2), skipping xguest-1.0.6-6.fc9 That is strange. Do you have selinux turned on, on the machine you are attempting to install it on? I've tried to install it on two different laptops with rawhide. Turns out both had selinux disabled. Seems like we should allow the package to install though. Ok, I've was able to install xguest when I put selinux into permissive mode. Enforcing mode doesn't allow me to log in to any accounts even from login. In permissive mode I'm prompted for a password when clicking on the Guest user. That seems odd. Can you please give me some hints on how to reproduce this? believe this happens any longer.
https://bugzilla.redhat.com/show_bug.cgi?id=439702
CC-MAIN-2017-04
refinedweb
224
75.71
A HTTP mocking framework written in Swift. 😎 Painless API mocking: Shock lets you quickly and painlessly provide mock responses for web requests made by your apps. 🧪 Isolated mocking: When used with UI tests, Shock runs its server within the UI test process and stores all its responses within the UI tests target - so there is no need to pollute your app target with lots of test data and logic. ⭐️ Shock now supports parallel UI testing!: Shock can run isolated servers in parallel test processes. See below for more details! 🔌 Shock can now host a basic socket: In addition to an HTTP server, Shock can also host a socket server for a variety of testing tasks. See below for more details! Add the following to your podfile: pod 'Shock', '~> x.y.z' You can find the latest version on cocoapods.org Copy the URL for this repo, and add the package in your project settings. Shock aims to provide a simple interface for setting up your mocks. Take the example below: class HappyPathTests: XCTestCase { var mockServer: MockServer! override func setUp() { super.setUp() mockServer = MockServer(port: 6789, bundle: Bundle(for: type(of: self))) mockServer.start() } override func tearDown() { mockServer.stop() super.tearDown() } func testExample() { let route: MockHTTPRoute = .simple( method: .get, urlPath: "/my/api/endpoint", code: 200, filename: "my-test-data.json" ) mockServer.setup(route: route) /* ... Your test code ... */ } } Bear in mind that you will need to replace your API endpoint hostname with 'localhost' and the port you specify in the setup method during test runs. e.g.:{PORT}/my/api/endpoint In the case or UI tests, this is most quickly accomplished by passing a launch argument to your app that indicates which endpoint to use. For example: let args = ProcessInfo.processInfo.arguments let isRunningUITests = args.contains("UITests") let port = args["MockServerPort"] if isRunningUITests { apiConfiguration.setHostname(":\(port)/") } Note: 👉 The easiest way to pass arguments from your test cases to your running app is to use another of our wonderful open-source libraries: AutomationTools Shock provides different types of mock routes for different circumstances. A simple mock is the preferred way of defining a mock route. It responds with the contents of a JSON file in the test bundle, provided as a filename to the mock declaration like so: let route: MockHTTPRoute = .simple( method: .get, urlPath: "/my/api/endpoint", code: 200, filename: "my-test-data.json" ) A custom mock allows further customisation of your route definition including the addition of query string parameters and HTTP headers. This gives you more control over the finer details of the requests you want your mock to handle. Custom routes will try to strictly match your query and header definitions so ensure that you add custom routes for all variations of these values. let route = MockHTTPRoute = .custom( method: .get, urlPath: "/my/api/endpoint", query: ["queryKey": "queryValue"], headers: ["X-Custom-Header": "custom-header-value"], code: 200, filename: "my-test-data.json" ) Sometimes we simply want our mock to redirect to another URL. The redirect mock allows you to return a 301 redirect to another URL or endpoint. let route: MockHTTPRoute = .redirect(urlPath: "/source", destination: "/destination") A templated mock allows you to build a mock response for a request at runtime. It uses Mustache to allow values to be built in to your responses when you setup your mocks. For example, you might want a response to contain an array of items that is variable size based on the requirements of the test. /template route in the Shock Route Tester example app for a more comprehensive example. let route = MockHTTPRoute = .template( method: .get, urlPath: "/template", code: 200, filename: "my-templated-data.json", data: [ "list": ["Item #1", "Item #2"], "text": "text" ]) ) A collection route contains an array of other mock routes. It is simply a container for storing and organising routes for different tests. In general, if your test uses more than one route Collection routes are added recursively, so a given collection route can be included in another collection route safely. let firstRoute: MockHTTPRoute = .simple(method: .get, urlPath: "/route1", code: 200, filename: "data1.json") let secondRoute: MockHTTPRoute = .simple(method: .get, urlPath: "/route2", code: 200, filename: "data2.json") let collectionRoute: MockHTTPRoute = .collection(routes: [ firstRoute, secondRoute ]) A timeout route is useful for testing client timeout code paths. It simply waits a configurable amount of seconds (defaulting to 120 seconds). Note if you do specify your own timeout, please make sure it exceeds your client's timeout. let route: MockHTTPRoute = .timeout(method: .get, urlPath: "/timeouttest") let route: MockHTTPRoute = .timeout(method: .get, urlPath: "/timeouttest", timeoutInSeconds: 5) In some case you might prefer to have all the calls to be mocked so that the tests can reliably run without internet connection. You can force this behaviour like so: server.shouldSendNotFoundForMissingRoutes = true This will send a 404 status code with an empty response body for any unrecognised paths. Shock now support middleware! Middleware lets you use custom logic to handle a given request. The simplest way to use middleware is to add an instance of ClosureMiddleware to the server. For example: let myMiddleware = ClosureMiddleware { request, response, next in if request.headers["X-Question"] == "Can I have a cup of tea?" { response.headers["X-Answer"] = "Yes, you can!" } next() } mockServer.add(middleware: myMiddleware) The above will look for a request header named X-Question and, if it is present with the expected value, it will send back an answer in the 'X-Answer' response header. Mock routes and middleware work fine together but there are a few things worth bearing in mind: For middleware such as the example above, the order of middleware won't matter. However, if you are making changes to a part of the response that was already set by the mock routes middleware, you may get unexpected results! Shock can now host a socket server in addition to the HTTP server. This is useful for cases where you need to mock HTTP requests and a socket server. The Socket server uses familiar terminology to the HTTP server, so it has inherited the term "route" to refer to a type of socket data handler. The API is similar to the HTTP API in that you need to create a MockServerRoute, call setupSocket with the route and when server start is called a socket will be setup with your route (assuming at least one route is registered). If no MockServerRoutes are setup, the socket server is not started. The socket server can only be hosted in addition to the HTTP server, as such Shock will need a port range of at least two ports, using the init method that takes a range. let range: ClosedRange<Int> = 10000...10010 let server = MockServer(portRange: range, bundle: ...) There is only one route currently available for the socket server and that is logStashEcho. This route will setup a socket that accepts messages being logged to Logstash and echo them back as strings. Here is an example of using logStashEcho with our JustTrack framework. import JustLog import Shock let server = MockServer(portRange: 9090...9099, bundle: ...) let route = MockSocketRoute.logStashEcho { (log) in print("Received \(log)" } server.setupSocket(route: route) server.start() let logger = Logger.shared logger.logstashHost = "localhost" logger.logstashPort = UInt16(server.selectedSocketPort) logger.enableLogstashLogging = true logger.allowUntrustedServer = true logger.setup() logger.info("Hello world!") It's worth noting that Shock is an untrusted server, so the logger.allowUntrustedServer = true is necessary. The Shock Route Tester example app lets you try out the different route types. Edit the MyRoutes.swift file to add your own and test them in the app. Shock is available under Apache License 2.0. See the LICENSE file for more info. Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics
https://swiftpack.co/package/justeat/Shock
CC-MAIN-2022-27
refinedweb
1,277
58.69
Static variable is a special variable that is stored in the data segment unlike the default automatic variable that is stored in stack. A static variable can be initialized by using keyword static before variable name. This is useful if we want to isolate pieces of a program to prevent accidental changes in global variables. Static local variables are variables whose value is held in a function call to another.. The function count () returns the number of times it has been called. See the local int variable is initialized. This boot is only valid for the first time the function is called as a must maintain its value from a call to the other. What the function does is increase in every call and return its value. The best way to understand this is by implementing static local variable. Example: #include <stdio.h> #include <conio.h> void count(void) { static int count1 = 0; int count2 = 0; count1++; count2++; printf("\nValue of count1 is %d, Value of count2 is %d", count1, count2); } int main() { clrscr(); count(); count(); count();
http://ecomputernotes.com/what-is-c/types-and-variables/what-is-a-static-variable
CC-MAIN-2018-17
refinedweb
177
65.32
how can i pick the different numbers of both numbers in a pair entry more efficiently if(loc[0].first!=loc[1].first && loc[0].first!=loc[2].first) x=loc[0].first; if(loc[1].first!=loc[0].first && loc[1].first!=loc[2].first) x=loc[1].first; if(loc[2].first!=loc[0].first && loc[2].first!=loc[1].first) x=loc[2].first; if(loc[0].second!=loc[1].second && loc[0].second!=loc[2].second) y=loc[0].second; if(loc[1].second!=loc[0].second && loc[1].second!=loc[2].second) y=loc[1].second; if(loc[2].second!=loc[0].second && loc[2].second!=loc[1].second) y=loc[2].second; Source: Windows Que.. Category : std-pair The following code doesn’t compile. The line with pair is giving the error. Is there some other way to access the data or is this way correct?? unordered_map<int,int> hm; unordered_map<int,int>::iterator it; it=find(hm.begin(),hm.end(),x+c); if (it!=hm.end()) { bNotFound = false; pair<int,int> p = *it; ind = p.second; } Source: Windows Que.. .. Suppose we have an array of doubles x and an array of indices y, and we want to sort these indices by the respective values in x (so, sort [i in y] by x[i] as key). We can then create an array of pairs, with one component being the key value and one being the .. I want to order some strings by their indexes. And I don’t want to use two different types of priority queue. #include <string> #include <queue> #include <utility> int main() { const std::string &a = "hello"; std::pair<int, const std::string &> p = std::make_pair(1, a); std::priority_queue<std::pair<int, const std::string &>> pq; pq.push(p); return 0; } So how to .. just to clear this doubt of fine i just want to ask that which method is faster or more efficient to access pairs while iterating over a contiguous block of pairs. I used two method to iterate over a block. 1st pair<int, char> arr[3] = {{1, ‘a’}, {2, ‘b’}, {3, ‘c’}}; for (int i = .. In an assignment i was given a method that looks like this std::pair<double, double> operator()(const Eigen::VectorXd &vec, int index) const { return (*this)(vec[index – 1], vec[index], vec[index + 1], vec[index + 2]); } I am a little bit confused on the return type of the method. Shouldn’t it be a std::pair<double*, double*>? Moreover, how can .. I want to build a container for fractions. The key will represent the value of the fraction in double; The numerator and the denominator are stored in a pair. std::map<double, pair<int, int>> m (); I had problems with inserting and printing the elements. Can you tell me how to do it for this specific case? .. I am getting the problem on line 15 and 20 where i am trying to pushback elements in to the pair vector #include <iostream> #include <vector> #include <utility> using namespace std; int main() { int x, y, a, b, c, d, j, m, v; vector<pair<int, int> > ladder; cin >> x >> y; for (int .. We are given a std::vector of n pairs. (0 < n < 10^5). We are given q queries (0 < q <10^5). for each query we are given two numbers X and Y, we have to tell no of pairs which has first value greater than X and second value greater than Y. I tried .. Recent Comments
https://windowsquestions.com/category/std-pair/
CC-MAIN-2022-05
refinedweb
589
64.71
Details Description. Activity - All - Work Log - History - Activity - Transitions Here's a potential fix, which is really klugey. If no one objects to this I'll upload it as a real patch in the next couple of days: diff --git a/src/mapred/org/apache/hadoop/mapred/JobConf.java b/src/mapred/org/apache/hadoop/mapred/JobConf.java index 11be95a..4794eab 100644 --- a/src/mapred/org/apache/hadoop/mapred/JobConf.java +++ b/src/mapred/org/apache/hadoop/mapred/JobConf.java @@ -1452,6 +1452,13 @@ public class JobConf extends Configuration { if (toReturn.startsWith("file:")) { toReturn = toReturn.substring("file:".length()); } + // URLDecoder is a misnamed class, since it actually decodes + // x-www-form-urlencoded MIME type rather than actual + // URL encoding (which the file path has). Therefore it would + // decode +s to ' 's which is incorrect (spaces are actually + // either unencoded or encoded as "%20"). Replace +s first, so + // that they are kept sacred during the decoding process. + toReturn = toReturn.replaceAll("\\+", "%2B"); toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } Are there any other characters that need to be fixed? I'm worried that this is a point solution for one character rather than the right solution. Owen: that's the only difference I know of that's mentioned in the spec: I spent about 4 hours trying to find a portable non-klugey fix. The trouble is that the behavior is different on Windows compared to Linux. On a Windows JVM, it encodes spaces as "%20" and +s as "%2B" and on Linux it does neither, best I can tell. I definitely agree that this fix is not optimal, but I think '+' is the most common case for a "weird" character in a JAR name. In Debian and RPM packages, the non-alphanumeric characters allowed in version numbers are [+-~.:] and I think all of those should be fine after this patch. Of course, you could detect the operating system like Path does. Look at the definition of Path.WINDOWS. Of course, we probably should make a method that checks that boolean... That said, I'm ok with the quoting as long as it works on both operating systems. (I agree, it is kludgy, but...) passed system test framework compile. The findbugs warnings are bogus (none related to this patch). The release audit warnings are also unrelated ("smoke-tests" file and "robots.txt" file). See MAPREDUCE-2172. +1 This patch looks good to me. Looks like there may be other potential incorrect uses of URLDecode in the HarFileSystem, minding filling a jira to fix those? Looks like there may be other potential incorrect uses of URLDecode in the HarFileSystem, minding filling a jira to fix those? Looking at HarFileSystem, it seems like it's actually safe - it's using URLDecoder to decode something that was encoded using URLEncoder in HadoopArchives.java. Using these as a pair is OK: groovy:000> URLDecoder.decode(URLEncoder.encode("foo+bar baz 100%")) ===> foo+bar baz 100% Integrated in Hadoop-Mapreduce-trunk-Commit #565 (See) MAPREDUCE-714. JobConf.findContainingJar unescapes unnecessarily on linux. Contributed by Todd Lipcon Integrated in Hadoop-Mapreduce-22-branch #33 (See) Integrated in Hadoop-Mapreduce-trunk #643 (See) I just confirmed this on Windows vs Linux. On Windows, the URL that you get back from ClassLoader.getResource has spaces encoded as "%20". On Linux it doesn't. Anyone have a creative solution to deal with this? We'd like to have +s in our version numbers due to standards in RPM and Debian land, but this is blocking that.
https://issues.apache.org/jira/browse/MAPREDUCE-714
CC-MAIN-2017-51
refinedweb
586
58.69
Create and save animated GIF with Python, Pillow Using the Python image processing library Pillow (PIL), you can create and save animated GIFs. Here, the following contents will be described. - Save as GIF with Image.save() - Sample code to generate animated GIF - Parameters of Image.save() append_images optimize loop duration Save as GIF with Image.save() You can create an animated GIF from multiple images and save it using Image.save(). im.save('out.gif', save_all=True, append_images=[im1, im2, ...]) The image list [im1, im2, ...] is added to the image im of the first frame, and an animated GIF file out.gif is generated and saved. See the official document below for details. The sample code and the explanation of the parameters are shown below. Sample code to generate animated GIF Here is sample code for drawing circles that grows gradually with Pillow's ImageDraw and saving it as a GIF file. from PIL import Image, ImageDraw images = [] width = 200 center = width // 2 color_1 = (0, 0, 0) color_2 = (255, 255, 255) max_radius = int(center * 1.5) step = 8 for i in range(0, max_radius, step): im = Image.new('RGB', (width, width), color_1) draw = ImageDraw.Draw(im) draw.ellipse((center - i, center - i, center + i, center + i), fill=color_2) images.append(im) for i in range(0, max_radius, step): im = Image.new('RGB', (width, width), color_2) draw = ImageDraw.Draw(im) draw.ellipse((center - i, center - i, center + i, center + i), fill=color_1) images.append(im) images[0].save('data/dst/pillow_imagedraw.gif', save_all=True, append_images=images[1:], optimize=False, duration=40, loop=0) The following animated GIF file is generated. Refer to the following article about how to draw figures such as circles with Pillow. Parameters of Image.save() Basically, if you have a list of images you can create an animated GIF with the following code: images[0].save('data/dst/pillow_imagedraw.gif', save_all=True, append_images=images[1:], optimize=False, duration=40, loop=0) If you want to create a GIF animation from multiple existing images instead of drawing graphics and creating images as in the example above, you can process the same if you load the images and store them in a list. append_images Call the save() method from the first frame image, passing the list of remaining images to append_images. Note that if you use append_images=images, the first frame will be repeated twice. In the above example, the second and subsequent images are selected by slicing. optimize I have not read the source code properly, so I do not know what processing is done, but if the default ( optimize=True), similar images may be omitted. If the output file is wrong, trying optimize=False may solve it. loop Set the number of loops to loop. If you set loop=0, it becomes an infinite loop. Note that the animation ends in one time by default. duration Set the display time of each frame to duraton in milliseconds. If the value is too small, it will be ignored.
https://note.nkmk.me/en/python-pillow-gif/
CC-MAIN-2020-40
refinedweb
500
50.33
CHECK_EXPIRE(3) BSD Programmer's Manual CHECK_EXPIRE(3) check_expire - check for password expiration #include <stdio.h> #include <util.h> int login_check_expire(FILE *back, struct passwd *pwd, char *class, int lastchance); The login_check_expire() function is called by a BSD authentication login script to check whether the user's password entry, as described by pwd, has expired. If a class is specified, it is used instead of the class specified in the user's password database entry. If the lastchance argument is non-zero, the user's password has expired, and it has not been expired longer than "password-dead" seconds (see login.conf(5)), the user will be able to log in one last time to change the password. The login_check_expire() function returns 0 if the user's password has not expired, and 1 if it has expired or if an error occurred. Status and error messages are passed back to the login script caller via the back channel, back. auth_subr(3), authenticate(3), login.conf(5) MirOS BSD #10-current November.
https://www.mirbsd.org/htman/i386/man3/login_check_expire.htm
CC-MAIN-2015-35
refinedweb
171
56.05
in a JAR file. JAR stands for the Java Archive. This file format is used Java Jar File Java Jar File In Java, JAR (Java ARchive) is a platform-independent file format that allows you... for reading and writing the JAR (Java ARchive) file format, which is based java-jar file creation - Java Beginners java-jar file creation how to create a jar file?i have a folder... file Hi Friend, JAR stands for the Java Archive. This file format...:// java jar file - Java Beginners java jar file How to create jar Executable File.Give me simple steps... int buffer = 10240; protected void createJarArchive(File jarFile, File...(); System.out.println("Jar File is created successfully."); } catch (Exception ex jar file jar file how to create a jar file in java Creating JAR File - Java Beginners me, in letting me know, as to how to create JAR file from my JAVA source... buffer = 10240; protected void createJarArchive(File jarFile, File[] listFiles...(); } out.close(); fout.close(); System.out.println("Jar File How to create a jar file ??? The given code creates a jar file using java. import java.io.*; import...; protected void createJarArchive(File jarFile, File[] listFiles) { try...(); System.out.println("Jar File is created successfully."); } catch (Exception ex JAR FILE and applications. The Java Archive (JAR) file format enables to bundle multiple...JAR FILE WHAT IS JAR FILE,EXPLAIN IN DETAIL? A JAR file... link: Jar File Explanation Java to extract info to HTML Java to extract info to HTML I need to write a java program... subcategory I need to extract from the file and creating an individual method... wrong? I am in an intro course to java so my knowledge of the language Viewing contents of a JAR File the jar file operation through the given example. Program Result: This program... Viewing contents of a JAR File This section shows you how you can read the content of jar file jar file jar file how to run a java file by making it a desktop icon i need complete procedur ..through cmd jar file - Java Beginners an application packaged as a JAR file (requires the Main-class manifest header)java -jar...jar file jar file When creating a jar file it requires a manifest... options in jar file. What is Jar File? JAR files are packaged in the zip Listing the Main Attributes in a JAR File Manifest Listing the Main Attributes in a JAR File Manifest Jar Manifest: Jar Manifest file is the main section of a jar file. This file contains the detailed information about Creating a JAR file in Java Creating a JAR file in Java This section provides you to the creating a jar file through the java source code by using the jar tool command which is provided Java Jar File - Java Beginners Java Jar File What is a Java JAR file ..and how can i open a .jar file in Java? Just create a Jar file and Double click on it, it will automatically runs main method in that Jar : to create Project as JAR jarfile - JDBC jarfile i m making my project in netbean so i dont have mail.jar or activation.jar file so what should i do util packages in java util packages in java write a java program to display present date and after 25days what will be the date? import java.util.*; import java.text.*; class FindDate{ public static void main(String[] args Java JAR Files with applets and applications. The Java Archive (JAR) file format enables... Execute a JAR file java -jar jar_file_name In computing, a JAR file (or Java ARchive) is used for aggregating many files seeking info - JSP-Servlet seeking info Looking for the information on Java, JSP and Servlet Programming. Hello NaveenDon't worry as every one faces the same kind... computer or might be any code file is missing.so i would suggest You to make sure Jar File using Java How to Create Jar File using Java Programming Language A Jar file combines... is the code for Java Jar File Function: import java.io.*; import ... in the jar file. In this section, we are going to create our own jar file jar file jar file steps to create jar file with example Creating JAR File - Java Beginners Creating JAR File Respected Sir, Thankyou very much for your..., which says, Failed to load Main-Class manifest attribute from H:\Stuff\NIIT\Java... to change the contents of my manifest file. I read somewhere regarding i have to add Java Execute Jar file operating system or platform. To execute a JAR file, one must have Java... file type java -jar [Jar file Name] in the command prompt. To execute...JAR stands for Java ARchive and is platform independent. By making all change jar file icon - Java Beginners change jar file icon How to create or change jar file icon Hi friend, The basic format of the command for creating a JAR file is: jar cf jar-file input-file(s) * The c option indicates that you want quotion on .jar quotion on .jar in realtime where we use .jar class files. A Jar file combines several classes into a single archive file. Basically,library classes are stored in the jar file. For more information,please go through jar File creation - Swing AWT in java but we can create executable file in java through .jar file.. how can i convert my java file to jar file? Help me...jar File creation I am creating my swing applications. How can i Java FTP jar Java FTP jar Which Java FTP jar should be used in Java program for uploading files on FTP server? Thanks Hi, You should use commons-net-3.2.jar in your java project. Read more at FTP File Upload in Java How to use JAR file in Java on any platform. All operating system support Java. JAR file works as normal Zip...JAR which stands for Java ARchive allows a programmer to archive or collect... to digitally sign the JAR file. Users who want to use the secured file can check Changing Executable Jar File Icon Changing Executable Jar File Icon I have created an executable jar file for my java program and the icon that appears is the java icon. I will like...;Hi, You may use JSmooth to create executable java file and also associate icon Java util package Examples keeps giving me " could not find the main class". Program will exit. .jar file keeps giving me " could not find the main class". Program will exit... clean and build it which produces a .jar file in my dist folder. When I double... will exit." However, if I choose to run it from the command prompt "java -jar Jar file - Java Server Faces Questions Jar file Hi All, What is the Jar file to run The Jsf Applications.When i am trying to run in the Eclipse its not running. Thanks in Advance, Puppy Hi friend, Jar file to run The Jsf Applications jsf Util Package - Utility Package of Java Java Util Package - Utility Package of Java Java Utility package is one of the most commonly used packages in the java program. The Utility Package of Java consist Vendor Info Error - WebSevices Vendor Info Error Hi, i wrote the code for Vendor Information using java script. If its full time the vendor info alert box is not displayed. And its contract or contract to hire the alert box is displayed. Tell me JAR Generation JAR Generation Hi, I have done this code. Can u pls tell me how to create a jar for this in eclipse, this is only a single java file? package... public boolean accept(File arg0 Changes in Jar and Zip ; In Java SE 6 there are two changes in jar command behavior: Before Java SE 6, the timestamps (date and time) of extracted files by jar... in Java SE 6, they do a change in jar command behavior that is the date quqtion on jar files quqtion on jar files give me realtime examples on .jar class files A Jar file combines several classes into a single archive file. Basically,library classes are stored in the jar file. For more information,please go Could not able to load jar file - WebSevices Could not able to load jar file Hi, I tried to parse the xml file to a java object. I followed the procedure that you have mentioned in the website. I created one batch file that consists of all info button iphone example info button iphone example I'm looking for a simple info button example in iPhone XCode. File Management Example of file. Read the example Read file in Java for more information on reading...Java File Management Example Hi, Is there any ready made API in Java for creating and updating data into text file? How a programmer can write Tomcat jar file issue - JSP-Servlet Tomcat jar file issue Hello All, Currently in my application we...) at com.sun.corba.se.impl.orb.ORBImpl.resolve_initial_references(ORBImpl. java:1157... .java:374) at org.apache.jasper.servlet.JspServlet.serviceJspFile how to get harddisk info using S.M.A.R.T using java how to get harddisk info using S.M.A.R.T using java how to get harddisk info using S.M.A.R.T using java Fat Jar Eclipse Plug-In deploys an Eclipse java-project into one executable jar. It adds the Entry "Build... contains all needed classes and can be executed directly with "java -jar... Fat Jar Eclipse Plug-In   java binary file io example java binary file io example java binary file io example Ant make directory with relative path , how to compile java file and how to create jar file. This is a simple program... file. In this example five targets are used, the first target <target name="...; is used to compile the java file and copy the class file in build directory Java FTP file upload example Java FTP file upload example Where I can find Java FTP file upload...; Hi, We have many examples of Java FTP file upload. We are using Apache... Programming in Java tutorials with example code. Thanks jar file jar file jar file where it s used util How to generate build.xml file you make a java file in the src folder and run with ant command, the jar file...; This example shows how to generate the build.xml file. You...; <jar jarfile="${dir.dest}/roseindia.jar" basedir=" Java util date Java util date The class Date in "java.util" package represents... to string and string to date. Read more at: http:/ The "isThreadSafe" & "info" Attribute of JSP page directive ="text" %> Example : <%@page info="This is the example of info attribute of the page directive." %>  ...;info "attribute of JSP page directive. The "isThreadSafe" jar file built by ant jar task does not have all the dependant jars and throws exception while reading the appplicationContext,xml ;/target> While executing the jar file using java -jar command it is throwing...jar file built by ant jar task does not have all the dependant jars and throws... applicationContext.xml . My intention is to jar this main class along with its dependant how to return to main menu after adding all the info. - Java Beginners how to return to main menu after adding all the info. import java.util.Scanner; public class RegistrationSystem { public static void main(String[]args){ Scanner scan = new Scanner(System.in); int menu = 0 file in java - Java Beginners file in java I want to count the number of white line and comment line in a file (.sql) with java if you have an example thank you in advance how to create .exe file of java application?? - Java Beginners how to create .exe file of java application?? hi i want to know how... createJarArchive(File jarFile, File[] listFiles) { try { byte b...(); fout.close(); System.out.println("Jar File is created successfully Extract Jar File Extract Jar File How to extract jar file? Hi Please open the command Prompt and to the jar file and write the command jar -xvf JaraFileName.jar Directory and File Listing Example in Java C:\nisha>java DirListing example myfile.txt... specified a directory name "example" that contains only a single file "myfile.txt". Download this example Example Executale File - Java Beginners for java but you can create an executable jar file .create a MF file...Executale File Plz tell me how to convert java file into .exe file... the instruction.. Good Luck i don;t know how to create the exe file for java   The info Attribute of page Directive In JSP is the JSP code: <%@page info="This is the example of info attribute...; <% out.println("Example of the info attribute of the page directive... The info Attribute of page Directive In JSP   developed a project in J2SE.I am creating a JAR file of it but I am facing a problem...\jarfile\shell\open\command REG_SZ "C:\Program Files\Java\j2re1.4.1_03... is wrong. What is the meaning of this msg? My JAR file is created but Manifest Java - Java Beginners from // the Java Archive file "grfingerjava.jar" //This jar archive, in turn...Java how can i make this java program open an image file and open a website like yahoo? GrFinger Java Sample (c) 2006 Griaule Tecnologia Ltda FTP File Upload in Java FTP File Upload in Java This tutorial shows you how you can write Java program... easy to write code for FTP File Upload in Java. I am assuming that you have FTP... will be able to create programs in Java that uploads the file on FTP server Page Directive attribute - info about the page" %> Example : <%@page info="This is info...Page Directive attribute - info This tutorial contains description of info attribute of page Directive. info Attribute : info attribute of page org.apache.commons.collections15.Transformer jar file org.apache.commons.collections15.Transformer jar file Dear, Please can you provide me the link for the following jar file: import org.apache.commons.collections15.Transformer; tahnks too much how to count no.of sheets in excel through POI jar as well as through Java? how to count no.of sheets in excel through POI jar as well as through Java... will be dynamic ) .I want to read all sheets one by one in java by using POI jar. I... know the method to count the no.of sheets in excel through POI jar or else java JDOM example in java, How to read a xml file in java. JDOM example in java, How to read a xml file in java. In this tutorial, we will see how to read a xml file in java. Code. Student.xml...; File file = new File(data Creating an executable jar file Creating an executable jar file When I try to create jar.exe through CMD, the manifest file created doesn't contain Main-Class attribute, even though it is included in text file used during creation of jar file
http://www.roseindia.net/tutorialhelp/comment/84187
CC-MAIN-2014-23
refinedweb
2,513
65.62
Debugging tips Programs are like kids. You're at your home/office playing around, see how your baby grows, does all these nice things you taught it to do, and feel so proud when it succeeds. It reflects you so well, for the better & the worst. True, somethings it misbehave and make you regret that late drunken night it all started at, but at the end you're creation is all grown up and needs to go out to the world. Well all was nice & cozy back home, but its a jungle out there! Bullies will try to hurt it, viruses will try to kill it, and all those damn users just don't understand how to tread it right... So, when you release your baby out to the world, make sure its damn ready. And when it comes back home all banged up - patch it up fast all send it out there again, because mammy & daddy are working on a new one now and don't have time for this kind of crap. The Debug process The basic steps in debugging are: 1. Recognize that a bug exists 2. Isolate the source of the bug 3. Identify the cause of the bug 4. Determine a fix for the bug 5. Apply the fix and test it Pretty simple ahh? But we all know its not as easy as it sounds. The hardest parts are 2 & 3. This is where you bang your head at the table and regret the day you choose to be a programmer. Luckily, there are ways to soften that processes. At this doc, we'll go over some. Tools The difference between a pro and an amateur is that a pro knows how to use his tools. Its easier to kill a bug with an exterminator that with a flip-flop. But keep in mind its easier to kill it with the flip-flop than drive it over with a truck. And if you aim is off, non of them will help you. Choose you tools wisely, learn how to use them correctly. When used right, tools will help use complete the job faster & better. Loggers allow us to to see what a program is doing just by observing from outside. When logs are kept & well maintained, it will also allow us to see what the system did in the past. When something is logged, it is written into the corresponding log file, if the log level of the message is equal or higher than the configured log level. Most common log levels (ordered by severity) are :debug, :info, :warn, :error, :fatal, but most loggers will allow you to add your own levels & tags. Loggers affect programs performance in two aspects: - IO - Logs are written to disk. When IO is massive, it can become a bottle neck at your OS/Network, which can impact your program performance. - CPU/RAM - Strings are written to the log. If we convert complex objects to strings, it takes its toll on the OS. Reading a log should give you a clear indication of what is going on at the system. A log entry should be informative. It should be easy to understand: - Where in the code this log entry was created at. - Which system/module/process generated it. - When & in what order the events happen. - What exactly happened. You can achieve most of it by - Add the Module & Method name to the log entry - Print parameters & variables - Use log levels wisely. In order to minimize the Logger impact on your system: - Avoid logs in a loop - Avoid logs that require stringify/parsing of big data structures Lets consider the following code module MyMath def add(x, y) return (x.to_i + y.to_i) end end module MyCalc def awesome_calc(args) ... MyMath.add(x, y) ... end end Our program which uses the MyMath module, is misbehaving. Some users complained that sometimes the program returns the wrong result. After more questioning, we know the exact input the user entered. We are able reproduce the bug, but see no errors/exceptions raised. All we can to do is start probing around at the code, while running manual tests. How can we prevent, or at least reduce the debug cycle of such scenarios? Methods have input, and output. If we know what goes in & out of them, we can tell if they work properly. This is why often while coding & debugging we find ourselves adding prints to the code like so: # coverts 2 strings to integers and performs addition. def add(x, y) puts "x=#{x}" puts "y=#{y}" puts "x+y=#{(x.to_i + y.to_i)}" return (x.to_i + y.to_i) end Those kind of prints are very helpful while developing/debugging, but pretty annoying for when comes in masses. This is why prints are required to be deleted - in order to keep our system logs clean. Using loggers debug mode allows us to eat the cake and leave it whole - use our prints, but only when needed. def add(x, y) @logger.debug("MyMath.add(#{x}, #{y})") res = (x.to_i + y.to_i) @logger.debug("MyMath.add: res = #{res}") return res end Now by simply viewing the log we can pin point the error, looks like someone is misusing the the MyMath.add method and feeding it the wrong input. Apr 24 04:01:20 [debug]: MyMath.add(3, _2) Apr 24 04:01:20 [debug]: MyMath.add: res = 0 We can even improve that by adding a warn message def add(x, y) @logger.debug("MyMath.add(#{x}, #{y})") @logger.warn("MyMath.add: invalid input x=#{x}") unless valid_arg(x) @logger.warn("MyMath.add: invalid input y=#{y}") unless valid_arg(y) res = (x.to_i + y.to_i) @logger.debug("MyMath.add: res = #{res}") return res end Now by just viewing the logs, we can see the issue. Apr 24 04:01:20 [debug]: MyMath.add(3, _2) Apr 24 04:01:20 [warn]: MyMath.add: invalid input y=_2 Apr 24 04:01:20 [debug]: MyMath.add: res = 0 Debuggers allows us to see what a programs is doing from the inside. Different debugger have different capabilities but usually you can find the same basic features at each. Breakpoint allows stopping or pausing place in a program. A breakpoint consists of one or more conditions that determine when a program's execution should be interrupted. the basic condition is line number, but we can add more sophisticated conditions. once the programs is paused, we can follow each line/frame/block of code and see exactly whats going on. We can evaluate different variables, run queries, check performance... all in order to find out what our program state. Byebug, for example, is a great debugger for Ruby. see byebud_demo.rb for a live demo. require 'pry-byebug' def count_down(x) p "#{x}..." return true if x <= 0 count_down(x - 1) end byebug bomb = { sound: 'BOOM' } count_down(5) p bomb[:sound] Linters are programs that analyze code for potential errors. Simply put, a parser parses your code and looks for mistakes. It saves time & maintain code quality/safety. Most editors will allow us to integrate linters as plugins, but we can use them as stand alone to automate scripts of our own. Linters have a wide range of abilities: - Detect logical errors (such as missing a comma or misspell a variable name) - Detect code anti-patterns. - Detect syntax error. - Detect deprecated code usage. - Suggest code optimizations. - Some Linters will even do those fixes for you. For example, a linter will prevent the classic mistake of global variables at JS function (){ i=0; ... } or useless assignments at ruby obj = do_some_heavy_calc() ... obj = [] A validator is a program that can checks your web pages against the web standards. It is easy to miss a closing tag or misspell attribute, and very hard to find once its there. Most of the time it leads to visual bugs. Visual bugs can be hurt UX so badly that it will affect you app drastically (for example, a user that can't click a submit button of a form). HTML will work, somethings even look pretty good, when there are some major issues with the page structure. To make things even more challenging, different browsers deal with such invalid structure differently, so you page can look great on one, but totally deformed on other. Plus, Visual bugs are the ones makes you look bad & unprofessional just because there very easy to spot by the end user. The user doesn't thinks 'boy, I shouldn't view this site with Opera 9, maybe I'll switch to chrome 47'. He will probably think 'Man those guys are idiots over there' and move on to our competitors. Formatters are programs that analyze code, and fix them automatically according to style conventions. Formatters will remove all the annoying 'ugly code' for you. don't spend time on fixing indentations, white spaces, and match brackets. Focus on what you write, not who it looks. Since Linters warn about style issues, formatters help reduce lint errors too. Bugs are 99.99999% human error. someone wrote a piece of code that is misbehaving. Version Control keeps our code history. By reviewing the history we can tell who changed what & when. git commit In order to make the best of it, first we should be descriptive at our commits messages. Commit messages like git commit -am 'fix' are pretty useless... Messages should be informative: - What feature does this commit relate to? - Is there a task id that we use to manage our work? include that too. - Describe what changes does this commit bring to the project. - Make sure your username & email are set correctly git config -l - Keep commits small. commits that includes many code changes are hard to follow/describe. This way, our commit will look more like commit 0196feb6de1e75f44ca05ebb6f25bf235acc21b8 Author: Guy Yogev <[email protected]> Date: Wed May 4 12:17:42 2016 +0300 TASK-87 - Fix download buttun action. At User page, `download` button didn't work due to of missing 'id' parameter at request params. added user params to request. Now that our commits contains some actual useful data, how can we find the relevant commit? git log Displays latest commits to the repo. git blame Shows who was the last to make changes to the viewed code, and at which commit. git bisect Does a binary search on the commits. - git bisect start - start the bisect - git bisect bad - marks the current commit as bad, meaning the bug exists. - git bisect good <COMMIT_ID> - makes the commit as bug free, (for example the last stable version that was marked with the git tag cmd) - git bisect check out to the middle commit. Keep marking commits as good/bad till you find the commit that produced the bug. - remmber to use git bisect reset to go back to the starting point, or you'll leave the repo in a weird state. git diff Displays the diffrance between 2 commits / branches / files Use the --name-only option to list affected files instead of files content. git show When a lot of changes where done between the two targets, git diff can be too overwhelming. git show displays only changes from the given commit. --name-only works here too. Browsers dev tools All major browsers have developer-tools built-in. Its a wide range of tools such as debuggers, analyzers, recorders, viewers. diving into each one is beyond the scope of this doc. Generally speaking, those tools provide web developers deep access into the internals of the browser and their web application. It helps us efficiently - Track down layout issues - Debug JavaScript breakpoints - Get insights for code optimization via audits. Culture A single developer can work very fast & efficiently, but there is a limit. At some point the project is simply too big/complicated for a single developer to manage & support. Working as a team requires good communication & following agreed guidelines. As our software gets bigger & bigger, the code base increases. Vendors code is integrated & open source code is added. As the code evolves, it accumulate more and more bugs. - When a bug is found, minor or major, make sure it is tracked. - Minor bugs can be ignored for a while, but can also mutate into a more serious issue. - Open a task. Write everything you found relevant during your investigations for future usage. - Keep vendor/open source code updated. - Keep track on your vendors blogs / press releases. - View the change log of new releases. - Review the external projects open/close issues. - Upgrades can contain bug fixes. - Upgrades can introduce new bugs too, run sanity tests before committing code upgrades. Ok, we use all those awesome tools now know where the bug is generated. Time to pin point the issue and find a solution. Debugging is hard. We need to keep our mind sharp. - Take breaks - Find a quite place to work. - Ask not to be disturbed. In order to find a solution, we first need to define the problem. We all had that experience when a solution emerges while you try to explain the problem to someone else. You don't need their input, just someone to talk to aloud while you gather your thoughts. Studies that objects can be as effective as a humans for that purpose, So... why not talk to a rubber duck or a teddy bear? Well, even your duck wasn't very much helpful... Time to leverage other people knowledge & experience. - Decide for how long you're going to pursue leads on your own. - Keep in mind that others are busy too. Try to find leads at forums / blogs before approaching a co-worker. I find the 'Try everything from the first Google page' rule pretty useful. - Once you got someone attention, let them find their own way. - Explain what is wrong, not what you did. Let others find their own way. - Be patient, nobody likes helping a jackass. Bugs appear when the programs is in some state - Every time that state applies, the bug will appear. Sometimes it requires a few simple steps to put the system in the buggy state. A click of a button, or a flag change and you're done. In other cases, getting there can be quite a journey. You'll need to repeat multiple changes every time in order to see & test the bug. This is just white noise for the debugging process. Plus, when we have multiple actions to complete each run, it is easy to miss one, and get to a totally different state. Automation helps us to remain focused on the stuff that matter. We can reproduce/test our bug fast. - Write a script that will change your programs state. - Write an automated test for that bug. - Automate casual state changing tasks such as db seeds/resets/cleanups/backups. - Automate devOps tasks such as deployment, e2e/smoke tests. Code is almost never written just once. Most of the time, someone (maybe even you) will need to work on that piece of code at some point..” But why should you care? What’s wrong with code that just works? - 'Clean code' contains less bugs, easier to understand & debug. - 'Dirty code' is hard to handle & maintain, and in time will 'rot' due to abandonment. More tips: - The five-minute rule - if you find an ugly piece of code that can be fixed very fast, do it. - Always improve yourself. if you are not happy with your current work, improve it, or at least understand what is wrong. next time, do it better. Programs are divided into modules. Every module has its role and purpose. It helps you keep DRY principle and code quality. Some tasks can be quite complex, and won't be completed in one coding session. We want to make sure that if & when we drop or hand over a task to someone els, it will be easy to pickup. Overall, sound architecture also prevents bugs. When program parts are not well defined/written we start seeing mutant modules that does many things, code duplication, and spaghetti code. Before racing ahead and writing hundreds of lines of code, take some time an ponder about the task at hand. - How does it fit the 'big picture'. - What are the feature requirements exactly? - Do I have sufficient knowledge in order to complete the task, or need more time for research. - What are the feature components and how they interact with each other. - Can I reuse/expand any other modules? - Break the tasks into a road-map. Define were are the main break points. When you reach a break point, ask your self if you have the time to reach the next one or not. Code review is systematic examination of the source code. Its main goals are find developers mistakes before the code is deployed and mutate into a full grown bug. There are a few type of code reviews - Over-the-shoulder – one developer looks over the author's shoulder as the latter walks through the code. - Email pass-around – source code management system emails code to reviewers automatically after commits is made. - Pair programming – two authors develop code together at the same workstation, as it is common in Extreme Programming. - Tool-assisted code review – authors and reviewers use software tools specialized for peer code review. Studies show that lightweight reviews uncovered as many bugs as formal reviews, but were faster and more cost-effective. - Use tools (like version control) to see code changes. - Review the code while its fresh. - Sessions should be brief, no more than an hour. - Cover 200-400 line per session. - Cover everything. Configs, unit tests are code too. There are lots of reasons why we should automate tests. You can read more about it at a previous post here The main argument you hear against it is - 'it takes too much time'. Unit tests are usually an 'easy written' code, therefore, it is written much faster than production code. Studies show that the overhead on on the development process is around 10%. Well, let me assure you - debugging takes much longer. Resources
https://www.spectory.com/blog/Debugging%20tips
CC-MAIN-2019-18
refinedweb
3,022
75.81
[ ] stack commented on HBASE-8699: ------------------------------ I think you need test to prove that regex finds the right versions. Just do a little method in here in your test. Why we do it like this: {code} + @Test + public void testExistenceOfIsFileClosed() throws IOException { + String hadoopVer = VersionInfo.getVersion(); + // known versions where DistributedFileSystem supports IsFileClosed(Path) + final Pattern knownVers[] = { + Pattern.compile("1\\.2\\."), + Pattern.compile("2\\.1\\.") + }; + for (Pattern pat : knownVers) { + if (pat.matcher(hadoopVer).matches()) { + try { + DistributedFileSystem.class.getMethod("isFileClosed", new Class[]{ Path.class }); + break; + } catch (NoSuchMethodException nsme) { + throw new IOException(nsme); + } + } + } + } {code} Why not just do reflection to see if method is there? Skip the test if it is not present? What about hadoop 3.x? What is this test doing? Testing that a hadoop version has isFileClosed? Do we care? Either it is present or it is not. If it is not present when we expect it in a particular hadoop, what will we do? Why not add a unit test for all methods we expect in hadoop? Remove it I'd say? We will do this reflection (and fail most of the time, at least currently) whenever we make this call? {code} + + Method isFileClosedMeth = null; + try { + isFileClosedMeth = dfs.getClass().getMethod("isFileClosed", new Class[]{ Path.class }); + } catch (NoSuchMethodException nsme) { + LOG.debug("isFileClosed not available"); + } {code} Why not do it on instantiation once? > Parameter to DistributedFileSystem#isFileClosed should be of type Path > ---------------------------------------------------------------------- > > Key: HBASE-8699 > URL: > Project: HBase > Issue Type: Bug > Components: wal > Reporter: Ted Yu > Assignee: Ted Yu > Attachments: 8699-v1.txt, 8699-v3.txt, 8699-v4.txt > > > Here is current code of FSHDFSUtils#isFileClosed(): > {code} > boolean isFileClosed(final DistributedFileSystem dfs, final Path p) { > try { > Method m = dfs.getClass().getMethod("isFileClosed", new Class<?>[] {String.class}); > return (Boolean) m.invoke(dfs, p.toString()); > {code} > We look for isFileClosed method with parameter type of String. > However, from hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java (branch-2): > {code} > public boolean isFileClosed(Path src) throws IOException { > {code} > The parameter type is of Path. > This means we would get NoSuchMethodException. -- This message is automatically generated by JIRA. If you think it was sent incorrectly, please contact your JIRA administrators For more information on JIRA, see:
http://mail-archives.apache.org/mod_mbox/hbase-issues/201307.mbox/%3CJIRA.12651371.1370535198672.15513.1373331590034@arcas%3E
CC-MAIN-2018-13
refinedweb
366
53.17
BBC micro:bit Gesture Detection Introduction In this project, we extend the functionality of our serial port connection program to allow us to read button presses and gestures on the micro:bit. For this project, you need to have Visual Basic (any of the free versions) installed on your PC. You also need a serial port driver. MicroPython The first that we need is a Python program that will make our micro:bit send readings to the serial port. This program encodes the accelerometer gestures and button presses in the first 6 bits of a byte of data. This information will be sent as characters but it will be possible for us to perform a neat conversion in Visual Basic. from microbit import * while True: bite = 0 if accelerometer.was_gesture("up"): bite = bite + 1 elif accelerometer.was_gesture("right"): bite = bite + 2 elif accelerometer.was_gesture("down"): bite = bite + 4 elif accelerometer.was_gesture("left"): bite = bite + 8 if button_a.was_pressed(): bite = bite + 16 if button_b.was_pressed(): bite = bite + 32 print(bite) sleep(50) If you can't follow how this program will work, look up how to encode numbers using 8 bit binary. By adding the place values to the variable, we are setting certain bits to equal 1 when the gesture is detected. Visual Basic - Form Design This code is built on top of the serial port program mentioned at the start of this section. The output TextBox has been resized and 6 labels have been added. I have messed around with the properties of the labels, changing autosize to false and making some formatting choices. The labels are named as follows, - lblA - lblB - lblUp - lblDown - lblLeft - lblRight Visual Basic - Programming The only changes to the program that are needed are in the ShowString() procedure that outputs the data received on the serial port. These changes are as follows, Sub ShowString(ByVal myString As String) txtOutput.AppendText(myString) Dim bite As Byte Try bite = CByte(myString) Catch ex As Exception Exit Sub End Try Dim labels() As Label = {lblB, lblA, lblLeft, lblDown, lblRight, lblUp} For i As Integer = 5 To 0 Step -1 If (bite And (1 << i)) <> 0 Then labels(5 - i).BackColor = Color.Yellow Else labels(5 - i).BackColor = Color.White End If Application.DoEvents() End Sub If you watch the output you get in the TextBox, you will notice that reading serial data is a bit hit and miss. The error handling code is there to make sure that our program does not get into a pickle if the data received are not quite what was expected. Run the program and make a connection to a micro:bit running the MicroPython program from the top of this page. Pressing buttons and making gestures should result in the correct label lighting up for you. Button presses are always registered, only one accelerometer gesture can be received at a time. In the screenshot, the byte that was received last was equal to 24. This meant that button A was pressed (16) and the accelerometer was tilted to the left (8). Challenges This page is about experimentation. It proves that the concept is workable. You can pick up accelerometer gestures on the micro:bit and send them via USB to a Visual Basic program. That is enough reassurance to make it worth embarking on a more complex Visual Basic project that makes use of the micro:bit as an input device. If you change the Python program on the micro:bit, you can send the raw readings from the accelerometer and view them in real time in a Visual Basic program.
http://multiwingspan.co.uk/micro.php?page=vbacc
CC-MAIN-2017-22
refinedweb
600
62.98
InvokeRecurrenceRuleLimit Since: BlackBerry 10.3.0 #include <bb/system/InvokeRecurrenceRuleLimit> To link against this class, add the following line to your .pro file: LIBS += -lbbsystem The possible limits that are used in an InvokeRecurrenceRule. Overview Public Types Index Public Types The possible limits that are used in an InvokeRecurrenceRule. BlackBerry 10.3.0 - None 0 No limit. - Count 1 Count limit. This limit guarantees that the recurrence rule will no longer be applied after it was triggered the specified number of times.Since: BlackBerry 10.3.0 - Date 2 Date limit. This is the time at which the recurrence rule will no longer be applied.Since: BlackBerry 10.3.0 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/cascades/bb__system__invokerecurrencerulelimit.html
CC-MAIN-2015-18
refinedweb
126
63.25
I am trying to obtain a string from the attributes of the changegame async def changegame(*game_chosen: str): """Changes the game the bot is playing""" game_str = discord.Game(name=game_chosen) try: await bot.change_status(game=game_str, idle=False) await bot.say("```Game correctly changed to {0}```".format(game_chosen)) Game correctly changed to ('Test', 'string', '123') To solve your initial issue, try a simple join: ' '.join(map(str, game_chosen)) However, your bigger problem is: game_str = discord.Game(name=game_chosen) Here you are passing a tuple to discord.Game, are you sure this is right? If you want to call your initial function like this: changegame("League of Legends"), then you need to fix your function definition: async def changegame(game_chosen: str) I suspect this is what you are actually trying to do.
https://codedump.io/share/lTulwkDjc00s/1/how-do-i-join-the-args-of-a-function-to-form-a-string
CC-MAIN-2017-04
refinedweb
131
67.45