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 |
|---|---|---|---|---|---|
Oskari Saarenmaa <o...@ohmu.fi> writes: > On Sun, Dec 22, 2013 at 09:43:57PM -0500, Robert Haas wrote: >> - Why change the API of transformRelOptions()?
Advertising
> The comment was changed to reflect the new API, I modified > transformRelOptions to only accept a single valid namespace to make things > simpler in the calling code. Nothing used more than one valid namespace > anyway, and it allows us to just use a constant "toast" without having to > create a 2 char* array with a NULL. That may be true today, but the code was obviously designed to allow for more than one namespace in the future. I'm inclined to reject this part of the patch, or at least rework it to const-ify the existing data structure rather than editorialize on what's needed. However, I believe this code was Alvaro's to begin with, so I'd be interested in his opinion on how important it is for transformRelOptions to allow more than one namespace per call. Actually, I'm kind of wondering why the code has a concept of namespaces at all, given the fact that it fails to store them in the resulting array. It seems impossible to verify after the fact that an option was given with the right namespace, so isn't the feature pretty much pointless? regards, tom lane -- Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org) To make changes to your subscription: | https://www.mail-archive.com/pgsql-hackers@postgresql.org/msg230704.html | CC-MAIN-2018-26 | refinedweb | 239 | 59.23 |
Provides scheduled jobs from the Django Admin using Django-RQ
Project description
Provides scheduled jobs management from the Django Admin using Django-RQ
Admin Screenshot
Installation
Make sure you have Django-RQ up and running before you do anything. This app is just a simple admin plugin to manage your scheduled tasks and management commands.
Install the package with pip install django-rq-jobs
Add django_rq_jobs to INSTALLED_APPS in settings.py:
INSTALLED_APPS = ( # other apps "django_rq", "django_rq_jobs", )
Add RQ_JOBS_MODULE in settings.py. A string or a tuple of strings designating all modules where you keep your jobs. Anything marked with the Django RQ’s @job decorator will show up in the admin.
# A singe module: RQ_JOBS_MODULE = 'myapp.tasks' # or with multiple modules: RQ_JOBS_MODULE = ( 'myapp.tasks', 'anotherapp.tasks', )
Run python manage.py migrate to create the job model.
Open your Django admin and find the RQ Jobs scheduled job section and schedule something.
Schedule the heartbeat python manage.py rqjobs with your favorite scheduler. This can be cron, Heroku scheduler or anything else you prefer. Make sure you set the heartbeat interval to something sensible; 5 or 10 minutes is usually enough, but run it every minute if you want. Execution of the jobs is deferred to RQ anyway.
Notes
- Supports once, hourly, daily, weekly, monthly, quarterly and yearly scheduled tasks.
- Limited run schedules: Set the ‘Repeats’ on a task to the maxium number of repeats you want. The task gets deleted once the counter reaches zero. Defaults to -1 for eternal.
- Arguments are a dict: {'one': 1, 'two': 2, 'three': 3}
- RQ Jobs will try to link a job to a queue task status in Django RQ. Usually these job reports don’t exist much longer than a few minutes unless they fail. So if you are seeing None in the RQ status, that usually means things went well.
- If you haven’t run the heartbeat manage.py rqjobs for a while and missed some scheduled jobs, RQ Jobs will play catch-up with every heartbeat. This way limited run schedules don’t get compromised.
Scheduling Management Commands
If you want to schedule regular Django management commands, it’s easiest to add them using Django’s management wrapper. So if you wanted to schedule `manage.py clearsessions’ :
from django.core import management @job def clear_sessions(): return management.call_command('clearsessions')
This will automagically appear as ‘Clear Sessions’ in the admin interface.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-rq-jobs/ | CC-MAIN-2021-10 | refinedweb | 422 | 67.76 |
Socket.IO - What, Why and How?
Mohd Shad Mirza
Updated on
・5 min read
This.
Why Socket.io?.
What is Socket.io?.
By definition.
How?
I'm assuming you've read the first part and know the working of native WebSockets. Let's quickly upgrade that to Socket.io.
Commented code is WebSocket usage. I've added it for comparison.
Server
Explanation
- Instead of importing websocket from 'ws', we're importing socketio from 'socket.io' library.
- Creating a server and handing it to socketio instead of websocket.
- Instead of 'send', we're now using 'emit' function on 'io' object. The only difference is we have added event name as the first argument. We'll use this event name to retrieve the message at the client's end.
- Method 'on' still works the same, the only difference is the addition of event name. Simple enough?
Client
Explanation
- Importing 'socket.io' library as it is not provided by JavaScript out of the box. This will expose 'io' namespace.
- Providing url for io to connect. (We are not using new keyboard unlike WebSocket usage because it is optional. It's up to you if you wanna use it or not.)
- Again 'send' is replaced by 'emit' and we have added event name (check line 21 of Server part).
- Method 'on' is still the same with the addition of event name (check line 20 of Server part). Makes sense?
Cheers! We have created our simple Socket.IO Server and Client.
I've tried to keep things as simple as possible. We'll dig deeper into Socket.IO in the third part of this series. Let me know if this was helpful.
Shad
Reference
- Socket.IO Server API -
- Socket.IO Client API -
How to use socket io for larger projects which has more number of concurrent users?
Currently I am facing lot of memory related issues with socket io. Is there any way kill inactive socket clients at NodeJS level?
Hi jeyaraj, tbh I have never used socket.io at a large project. I have just started to use socket.io (currently playing with slack clone) and thought to share my learning strategy along the way. But still, I will look out for this issue and let you know if I can find something.
This reason was the most critical one behind my announcement of the neffos real-time framework (github.com/kataras/neffos).
Good stuff mate!
Thank you vaibhav. 😄 | https://dev.to/iamshadmirza/socket-io-what-why-and-how-2cjb | CC-MAIN-2019-35 | refinedweb | 405 | 70.29 |
Inspiration to reset your biological body clock and improve your health and sleep hygiene with Arduino
A Circadian clock is NOT a clock we look at to tell the time. It is rather a timekeeper and an oscillator within our body organisms to coordinate the biology and behavior with daily environmental changes in the day-night cycle.
The normal body clock oscillates with a period of around 24 hours when it receives daily corrective signals from the environment, primarily daylight and darkness. Circadian clocks are the central mechanisms that drive circadian rhythms.
The circadian clock is intertwined and regulated with light and even the smallest night light as pilot lights interfere with this rhythm. That is why I have created a clock that simply turns off the backlighting for 8 hours enabling you to do your own research or just use it to correct your own circadian clock.
I hear often from friends and family that their children do not sleep well at night and ask if they leave the lights on at night. As this could impact on their children’s sleeping disorder.
The body.
Wikipedia also says:. The subjects were allowed to turn on....
Light and the biological clock
Light resets the biological clock depending on the timing. Light can advance or delay the circadian rhythm. The required illuminance varies from species to species and lower light levels are required to reset the clocks in humans.
A short period of sleep during the day, a power-nap, does not have any measurable effect on normal circadian rhythms but can decrease stress and improve productivity.
The circadian clock oscillation is intertwined and regulated with light and even the smallest standby light interferes with this rhythm. Managing to adjust the body oscillation may help circadian rhythm disorder, insomnia, delayed sleep phase disorder, Airline pilots who are often unable to maintain sleep patterns. This all may help health in general or perhaps helps cancer researchers to look into a different direction....
Circadian rhythm abnormalities are also extremely common. Just look into our own bedroom where modern technology moved in with mobile phones and PC tablets that receive text messages and turn the screen lights on and making sounds waking us running 24 hours nonstop.
This knowledge inspired me to construct what I call a Circadian Clock?
As we now know that light is a factor in adjusting the circadian clock, all lights and standby lights in the bedroom must be turned off including the backlight of your alarm clock.
I have constructed and Arduino based clock with LCD screen for this sole purpose that simply turns off the backlighting for 8 hours from 10 pm to 6 am.
It is adjustable in the software with detailed instructions on how to adjust the backlight to your liking. The backlight can be dimmed in the evening and (or) completely turned off for 8 hours or more to have a good night sleep and feel refreshed in the morning.
In this instructable and the Arduino Uno sketch file, I have included a clock, hygrometer and a calendar at the same time. If you do happen to wake up at night and like to see what time it is, you can install a button on your bedside or directly on the clock to turn the backlight on for an adjustable time.
On the LCD screen you have:
· hours
· minutes
· day
· temperature
· humidity
· then it briefly switches to month and year ( not working while I begin writing this instructable)
I had first heard of this when I was reading a book on health,
called Sugar Dreams by Monica Colmsjö
She says: Sugar is more addictive than cocaine?
My brother is a professor at the Stockholm University and he made sure I had references to all the data!!
Then I did my own research with Dr. Google. But only when I had help with the software, I was able to make this instructable.
The ino file was professionally edited to suit.
Step 1:
Construction
The easiest LCD circuit without too many wires hanging all over the place is from
my friend Sagar who created Buildcuircuit.com using a small board and a Atmega 328P.
The same chip the Arduino runs on....
Originally this kit came from Sparkfun US $24.95. A lot of things can be made with it.
I also have everything you need in stock
The kit sells for AU $19.95 free freight within Australia email me for the lot
And Sagar has a better ADD TO CART website for the Kit and instructions on the kit AU $ 19.95.
The 16 x2 LCD display comes with the kit.
· 1 Kit or Arduino and LCD display.
· 1 clock DS3231_I2C eBay $ AU 1.14
Battery for the clock LIR2032 3.6 Volt (The coin cell battery that size you get in every shop has 3 Volt and does not work with the clock. This battery keeps the clock running when you turn the power off for another year. Or solder CR2 3V Lithium Camera Battery on to the clock battery terminals. Jaycar.
· 1 humidity meter white in colour DHT22 ( avoid the old model in blue (DHT11)
· Some connector wires
· 1 momentary switch
· 1 power supply 5V DC (The LCD kit has no power control and only takes max 5 Volt DC)
· Box for mounting.
· On off switch is optional
· Programmer $15.95 to avoid taking the chip out and program it in your on your Arduino UNO...
The programmer comes with cables.
When I did not know about the battery I got myself a 3.6 volt battery at 1.2 Ah from Jaycar that may last 10 years.
My laser cut box was made form Jim at
Jim mainly deals in fine stainless steel but may make an exception to cut in timber.
Step 2:
The Arduino Atmel 328P code
Assuming you have the Arduino IDE 1.6.5 installed or younger. NOTE THAT 1.6.6 and 1.6.7 have bugs and add more problems than you want especially when we are using other programmers to upload.
in the code you need to adjust:
- #define DHT22_PIN 1 // change pin number to your input pin of humidity DHT22
where do you connect your DHT222 humidity meter to. I have pin 1
- #define THERMO A1 // external thermostat ,also adjust in line 223
- #define BUTTON A0 // where you connect your button switch to grounded with a 10K resistor to ground
#define LIGHT_PIN 9 // the pin that turns on your backlight
int interval=30000;// **** 30seconds x 1000 ***user define back light time when the button pushed****
// this array contains the brightness values for each hour there are 24 hours
// starting from 1am . 0 is off and 255 is fully on. int led_brightness_data[24]={0,0,0,0,0,0,250,250, 230,220,150,150,160,170,180,190, 200,190,180,170,160,0,0,0};
This looks complicated but is easy to work out.
1pm 0 sets the backlight to LOW. LOW turns the backlight off.
2am 0 =LOW up to 6pm it stays LOW
Than at 7am it wakes up ( but has no alarm) and turns the backlight on .
The value 250 is an analog PWM value . 0 off to 255 fully on.
Then different brightness during the day you can change and finally at 10pm a zero value turning the backlight off for 8 hours.
This circuit has no alarm as everyone uses their phone these days as alarm.
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(2, 3, 4, 5, 6, 7, 8 ); //correct for builtcircuit.com.au kit //change to your crystal pin out
- and pin 9 is the backlight pin
- lcd.print("Sunday"); // here you can put ("Sonntag") or other languages to suit your needs wanted on the LCD screen. The same for month.
- nothing else to change till the end of 2999. lcd.print("20"); //year 2015 as the code on prints the last two digits.
lcd.begin(16, 2); this for the LCD screen 16 columns and 2 rows
if you use a bigger LCD with 4 rows the code looks like this lcd.begin(16,4);
and here the code
Now you need a code to set the clock
Step 3:
If compiling does not work FAULT FINDING
Usually this is due as you did not install the include files into your libraries folder found within the Arduino folder.
#include "Wire.h"
#include <dht.h>
#include <LiquidCrystal.h>
- the library is missing
- the cable used is a charger cable without data connection
- the board chosen is wrong . Choose arduino UNO for the kit
- the port is not set correctly in TOOLS of your Arduino IDE
- you used a programmer and did not set the "USBasp" setting
other problems with the LCD
- the screen is not visible. Solution make adjustments on the trimpot.
Setting the clock
Insert 3.6 V battery first. Use "LIR 2032 3.6 volt battery
Use this code first
// set the initial time here:
// DS3231 seconds, minutes, hours, day, date, month, year
set DS3231time(30,54,21,4,24,6,15); //set the clock here***************
// after setting clock check in serial monitor // sunday is 1, Monday 2 and so on
uncomment this line //
the first number is seconds in my sample 30
the second number is minutes in may sample 54
the third number 21 is hours
the day of the week starts with Sunday =1 Monday=2 in my sample the number 4 is Wednesday
and so on.
This Instructable has no circuit diagram, but you can work it out easily from the code and my instructions on where to connect what.
Good health with your change of your body clock.
Step 4: Improved Code That Displays the Year,day and Month
It has been taking me weeks to improve the code.
The 500 number is the time it displays the
for (unsigned long xy =0; xy< 500; xy++){
lcd.setCursor(0, 1); // prints on the second line
lcd.print("20"); //year 2015
lcd.print(year);
lcd.print(" ");
lcd.print(dayOfMonth, DEC);
}
This part of the code toggles between the temperature and humidity over to displaying the year, day and month and works ok,
BUT in the short time the second line changes, the button for the backlight cannot be used.
also in line 250 I have slowed down the refresh of the display.
wait_on_escape(9000);// for the given time the control has been transfered to this function.
This looks good but , with a longer refresh displaying the time is out by a few seconds.
My programmer does not understand the issue or can fix it.
So any suggestions are welcome.
Apart from some delay issues this code is fine to use in your Arduino IDE.
Discussions
3 years ago
Nice project, very well described and supported with references. I happen to be in a circadian "glitch" right now that has me getting poor sleep - going to read and apply what you've shared! | https://www.instructables.com/id/Reset-Your-Circadian-Clock-biological-Body-Clock-W/ | CC-MAIN-2019-26 | refinedweb | 1,836 | 70.73 |
Download presentation
Presentation is loading. Please wait.
Published byRandolph Richards Modified over 4 years ago
1
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004
2
Introduction to C# What is C# Java like language from Microsoft Object Orientated Language Derived from C++ Has the power of C++ and the simplicity of Visual Basic Part of Microsoft.NET framework If you are serious about.Net you need to learn C#
3
Introduction to C# Can only run on Windows OS Cross Language Able to use objects created in C++.NET and Visual Basic.NET and all the other.NET Languages (or not) Cross Platform What is C# (con’t)
4
Introduction to C# What do you need? –Windows OS Machine. Windows 2000, XP or 2003 –Microsoft.NET SDK –Text Editor Save files with a.cs extension Getting started with C#
5
Introduction to C# What about a development environment? –Visual C++ from Visual Studio 6.0 Requires registry tweaking –Visual Studio.NET –3 rd Party software Emacs and XEmacs Borland Getting started with C# (con’t)
6
C# vs. The World Compilation Process CPU code csc JIT.cs Source Code.exe.dll Microsoft Intermediate Language (MSIL) CLS Compliant Languages How does C# work?
7
C# vs. The World Common Language Runtime (CLR) –Provides an execution engine for developers code Code management (loading and execution) Memory management Garbage Collection Verification of type safety Enforcement of code access security Interoperation between managed code, COM objects, and pre-existing DLLs How does C# work? (con’t)
8
C# vs. The World Hello world using System; class HelloWorld { public static void Main() { Console.WriteLine(“Hello World!"); } >csc HelloWorld.cs >Hello World! The Language (con’t)
9
C# vs. The World Properties public class button { private string caption; public string Caption { get { return caption; } set { if (value != null) caption = value; } button b = new button(); b.Caption = “abc” string s = b.Caption; The Language (con’t)
10
C# vs. The World Parameter Passing The Language (con’t) By Value public static void Swap(ref int x, ref int y) { int z = x; x = y; y = z; } By Reference
11
C# vs. The World Pointers –Not recommended for use public struct Node { public int value; public unsafe Node* next; } The Language (con’t) public unsafe class A {... public class A { public unsafe void B (char *p) {...
12
C# vs. The World The Language (con’t) Boxing / Unboxing –Allows value types to be converted to and from objects automatically ArrayList list = new ArrayList(); int z = 100; list.Add(1); list.Add(13.12); list.Add(z); //integers are automatically boxed //when they are added to the list
13
C# vs. The World The Language (con’t) Delegates –Basically a type-safe object orientated function pointer delegate void simpleDelegate(); Class Test { static void F() { System.Console.Writeline(“Test.F”); } static void main (){ simpleDelegate d = new simpleDelegate(F); d(); }
14
C# vs. The World The Language (con’t) Delegates (con’t) void multiCall (simpleDelegate d, int count) { for (int i=0; i<count; i++){ d(); }
15
C# vs. The World The Language (con’t) Versioning Class B y(); Class A x(); v.1 Class A x(); y(); v.2 Class B y(); Which one to use?
16
C# vs. The World Versioning –C# requires developers to clearly state their intent Use of the keyword ‘new’ and ‘override’ Class Derived B { new public void x () {... Class Derived B { public override void x () {... The Language (con’t)
17
C# vs. The World Libraries The Language (con’t) Few core libraries Uses the libraries from the.NET framework Threading, Collection, XML, ADO+, ASP+, GDI+ & WinForms libraries
18
C# vs. The World Comparison of C# syntax with Java and C++ Similarities Single rooted class hierarchy Similar keywords (derived from C++) Virtual Machine & IL/CLR Garbage Collection No global methods Interface, no Multiple inheritance Exception handling
19
C# vs. The World Comparison of C# syntax with Java and C++ Differences Syntax and Keywords not from C++ Properties, Delegates, Boxing, Pointers, Libraries, etc. Preprocessor Directives
20
C# vs. The World Easy to learn, similar to both C++ and JAVA Can use existing pool of C++ and Visual Basic programmers. Can use components from.NET Syntactical Sugar C# Advantages
21
C# vs. The World Only runs on Windows machines Limited choice in development environment Locked into Microsoft compatibility Not extensively tested Not enough maturity time C# Disadvantages
Similar presentations
© 2019 SlidePlayer.com Inc. | http://slideplayer.com/slide/5951965/ | CC-MAIN-2019-43 | refinedweb | 749 | 57.87 |
Revision history for Perl extension PGXN::Site 0.10.3 2013-11-06T07:22:46Z - Updated Dalibo logo. - Removed sponsors from the home page. Now showing the five most recent releases, instead. - Removed Pod tests from the distribution. 0.10.2 2013-06-19T06:35:03Z - Distribution links in the user page now include the version, so that it links to the latest version of the distribution released by the user, rather than the latest released by any user. - Replaced use of the smartmatch operator with List::Util::first so as to eliminate deprecation warnings from Perl 5.18. 0.10.1 2012-12-12T07:31:22Z - Added an Nginx configuration example to the mirroring page. - Updated GitHub URLs to point to `/pgxn/` rather than `/theory/` (RT #79085). - Set `=encoding` for Pod in PGXN::Site::Locale (RT #79086). - Updated tagline for sponsor Younicycle. - Fixed test failure due to change in behavior in Email::Sender. 0.10.0 2012-01-10T04:37:24Z - Updated links in the About page. - Reversed the display of the browse and download icons for distributions listed on the user page. This is so that they are in the same order as on the distribution page. Per gripe from Marti Raudsepp. - Now showing an error page when the `in` parameter to `/search` is missing, rather than throwing an exception and returning 500. - Added Email::MIME, Email::Sender::Simple, and Software::License to the list of requirements. The were inadvertently omitted. - Added all core and Plack modules to the list of requirements, just to be safe. - Switched to 12 tag cloud sizes and enabled the CSS for the sizes, now that PGXN has enough tags to make it interesting. - Added Identity page a Creative Commons Attribution-ShareAlike 3.0 Unported License, description of fonts, and links to original art work. - Added `Capfile` for capistrano deployment. - Added `eg/debian_init`, an example init script for Debian that runs PGXN::Site on Starman. - Updated the question about a command-line client in the FAQ to point to the client that was actually implemented, rather than the client that was never written. 0.7.4 2011-05-18T17:54:32 - The router tests are now skipped if PGXN::API::Searcher is not installed. 0.7.3 2011-05-18T17:44:31 - Fixed alignment of definition list items on user page. Reported by Daniele Varrazzo (Issue #1). 0.7.2 2011-05-16T20:35:12 - Added Router::Resource to list of requirements. Was inadvertently omitted. - Multiword tags in the tag cloud no longer wrap across lines. 0.7.1 2011-05-12T18:11:02 - Added `use blib` to `pgxn_site_server` so that the server will always find the HTML files generated from the MultiMarkdown source files. - Added namespace::autoclean to prerequisites. Its omission was inadvertent. - Backported to support Perl 5.10. 0.7.0 2011-05-03T02:40:50 - Replaced the gradient background image wih one that uses dithering. This'eliminates banding in the image, which the eagle-eyed Marti Raudsepp noticed and was kind enough to fix. - Added Test::File::Contents to the build prerequisites. Its omission was an oversight. - Replaced `pgxn_site.psgi` with `pgxn_site_server`. This program wraps the functionality of `plackup` to do proper option processing. 0.6.5 2011-04-30T20:04:44 - Added Data::Dump to list of requirements. Was inadvertently omitted. 0.6.4 2011-04-29T21:54:44 - Documentation tweaks. - First release on CPAN. 0.6.3 2011-04-27T18:52:18 - The distribution page now shows the distribution name with the case preserved as found in the distribution metadata file. 0.6.2 2011-04-25T16:35:28 - Fixed offsetting of the "Abstract" item below "Other Releases" in the distribution metadata section of the distribution file. Seen in Firefox on Ubuntu. - All distribution and extension names and versions, as well as tags and user nicknames, are now lowercased for use in URIs. 0.6.1 2011-04-22T18:51:42 - Improved the styling of table headers, as seen in `/spec/` and documentation HTML. - Added a note under the "Distributions" header for users who have yet to release a distribution. - Added redirect from `/meta/spec.html` to the new URL, `/spec/`. - Added links to the Google group to the About and FAQ pages. - Made the background tranparent in `code` elements inside tables. 0.6.0 2011-04-20T05:35:52 - Requests should now all be returned with an appropriate `Content-Length` header. - A search request with no query parameter now redirects back to the home page or, if it's on the same site, the referring page. - Load users starting with a letter from the new "userlist" API. - Updated for PGXN::API v0.12.0, notably changed method names for fetching HTML documentation files in WWW::PGXN and doc path keys. 0.5.1 2011-04-13T18:12:57 - Added the PGXN::Site version string as a query parameter to the CSS URLs. This should force them to be reloaded after the release of any new version by browsers that would otherwise cache them. - Fixed the display of the table of contents sidebar on the documentation page on Firefox. Per gripe from depesz. - Moved the HTML rendering of the spec to /spec/. 0.5.0 2011-04-13T02:25:37 - An invalid search query, such as "*", "", or "?", now returns a 400 response. - Removed `robots.txt` route. This baby's going live tomorrow! - Changed tags on home page to all be the same size and color. Just for now, while there are a limited number of tags all with only one associated distribution. It looks awful when they're all huge and red. - Using the user's profile page for the Gravatar link URL if the user has specified no URL. - Added documentation for all controller action methods. - Added Meta Spec pages (HTML and text). 0.4.0 2011-04-11T23:41:16 - Updated tag cloud and recent releases code to rely on the new files generated by PGXN::Manager 0.11.0. - Added the version to the footer. - Added summary stats to the About page. 0.3.0 2011-04-07T18:19:55 - Renamed "backers" to "donors". 0.2.0 2011-04-07T18:02:50 - Fixed some URIs so that they no longer reveal private URLs from behind a proxy server. That is, all local URLs should be relative to the document root, and not contain the scheme or host name. - Added Gravatar to user page. - Added `reverse_proxy` option, so that the default gravatar URL will work properly for proxied servers. - Added tag cloud to the home page. - Added page with list of recent releases. 0.1.0 2011-04-03T20:24:35 - Initial version. | https://metacpan.org/changes/distribution/PGXN-Site | CC-MAIN-2015-40 | refinedweb | 1,107 | 68.87 |
Technical Blog Post
Abstract
How to ensure that all records in a file contain the required number of characters
Body
Here is a real-world issue that crossed my desk recently: our client received inbound files from trading partners in which each file record needed be exactly 512 characters in length. If a record contained fewer than 512 characters, the record needed to be padded with spaces. One trading partner sometimes sent records shorter than the required length, so the customer needed a means of ensuring that all records were compliant. I thought about this issue and suggested the following code, which is deployed within a Java Task Service:
import com.sterlingcommerce.woodstock.workflow.Document;
import java.io.*;
import java.lang.System.*;
final int MAX_LEN = 512;
final String LS = System.getProperty("line.separator");
Document document = new Document();
Document srcDoc = wfc.getPrimaryDocument();
InputStream is = srcDoc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String thisStr = "default value";
StringBuffer contents = new StringBuffer();
char [] cBuf = new char[MAX_LEN];
char [] tmpArray;
int i;
while ((thisStr = br.readLine()) != null) {
if (thisStr.length() < MAX_LEN) {
tmpArray = thisStr.toCharArray();
cBuf = new char[MAX_LEN];
System.arraycopy(tmpArray, 0, cBuf, 0, thisStr.length());
for (i = thisStr.length(); i < MAX_LEN; i++) {
cBuf[i] = ' ';
}
thisStr = new String(cBuf, 0, MAX_LEN);
}
contents.append(thisStr);
contents.append(LS);
}
br.close();
document.setBody(contents.toString().getBytes());
wfc.putPrimaryDocument(document);
return "OK";
Now that the code was created, a Java Task Service needed to be configured to call it.
This was done via Deployment > Services > Configuration > New Service > Go.
You have a choice of File or Inline for your code. If you choose File, you then specify the name of the file on the File System that contains the code. Choosing File will be necessary if there are many lines of code to be executed. This approach also comes in handy when you are first testing the code, as you can edit the file on the File System without having to go into the Service Configuration should you need to modify the code. In this particular case, though, I chose Inline, as the 31 lines of code were not too unwieldy:
After saving the Service, a simple Business Process allows us to test the service:
<process name="padLineTest">
<sequence>
<operation name="JavaTask Service">
<participant name="padLine_javaTask"/>
<output message="JavaTaskInputMessage">
<assign to="." from="*"></assign>
</output>
<input message="inmsg">
<assign to="." from="*"></assign>
</input>
</operation>
</sequence>
</process>
This scenario may not arise very often, but if it does, these steps may provide the means to work around the issue.
UID
ibm11120719 | https://www.ibm.com/support/pages/how-ensure-all-records-file-contain-required-number-characters | CC-MAIN-2020-40 | refinedweb | 423 | 55.44 |
Collaborative filtering in Keras
Ten years ago, Netflix started the Netflix challenge. A contest to see if the community could come up with a movie recommendation approach that beat their own by 10%. One of the primary modeling techniques that came out of the contest was a set of sparse matrix factoring models whose earliest description can be found at Simon Funk’s website. The basic idea is that the actual ratings of movies for each user can be represented by a matrix, say of users on the rows and movies along the columns. We don’t have the full rating matrix, instead, we have a very sparse set of entries. But if we could factor the rating matrix into two separate matrices, say one that was Users by Latent Factors, and one that was Latent Factors by Movies, then we could find the user’s rating for any movie by taking the dot product of the User row and the Movie column.
One thing that is somewhat frustrating about coding Funk’s approach is that it uses Stochastic Gradient Descent as the learning mechanism and it uses L2 regularization which has to be coded up as well. Also, it’s fairly loop-heavy. In order to get any sort of performance, you need to implement it in C/C++. It would be great if we could use a machine learning framework that already has other learning algorithms, multiple types of regularization, and batch training built in. It would also be nice if the framework used Python on the front end, but implemented most of the tight loops in C/C++. Sort of like coding the algorithm in Python and compiling with Cython.
My current favorite framework is Keras. It uses the Theano tensor library for the heavy lifting which also allows the code to run on a GPU, if available. So, here’s a question, can we implement a sparse matrix factoring algorithm in Keras? It turns out that we can:
from keras.layers import Embedding, Reshape, Merge from keras.models import Sequential, from keras.optimizers import Adamax from keras.callbacks import EarlyStopping, ModelCheckpoint factors = 20 left = Sequential() left.add(Embedding(numUsers, factors,input_length=1)) left.add(Reshape(dims=(factors,))) right = Sequential() right.add(Embedding(numMovies, factors, input_length=1)) right.add(Reshape(dims=(factors,))) model = Sequential() model.add(Merge([left, right], mode='dot')) model.compile(loss='mse', optimizer='adamax') callbacks = [EarlyStopping('val_loss', patience=2), \ ModelCheckpoint('movie_weights.h5', save_best_only=True)] model.fit([Users, Movies], Ratings, batch_size=1000000, \ validation_split=.1, callbacks=callbacks)
Ta da! We’ve just created a left embedding layer that creates a Users by Latent Factors matrix and a right embedding layer that creates a Movies by Latent Factors matrix. When the input to these is a user id and a movie id, then they return the latent factor vectors for the user and the movie, respectively. The Merge layer then takes the dot product of these two things to return rating. We compile the model using MSE as the loss function and the AdaMax learning algorithm (which is superior to Sparse Gradient Descent). Our callbacks monitor the validation loss and we save the model weights each time the validation loss has improved.
The really nice thing about this implementation is that we can model hundreds of latent factors quite quickly. In my particular case, I can train on nearly 100 million ratings, half a million users and almost 20,000 movies in roughly 5 minutes per epoch, 30 epochs – 2.5 hours. But if I use the GPU (GeForce GTX 960), the epoch time decreases to 90s for a total training time of 45 minutes.
Alkahest » Blog Archive ... and logistic regression - Alkahest said,
March 7, 2016 @ 9:24 pm
[…] my heroes have always died at the end Bigger Font Size Smaller Font Size Left Align Justify Align Right Align Bookmark This Page Print This Page « Collaborative filtering in Keras […] | https://fenris.org/2016/03/07/index-html | CC-MAIN-2021-21 | refinedweb | 652 | 64.3 |
Creator: Documentation gone
Yesterday, my Creator 3.6.1 help system worked fine.
Today, I get:
The page could not be found Error loading: about:blank Check that you have the corresponding documentation set installed.
Tools->Options->Help->Documentation shows a ton of auto-detected entries, but no obvious way to check whether they are valid or not.
Hi,
Did you have any update done in between ?
Are the files still in place ?
I haven't done any updates.
Doc files are in place, but it's impossible to see from Qt Creator settings whether the registered help files are local or remote content. However, when I tried to add local help files, I received a "namespace already registered" error.
Sorry, I meant a system update.
That's pretty strange… The only quick way I can think of is to remove all the docs and add them again. Not the best answer but it should get you back on track.
I have tried to remove everything under "Options"-"Help"-"Documentation", then add qch files manually. No change. When I only remove everything and restart creator, the files are auto-detected, but docs still won't work.
The only thing that is available is the Qt Creator manual - probably built-in.
What OS are you running ?
Windows 7x64
Thanks for your replies so far. I have in the meantime made a support case out of it. I just hoped it would only be a minor thing that someone on the forums can tell me immediately. | https://forum.qt.io/topic/67230/creator-documentation-gone | CC-MAIN-2018-34 | refinedweb | 254 | 75.61 |
Hi Ed, > Greeting to HDF HQ! > > Some questions: > > 1 - If any dimension of a dataset is to be extensible, the dataset > must be chunked, correct? Yes. > 2 - If I have a dataset with one expendables dimension, and several > fixed dimensions, I can create it using a space like this: > > if ((spaceid = H5Screate_simple(var->ndims, dimsize, maxdimsize)) < 0) > BAIL(NC_EHDFERR); > > Where dimsize is an array of initial dimension sizes, and maxdimsize > is an array of max dimension sizes, or -1 for an unlimited dimension. > > The problem I have is this. If I try and create a space with one of > the dimsizes as zero, and the corresponding maxdimsize as -1, HDF5 > hands when I try to close the defined dataset (this seems like a HDF > bug, BTW). > > So I can do it if I start with a dimsize of 1 instead of 0, but this > is not the netcdf way. After defining such a dataset, when I get the > number of records in it, using H5Sget_simple_extent_dims, I get a size > of one along that dimension, even though I haven't written any data to > it yet, because I have to define it as having length of at least one. > > Any comment or help would be appreciated... Hmm, an initial size of 0 should work. Can you send me some test code that fails? I'll address the bug immediately then. Quincey >From owner-netcdf-hdf@xxxxxxxxxxxxxxxx 04 2003 Nov -0700 09:58:02 Message-ID: <wrxwuagnk9x.fsf@xxxxxxxxxxxxxxxxxxxxxxx> Date: 04 Nov 2003 09:58:02 -0700 From: Ed Hartnett <ed@xxxxxxxxxxxxxxxx> To: netcdf-hdf@xxxxxxxxxxxxxxxx Subject: HDF5 hangs... Received: (from majordo@localhost) by unidata.ucar.edu (UCAR/Unidata) id hA4Gw4Ne018587 for netcdf-hdf-out; Tue, 4 Nov 2003 09:58:04 -0700 (MST) Received: from rodney.unidata.ucar.edu (rodney.unidata.ucar.edu [128.117.140.88]) by unidata.ucar.edu (UCAR/Unidata) with ESMTP id hA4Gw2Ob018530 for <netcdf-hdf@xxxxxxxxxxxxxxxx>; Tue, 4 Nov 2003 09:58:02 -0700 (MST) Organization: UCAR/Unidata Keywords: 200311041658.hA4Gw2Ob018530 Lines: 43 User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.2 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Sender: owner-netcdf-hdf@xxxxxxxxxxxxxxxx Precedence: bulk Quincey, I am having a really weird problem. At a certain point in my code, the following code hangs in the H5Dcreate call. This code works a bunch of times, then, at some point (I'm doing lots of other HDF stuff, but not with this file), it hangs. I don't know what the deal is. { hid_t dsid = 0; hid_t typeid1 = H5Tcopy(H5T_NATIVE_CHAR); hid_t plistid1 = H5P_DEFAULT; hid_t spaceid1 = 0; hid_t hdfid = 0; if ((hdfid = H5Fcreate("ccc_test.h5", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT)) < 0) return (-1); if ((spaceid1 = H5Screate(H5S_SCALAR)) < 0) return (-1); if ((dsid = H5Dcreate(hdfid, "scaley", H5T_NATIVE_CHAR, spaceid1, plistid1)) < 0) return (-1); if (spaceid1 > 0) H5Sclose(spaceid1); if (hdfid > 0) H5Fclose(hdfid); if (dsid > 0) H5Dclose(dsid); dsid = 0; } When I use Cntl-C to interrupt the program, I get this message: Program received signal SIGINT, Interrupt. 0x400c997a in malloc_consolidate () from /lib/i686/libc.so.6 Somehow there is some malloc issue in H5Dcreate. Are you checking all your malloc returns to see that the memory you are using is really being allocated? I can't reproduce this in a short program (yet), but I'll keep trying... Ed
netcdf-hdflist information:
netcdf-hdflist
netcdf-hdfarchives: | http://www.unidata.ucar.edu/mailing_lists/archives/netcdf-hdf/2003/msg00037.html | CC-MAIN-2014-52 | refinedweb | 563 | 64.1 |
Getting Started
Published: January 15, 2013
Updated: January 15, 2013
Applies To: System Center 2012 SP1
Console add-ins in Virtual Machine Manager (VMM) enable customers and partners to create extensions for the VMM console. These extensions are presented as ribbon button entries. When you click the buttons, they do specific actions or display custom views in the console. Add-ins let you extend the VMM console with functionality that is specific to your needs.
What is an add-in?
Virtual Machine Manager add-ins are defined by manifest files. Manifest files are XML files that describe what your add-in will do and how it will be presented in the VMM console. If your add-in has custom code, the custom code must be provided by a Microsoft .NET 4 DLL that is packaged within the manifest file.
Manifests
A manifest defines your add-in for the VMM console. It contains basic information, such as authorship, description, and version. Additionally, it defines each piece of your add-in, such as ribbon button entries and views. If your add-in only provides ribbon buttons that either browse to URLs or start external applications, you do not have to provide a DLL.
For more information, see Manifests.
Custom code
If an add-in defines new pivot views or custom actions for the ribbon, you must create and package a DLL along with the add-in manifest file. The DLL is a Microsoft .NET 4 library using the System.Addin namespace. Depending on the base class that is used by your code, you can define what your add-in will provide to the console, and how it will operate when it is invoked.
For more information, see Base Classes.
Required assemblies
When you create an add-in that has custom code or a view, you will have to reference the add-in assemblies that are provided by the VMM console. These assemblies are located in the C:\Program Files\Microsoft System Center 2012\Virtual Machine Manager\bin folder. The following VMM assemblies are generally required to create add-ins:
- Errors
- Remoting
- Microsoft.SystemCenter.VirtualMachineManager
- Microsoft.SystemCenter.VirtualMachineManager.UIAddIns
- Microsoft.SystemCenter.VirtualMachineManager.UIAddins.ContextTypes
To install add-ins
Compress the add-in into a .zip file.
In the VMM console, select the Settings workspace.
Select the Console Add-Ins node and click the Import Add-In button. An import wizard will be presented to the user to let them choose the .zip file that contains the add-in.
For more information, see Managing Add-ins Overview. | http://msdn.microsoft.com/en-us/library/jj860339.aspx | CC-MAIN-2014-15 | refinedweb | 423 | 57.37 |
Service Versioning
After initial deployment, and potentially several times during their lifetime, services (and the endpoints they expose) may need to be changed for a variety of reasons, such as changing business needs, information technology requirements, or to address other issues. Each change introduces a new version of the service. This topic explains how to consider versioning in Windows Communication Foundation (WCF).
Four Categories of Service Changes
The changes to services that may be required can be classified into four categories:
- Contract changes: For example, an operation might be added, or a data element in a message might be added or changed.
- Address changes: For example, a service moves to a different location where endpoints have new addresses.
- Binding changes: For example, a security mechanism changes or its settings change.
- Implementation changes: For example, when an internal method implementation changes.
Some of these changes are called "breaking" and others are "nonbreaking." A change is nonbreaking if all messages that would have been processed successfully in the previous version are processed successfully in the new version. Any change that does not meet that criterion is a breaking change. This topic describes mechanisms for making nonbreaking changes in contracts, addresses, and bindings.
Service Orientation and Versioning
One of the tenets of service orientation is that services and clients are autonomous (or independent). Among other things, this implies that service developers cannot assume that they control or even know about all service clients. This eliminates the option of rebuilding and redeploying all clients when a service changes versions. This topic assumes the service adheres to this tenet of service orientation and therefore must be changed or "versioned" independent of its clients.
In cases where a breaking change is unexpected and cannot be avoided, an application may choose to ignore this tenet and require that clients be rebuilt and redeployed with a new version of the service. That scenario does not receive further discussion here.
Contract Versioning
Contracts used by a client do not need to be the same as the contract used by the service; they need only to be compatible.
For service contracts, compatibility means new operations exposed by the service can be added but existing operations cannot be removed or changed semantically.
For data contracts, compatibility means new schema type definitions can be added but existing schema type definitions cannot be changed in breaking ways. Breaking changes might include removing data members or changing their data type incompatibly. This feature allows the service some latitude in changing the version of its contracts without breaking clients. The next two sections explain nonbreaking and breaking changes that can be made to WCF data and service contracts.
Data Contract Versioning
This section deals with data versioning when using the DataContractSerializer and DataContractAttribute classes.
Strict Versioning
In many scenarios when changing versions is an issue, the service developer does not have control over the clients and therefore cannot make assumptions about how they would react to changes in the message XML or schema. In these cases, you must guarantee that the new messages will validate against the old schema, for two reasons:
- The old clients were developed with the assumption that the schema will not change. They may fail to process messages that they were never designed for.
- The old clients may perform actual schema validation against the old schema before even attempting to process the messages.
The recommended approach in such scenarios is to treat existing data contracts as immutable and create new ones with unique XML qualified names. The service developer would then either add new methods to an existing service contract or create a new service contract with methods that use the new data contract.
It will often be the case that a service developer needs to write some business logic that should run within all versions of a data contract plus version-specific business code for each version of the data contract. The appendix at the end of this topic explains how interfaces can be used to satisfy this need.breaking way. The service developer can make this assumption with confidence if the data contract features for versioning were already used for the first version of the service.
WCF, ASP.NET Web Services, and many other Web service stacks support lax versioning: that is, they do not throw exceptions for new unknown data members in received data.
It is easy to mistakenly believe that adding a new member will not break existing clients. If you are unsure that all clients can handle lax versioning, the recommendation is to use the strict versioning guidelines and treat data contracts as immutable.
For detailed guidelines for both lax and strict versioning of data contracts, see Best Practices: Data Contract Versioning.
Distinguishing Between Data Contract and .NET Types
A .NET class or structure can be projected as a data contract by applying the DataContractAttribute attribute to the class. The .NET type and its data contract projections are two distinct matters. It is possible to have multiple .NET types with the same data contract projection. This distinction is especially useful in allowing you to change the .NET type while maintaining the projected data contract, thereby maintaining compatibility with existing clients even in the strict sense of the word. There are two things you should always do to maintain this distinction between .NET type and data contract:
- Specify a Name and Namespace. You should always specify the name and namespace of your data contract to prevent your .NET type’s name and namespace from being exposed in the contract. This way, if you decide later to change the .NET namespace or type name, your data contract remains the same.
- Specify Name. You should always specify the name of your data members to prevent your .NET member name from being exposed in the contract. This way, if you decide later to change the .NET name of the member, your data contract remains the same.
Changing or Removing Members
Changing the name or data type of a member, or removing data members, is a breaking change even if lax versioning is allowed. If this is necessary, create a new data contract.
If service compatibility is of high importance, you might consider ignoring unused data members in your code and leave them in place. If you are splitting up a data member into multiple members, you might consider leaving the existing member in place as a property that can perform the required splitting and re-aggregation for down-level clients (clients that are not upgraded to the latest version).
Similarly, changes to the data contract’s name or namespace are breaking changes.
Round-Trips of Unknown Data.
To enable round-tripping for a particular type, the type must implement the IExtensibleDataObject interface. The interface contains one property, ExtensionData that returns the ExtensionDataObject type. The property is used to store any data from future versions of the data contract that is unknown to the current version. This data is opaque to the client, but when the instance is serialized, the content of the ExtensionData property is written with the rest of the data contract members' data.
It is recommended that all your types implement this interface to accommodate new and unknown future members.
Data Contract Libraries
There may be libraries of data contracts where a contract is published to a central repository, and service and type implementers implement and expose data contracts from that repository. In that case, when you publish a data contract to the repository, you have no control over who creates types that implement it. Thus, you cannot modify the contract once it is published, rendering it effectively immutable.
When Using the XmlSerializer
The same versioning principles apply when using the XmlSerializer class. When strict versioning is required, treat data contracts as immutable and create new data contracts with unique, qualified names for the new versions. When you are sure that lax versioning can be used, you can add new serializable members in new versions but not change or remove existing members.
Message Contract Versioning
The guidelines for message contract versioning are very similar to versioning data contracts. If strict versioning is required, you should not change your message body but instead create a new message contract with a unique qualified name. If you know that you can use lax versioning, you can add new message body parts but not change or remove existing ones. This guidance applies both to bare and wrapped message contracts.
Message headers can always be added, even if strict versioning is in use. The MustUnderstand flag may affect versioning. In general, the versioning model for headers in WCF is as described in the SOAP specification.
Service Contract Versioning
Similar to data contract versioning, service contract versioning also involves adding, changing, and removing operations.
Specifying Name, Namespace, and Action
By default, the name of a service contract is the name of the interface. Its default namespace is "", and each operation’s action is "". It is recommended that you explicitly specify a name and namespace for the service contract, and an action for each operation to avoid using "" and to prevent interface and method names from being exposed in the service’s contract.
Adding Parameters and Operations
Adding service operations exposed by the service is a nonbreaking change because existing clients need not be concerned about those new operations.
Changing Operation Parameter or Return Types
Changing parameter or return types generally is a breaking change unless the new type implements the same data contract implemented by the old type. To make such a change, add a new operation to the service contract or define a new service contract.
Removing Operations
Removing operations is also a breaking change. To make such a change, define a new service contract and expose it on a new endpoint.
Fault Contracts
The FaultContractAttribute attribute enables a service contract developer to specify information about faults that can be returned from the contract's operations.
The list of faults described in a service's contract is not considered exhaustive. At any time, an operation may return faults that are not described in its contract. Therefore changing the set of faults described in the contract is not considered breaking. For example, adding a new fault to the contract using the FaultContractAttribute or removing an existing fault from the contract.
Service Contract Libraries
Organizations may have libraries of contracts where a contract is published to a central repository and service implementers implement contracts from that repository. In this case, when you publish a service contract to the repository you have no control over who creates services that implement it. Therefore, you cannot modify the service contract once published, rendering it effectively immutable. WCF supports contract inheritance, which can be used to create a new contract that extends existing contracts. To use this feature, define a new service contract interface that inherits from the old service contract interface, then add methods to the new interface. You then change the service that implements the old contract to implement the new contract and change the "versionOld" endpoint definition to use the new contract. To "versionOld" clients, the endpoint will continue to appear as exposing the "versionOld" contract; to "versionNew" clients, the endpoint will appear to expose the "versionNew" contract.
Address and Binding Versioning
Changes to endpoint address and binding are breaking changes unless clients are capable of dynamically discovering the new endpoint address or binding. One mechanism for implementing this capability is by using a Universal Discovery Description and Integration (UDDI) registry and the UDDI Invocation Pattern where a client attempts to communicate with an endpoint and, upon failure, queries a well-known UDDI registry for the current endpoint metadata. The client then uses the address and binding from this metadata to communicate with the endpoint. If this communication succeeds, the client caches the address and binding information for future use.
Appendix
The general data contract versioning guidance when strict versioning is needed is to treat data contracts as immutable and create new ones when changes are required. A new class needs to be created for each new data contract, so a mechanism is needed to avoid having to take existing code that was written in terms of the old data contract class and rewrite it in terms of the new data contract class.
One such mechanism is to use interfaces to define the members of each data contract and write internal implementation code in terms of the interfaces rather than the data contract classes that implement the interfaces. The following code for version 1 of a service shows an
IPurchaseOrderV1 interface and a
PurchaseOrderV1:
public interface IPurchaseOrderV1 { string OrderId { get; set; } string CustomerId { get; set; } } [DataContract( Name = "PurchaseOrder", Namespace = "")] public class PurchaseOrderV1 : IPurchaseOrderV1 { [DataMember(...)] public string OrderId {...} [DataMember(...)] public string CustomerId {...} }
While the service contract’s operations would be written in terms of
PurchaseOrderV1, the actual business logic would be in terms of
IPurchaseOrderV1. Then, in version 2, there would be a new
IPurchaseOrderV2 interface and a new
PurchaseOrderV2 class as shown in the following code:
public interface IPurchaseOrderV2 { DateTime OrderDate { get; set; } } [DataContract( Name = "PurchaseOrder ", Namespace = "")] public class PurchaseOrderV2 : IPurchaseOrderV1, IPurchaseOrderV2 { [DataMember(...)] public DateTime OrderId {...} [DataMember(...)] public string CustomerId {...} [DataMember(...)] public DateTime OrderDate { ... } }
The service contract would be updated to include new operations that are written in terms of
PurchaseOrderV2. Existing business logic written in terms of
IPurchaseOrderV1 would continue to work for
PurchaseOrderV2 and new business logic that needs the
OrderDate property would be written in terms of
IPurchaseOrderV2. | http://msdn.microsoft.com/en-us/library/ms731060(v=vs.90).aspx | CC-MAIN-2014-52 | refinedweb | 2,245 | 52.09 |
04 April 2011 05:28 [Source: ICIS news]
By Serena Seng
SINGAPORE (ICIS)--Asia C12 lauric acid prices may continue to soften on poor buying interest and amid falling values of feedstocks crude palm oil (CPO) and crude palm kernel oil (CPKO), market sources said on Monday.
Spot prices of C12 lauric acid shed $650/tonne (€455/tonne) or 20% from their peak on 23 February to $2,600-2,700/tonne FOB (free on board) SE (southeast) ?xml:namespace>
In
Poor market sentiment, combined with falling feedstock prices, caused C12 lauric acid prices to tumble in March, market sources said.
Prices were being adjusted, in line with the movement of crude prices, said a Malaysian fatty acids producer.
Meanwhile, most buyers have also covered some positions in early February, when prices were still on an uptrend, market sources said.
"C12 lauric prices were previously inflated to above $3,000/tonne FOB SE Asia levels. At that level, I did not buy as I know that was not the real market price," said an Indian buyer.
"When prices started to fall in [the] middle of March, I bought some cargoes as prices now are more realistic," a Japanese buyer said.
Strong availability of feedstock this month, as CPO and CPKO production goes on full swing, will likely keep the downward pressure on C12 lauric acid prices, market sources said.
"Most buyers are expected to hold out until prices drop even further in April," said an Indonesian producer, adding that the resulting weak demand will compound the pressure for C12 lauric acid prices to fall.
($1 = €0.70 / $1 = CNY6 | http://www.icis.com/Articles/2011/04/04/9449461/asia-c12-lauric-acid-may-extend-falls-on-weak-demand.html | CC-MAIN-2013-48 | refinedweb | 269 | 64.64 |
create list of all the children of an object
On 13/05/2017 at 05:28, xxxxxxxx wrote:
Hi,
I am stuck with something which should be quite simple and would really appreciate if someone can help me with it.
I just want to create a simple list of all the children of an object. I got the point you have to use a recursive loop and found this one (I have it on a script tag) :
def process_hierarchy(op) :
print op
op = op.GetDown()
while op:
process_hierarchy(op)
op = op.GetNext()
def main() :
process_hierarchy(op.GetObject())
When I define a list and append the children it is also reset at every round... (I get a list with just one child)
Here is what is not working:
def process_hierarchy(op) :
listChildren=[]
listChildren.append(op)
op = op.GetDown()
while op:
process_hierarchy(op)
op = op.GetNext()
print listChildren
Does anyone know how I can do this list?
Many thanks,
H.
On 13/05/2017 at 06:08, xxxxxxxx wrote:
Two solutions.
First one using GetNext/GetDown.
Second one using GetChildren
import c4d def getchildren_v1(op, stop_obj, data=None) : if not data: data = list() while op: data.append(op) getchildren_v1(op.GetDown(), stop_obj, data) op = op.GetNext() if op == stop_obj: return data def getchildren_v2(op, data=None) : if not data: data = list() data.append(op) children = op.GetChildren() for child in children: getchildren_v2(child, data) return data def main() : obj = doc.GetActiveObject() my_list_v1 = getchildren_v1(obj, obj.GetNext()) print my_list_v1 my_list_v2 = getchildren_v2(obj) print my_list_v2 if __name__=='__main__': main()
btw if you post code into this form try to use [ code] and [ /code]
On 15/05/2017 at 08:17, xxxxxxxx wrote:
Hi,
thanks, gr4ph0s
Just want to add a word of explanation, why the initial code is not working. Basically in the process_hierarchy() function, you were creating a fresh new list on every call of the function, then added one object to it and when leaving the function, this list got forgotten.
As gr4ph0s demonstrates, you need to pass one list through all the calls, successively adding to it. | https://plugincafe.maxon.net/topic/10119/13600_create-list-of-all-the-children-of-an-object | CC-MAIN-2020-50 | refinedweb | 346 | 74.29 |
hash_map::upper_bound
Returns an iterator to the first element in a hash_map that with a key having a value that is greater than that of a specified key.
Parameter
- _Key
- The argument key value to be compared with the sort key value of an element from the hash_map being searched.
Return Value
An iterator or const_iterator that addresses the location of an element in a hash_map that with a key that is greater than the argument key, or that addresses the location succeeding the last element in the hash_map if no match is found for the key.
If the return value is assigned to a const_iterator, the hash_map object cannot be modified. If the return value is assigned to an iterator, the hash_map object can be modified.
Remarks
In Visual C++ .NET 2003, members of the <hash_map> and <hash_set> header files are no longer in the std namespace, but rather have been moved into the stdext namespace. See The stdext Namespace for more information.
Example
// hash_map_upper_bound.cpp // compile with: /EHsc #include <hash_map> #include <iostream> int main( ) { using namespace std; using namespace stdext; hash_map <int, int> hm1; hash_map <int, int> :: const_iterator hm1_AcIter, hm1_RcIter; typedef pair <int, int> Int_Pair; hm1.insert ( Int_Pair ( 1, 10 ) ); hm1.insert ( Int_Pair ( 2, 20 ) ); hm1.insert ( Int_Pair ( 3, 30 ) ); hm1_RcIter = hm1.upper_bound( 2 ); cout << "The first element of hash_map hm1 with a key " << "greater than 2 is: " << hm1_RcIter -> second << "." << endl; // If no match is found for the key, end is returned hm1_RcIter = hm1. upper_bound ( 4 ); if ( hm1_RcIter == hm1.end( ) ) cout << "The hash_map hm1 doesn't have an element " << "with a key greater than 4." << endl; else cout << "The element of hash_map hm1 with a key > 4 is: " << hm1_RcIter -> second << "." << endl; // The element at a specific location in the hash_map can be found // using a dereferenced iterator addressing the location hm1_AcIter = hm1.begin( ); hm1_RcIter = hm1. upper_bound ( hm1_AcIter -> first ); cout << "The 1st element of hm1 with a key greater than " << "that\n of the initial element of hm1 is: " << hm1_RcIter -> second << "." << endl; }
Output
See Also
hash_map Class | hash_map Members | http://msdn.microsoft.com/en-US/library/4eez52af(v=vs.71).aspx | CC-MAIN-2013-48 | refinedweb | 340 | 72.46 |
.
Hi Kean,
I was lloking through posts, and could not find an answer to this:
The trim command allows crossing window selection of items within xrefs, as if the items are active.
is there a way to do this with .net?
I can do individual items no problem, but using windows is a dead end so far, I get the whole xref (block) or nothing...thanks
Posted by: James Maeding | October 14, 2008 at 07:19 PM
Also, almost forgot, can .net get and set lisp variables that are in separate namespaces?
I compile all my lisps to separate namespace vlx files.
Last time I tried, you could only get at vars set from non-compiled lisps.
thanks
Posted by: James Maeding | October 14, 2008 at 07:29 PM
Hi James,
I haven't tried this, myself (at least, not recently), but you might try setting PromptSelectionOptions.AllowSubSelections to true. I can't recall whether it works for XRefs.
Failing that, I'd suggest asking ADN or posting to the discussion group.
I don't recall what access is available for variables stored in VLXs - again, another good one to ask ADN or post to a forum.
Regards,
Kean
Posted by: Kean | October 15, 2008 at 09:28 AM
I'll try that, thx
Posted by: James Maeding | October 15, 2008 at 07:34 PM | http://through-the-interface.typepad.com/through_the_interface/2008/10/free-autocad-pr.html | crawl-002 | refinedweb | 225 | 71.75 |
Best quality New Products solar panels China Manufacturer prices in saudi arabia 300w 600w
US $0.3-0.42 / Watt
1 Watt (Min. Order)
Cheap price high quality mono solar panel 600w for sale
US $45-135 / Piece
1 Piece (Min. Order)
270w 280w 290w 300w 310w per piece mono price solar panel 600w
US $80.02-90.16 / Piece
50 Pieces (Min. Order)
yingli solar panel 50w 30w 100w 150w 200w 250w 500w 800w 600w price
US $0.39-0.49 / Piece
1 Piece (Min. Order)
panel solar 600w solar panel price uganda market nano solar panel with CE certificate
US $121.0-155.0 / Piece
1 Piece (Min. Order)
solar panel 50w 30w 100w 150w 200w 250w 500w 800w 600w price
US $0.35-0.45 / Watts
3000 Watts (Min. Order)
top selling 55w 50w solar panel price india solar panel 600w solar panel 60v
US $0.368-0.38 / Watt
1000 Watts (Min. Order)
Low Price solar panel 600w manufacturer
US $0.4-0.45 / Watt
250 Watts (Min. Order)
Factory Price Poly PV Module panel solar 600w with CE, TUV, CE certificates
US $0.38-0.38 / Watts
20 Watts (Min. Order)
Mono poly 200w 300w 600w solar panel price
US $0.6-0.65 / Watt
1 Watt (Min. Order)
Good price nice quality price solar panel 300w 310 solar panel 600w
US $0.25-0.45 / Watt
300 Watts (Min. Order)
Factory price panel solar 600w with good
US $0.37-0.45 / Watt
500 Watts (Min. Order)
Factory price eco-friendly mono/poly solar panel 600w with FCC ROHS IEC ISO certificates
US $0.43-0.78 / Watt
20000 Watts (Min. Order)
110v solar inverter panel 600w pv panel price made in china
US $52-159 / Piece
1 Piece (Min. Order)
600w solar panel price with good quality
US $50-120 / Piece
1 Piece (Min. Order)
600W High efficiency solar panel price low,mounting bracket
US $1-799 / Piece
5 Pieces (Min. Order)
Solar module price panel solar 600w for 8kw solar power system
US $0.3-0.55 / Watt
500 Watts (Min. Order)
risen energy color panel solar 600w price
US $70-120 / Piece
20 Pieces (Min. Order)
china high quality solar panel 600w price
US $150-500 / Set
1 Set (Min. Order)
best price solar panel 600w with high efficiency
US $0.58-0.69 / Watt
50 Pieces (Min. Order)
Sunway Poly PV Module Solar Panel Price for Micro Inverter 250w 300w 600w
US $0.35-0.45 / Watt
10000 Watts (Min. Order)
2017 SHINE Cheap price OEM 3V 0.36W 90mA PET solar panel
US $0.5-1.5 / Piece
10 Pieces (Min. Order)
Factory high quality solar panel 600w with best price
US $0.32-0.37 / Watt
3500 Watts (Min. Order)
2017 Hot sale High efficiency mono 300w solar panels from manufacturer
US $0.4-0.65 / Watt
10 Watts (Min. Order)
best quality good price 260w solar panel for solar system
US $0.32-0.4 / Watt
260 Watts (Min. Order)
Low Price Mono Solar Panel 185W-205WLow Price Mono G9
6500 Watts (Min. Order)
1200W DC-AC portable complete home solar system price per watt solar panels(BYGD-1200Y)
US $95.7-105.7 / Piece
1 Piece (Min. Order)
Best AC solar energy system price 1700-1800USD/set (SP600-1200),easy handy,best price,optional solar panels
US $1720-1770 / Set
1 Set (Min. Order)
factory price 96 volt charge controller for solar panel 20 amp with free sample
US $0.55-0.55 / Watt
1 Watt (Min. Order)
best price per watt solar panel solar 400w 500w 600w 800 1000w
US $0.3-0.4 / Watt
5000 Watts (Min. Order)
Promotion 110-240V 300W 100 watts solar power panels for home system NC50B in nairobi kenya
US $240-300 / Set
1 Set (Min. Order)
factory price 600W off grid home solar inverter solar systems with solar panel
US $208.0-312.0 / Set
1 Set (Min. Order)
import solar panels 1000w price list
US $600-1000 / Set
1 Set (Min. Order)
CE approved 600W complete solar power system for home, with solar panel
US $320-340 / Set
1 Set (Min. Order)
whole 1000w solar panel system with solar panel,controller,inverter,cable connector and mounting 100kw
US $1500-1800 / Set
1 Set (Min. Order)
2kw 1kw solar system 300w ploy solar panel
US $1500-1800 / Set
1 Set (Min. Order)
ZJSOLA 1KW-10kw solar power system 1000w solar panels for home kit solar fotovoltaico
US $988.0-1268.0 / Set
1 Set (Min. Order)
Direct factory sale price 350w solar panel/20kw solar panel system
US $0.65-0.7 / Watt
1 Set (Min. Order)
TDCsolar poly pv solar panel price 250w for micro inverter 300w 600w 1200w
US $0.3-0.42 / Watt
2500 Watts (Min. Order)
- About product and suppliers:
Alibaba.com offers 295 600w solar panel price products. such as paid samples, free samples. There are 295 600w solar panel price suppliers, mainly located in Asia. The top supplying countries are China (Mainland), United States, and Turkey, which supply 98%, 1%, and 1% of 600w solar panel price respectively. 00w solar panel price products are most popular in Southeast Asia, Mid East, and Africa. You can ensure product safety by selecting from certified suppliers, including 133 with ISO9001, 19 with ISO14001, and 11 with Other certification.
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show 600w solar panel price or other products of your own company? Display your Products FREE now! | http://www.alibaba.com/showroom/600w-solar-panel-price.html | CC-MAIN-2018-09 | refinedweb | 933 | 77.53 |
.
Finding the Number of Unread Messages in Your Inbox
Email: can’t live with it, can’t live without it. As the volume of email we get increases by leaps and bounds, people start looking for ways to automate and streamline their email use. Here’s a simple little script that might help: it checks your Outlook Inbox to find out how many unread messages you) Wscript.Echo objFolder.UnreadItemCount objOutlook.Quit
One thing to be careful about when scripting against Microsoft Outlook is the fact that you can create only a single instance of Microsoft Outlook. If Outlook is already running, you won’t get a new instance when running this script; instead, you’ll bind to the existing instance. That’s not that big of a deal except when you reach the final line of code: the last line causes Outlook to quit, which means your existing Outlook session will terminate. For now, we’re going to assume that you’ll be running this script only when Outlook isn’t already running. We’ll deal with determining whether Outlook is already running and how to modify the script accordingly in a future column.
We start off by defining a constant named olFolderInbox and assigning it the value of 6; this constant will be used to specify the folder we want to open. (As you might expect, olFolderInbox represents the Inbox.) We then create an instance of Outlook and use the GetNamespace method to connect to the MAPI namespace. Note that while you must pass “MAPI” as the parameter to GetNamespace, that’s the only parameter you can pass; Outlook can’t connect to any other namespaces.
We then call the Logon method to ensure that we connect to the proper profile. The Logon method requires four parameters:
After connecting to the correct profile we then use the GetDefaultFolder method to bind to the Inbox. (Note that we pass olFolderInbox as the sole parameter to GetDefaultFolder.) At that point we simply echo the value of the UnreadItemCount and then close Outlook.
By the way, you can determine the total number of items – both read and unread – that are in your Inbox by returning a collection of Inbox items and then echoing back the Count property for that collection. Here’s a sample script that does just) Set colItems = objFolder.Items Wscript.Echo colItems.Count objOutlook.Quit | https://technet.microsoft.com/en-us/library/ee692857.aspx | CC-MAIN-2017-30 | refinedweb | 397 | 58.72 |
Don't ad-block us - support your favorite websites. We have safe, unobstrusive, robotics related ads that you actually want to see - see here for more.
0 Members and 1 Guest are viewing this topic.
#include "timer.h"//im not using a crystal on my atmega644setup_timer //prescaling and stuffwhile(1){reset_timer //make timer go to zerowhile(timer < 2ms) //i dont care for anything above 2ms so no need to track overflows { do_stuff(); }do_other_stuff();}
#include "timer.h"void do_other_stuff(void); //define this lattervoid init(){ //setup the timer0 with appropriate bits timerAttach(SIG_OVERFLOW0, do_other_stuff); //other initialzation stuff}int main(void){ init(); while(1) { //just do_stuff() and the timer will automaticaly run do_other_stuff() }}void do_other_stuff(void){ //the other stuff you want to do}
setup_timer_1(T1_INTERNAL | T1_DIV_BY_8); //Set Timer1 prescaler to 8set_timer1(0); //reset timerwhile(get_timer1() < 2000) //~2ms has passed { timing=get_timer1(); do_stuff(); printf("Time passed: %d", get_timer()); //logs the time it took to do_stuff() } | http://www.societyofrobots.com/robotforum/index.php?topic=594.msg3569 | CC-MAIN-2015-22 | refinedweb | 151 | 53.34 |
This post collects a few situations where agents might want to make their decisions either predictable or unpredictable to certain methods of prediction, and considers a method of making a decision unpredictable by "diagonalizing" a hypothetical prediction of that decision. The last section takes a stab at applying this tool to the ASP problem.
The diagonal step
To start off, consider the halting problem, interpreted in terms of agents and predictors. Suppose that there is a Universal Predictor, an algorithm that is able to decide whether any given program halts or runs forever. Then, it's easy for a program (agent) to evade its gaze by including a diagonal step in its decision procedure: the agent checks (by simulation) if Universal Predictor comes to some decision about the agent, and if it does, the agent acts contrary to the Predictor's decision. This makes the prediction wrong, and Universal Predictors impossible.
The same trick could be performed against something that could exist, normal non-universal Predictors, which allows an agent to make itself immune to their predictions. In particular, ability of other agents to infer decisions of our agent may be thought of as prediction that an agent might want to hinder. This is possible so long as the predictors in question can be simulated in enough detail, that is it's known what they do (what they know) and our agent has enough computational resources to anticipate their hypothetical conclusions. (If an agent does perform the diagonal step with respect to other agents, the predictions of other agents don't necessarily become wrong, as they could be formally correct by construction, but they cease to be possible, which could mean that the predictions won't be made at all.)
Knowing own decision
In UDT/ADT, an agent is given definitions of its action (strategy) and utility value, and evaluates an action (strategy) by inferring the logical implications of taking it on the utility value (see this post for a more detailed description of the decision procedure and this post for an explanation of how it might be better to optimize strategy, rather than individual decisions). However, this algorithm breaks down if an agent becomes able to infer its own decision (or that a certain decision is impossible): in that case, it can infer anything from the hypothesis that it makes an impossible decision. This is one case where an agent might want to make its decision unpredictable to itself!
It seems that normally an agent won't be able to predict its own decision (see these posts for some discussion), but it's unclear how to set up an agent so that it provably doesn't do that. Worse, an ADT agent is a program that reasons using first-order logic and knows its own source code, which means that a statement declaring agent's actual decision is provable (by a standard inference system that enumerates all valid statements), and so the best we can hope for is that the agent won't stumble upon such a proof before it made a decision (see the section of this post on provability by the agent).
Countable diagonal step
Adding the diagonal step to ADT agents, to make them unable to predict (infer) their own decision, in the simplest case requires the agents to simulate themselves up until the point where they make a decision. In general this is too hard, so one way out is to grant the agents provability oracles. The resulting setting is described in this post.
The inference (prediction) system of an agent with a provability oracle can be completely described as a formal system S, which the agent uses (with help of the oracle) to check validity of any statement (in one step). Trouble with predicting own decisions then corresponds to S being too strong, able to infer agent's decision. The ("countable") diagonal step can be implemented by the agent checking, for each possible action A, whether S proves that actual action doesn't equal A, and performing A if S proves so. If S is sound, that situation is never realized, which means that S is weak enough to fail to predict agent's decision. The agent makes itself just complicated enough for its own inference system to become unable to reason about (origins of) its decision. This condition is then sufficient to prove that the agent satisfactorily resolves some thought experiments, such as Newcomb's Problem.
Avoiding spurious statements (without oracles)
An ADT agent without provability oracle only needs to hold off on predicting its decision until the decision is made. This can be arranged by use of the diagonal step if it's known when the decision can be made. Let's consider an example.
Newcomb's problem can be formalized (as in these posts) as follows:
def world():
box1 = 1000
box2 = (agent() == 2) ? 0 : 1000000
return box2 + ((agent() == 2) ? box1 : 0)
Define constant symbols A=agent(), U=world(). It's easy to see that statements [A=1 => U=1000000] and [A=2 => U=1000] are valid, no matter what agent() is (assuming it terminates and always outputs 1 or 2). But if actually A=2, then A=1 is false, and so the statement [A=1 => U=0] is true as well. How do we know that the agent won't find specifically the statements [A=1 => U=0] and [A=2 => U=1000], choose A=2 as a result, with A=1 indeed becoming false?
The problem is that even when we know that in the intended situation certain statements assigning value to possible actions are true, that doesn't automatically guarantee that the agent will find these same statements, and thus that it will make the decision implied by the statements we know to be true. In Newcomb's problem, an agent could in principle encounter true statements [A=1 => U=0] and [A=2 => U=1000] listed at the very beginning of a contrived inference system and two-box as a result, which is what makes those statements true.
Thus, it matters how agent's inference system works, even if we know that it's correct (i.e. enumerates all valid first order statements following from the stated axioms). It has to be sufficiently "natural" in some sense, so that we can rely on [A=1 => U=1000000] coming before statements like [A=1 => U=0], with agent acting on the more "natural" arguments about value of a possible action, and not on one of the spurious ones (implied by the possible action not being actually taken).
Finite diagonal step
In the preceding example, we can point out specific proofs of [A=1 => U=1000000] and [A=2 => U=1000] that don't depend on definition of A. Knowing the length of such proofs (say, L) and using an inference system that enumerates all valid proofs in the order of their length allows predicting when those particular proofs will be encountered, and so when, at the latest, the decision will be made (if it's not made before that, but using some other, shorter proof). It is then only until that point that the agent has to hold off on predicting its own decision.
If we know the number of steps N for the duration of which the inference system needs to be protected (while it considers the proofs no longer than L), the ("finite") diagonal step consists in running agent's inference system S for N steps, and contradicting (by action) any prediction about agent's action reached during these N steps. This step is decidable and doesn't require an oracle. Implementing it guarantees that (if S is sound and N is selected as discussed above) agent won't be able to predict its decision before it's made.
Sufficiently increasing the threshold N allows to prove that no other statements of the form [A=A1 => U=U1] will be proved before a decision is made (and so that the decision will be as expected). Specifically, let M>N be the new threshold. We know that (for example) [A=1 => U=1000000] is proved by S within N steps, so if (say) [A=1 => U=0] is proved also within N steps, then the proof of negation of [A=1] is only a few steps longer than 2*L, and so if we choose M to include all proofs of that length, the disproof of [A=1] will be encountered within the first M steps, which would trigger the diagonal step. Since the diagonal step can't be triggered if S is sound, we've thus proved that presence of the diagonal step guarding the first M steps of the inference system allows to conclude that the agent won't infer any spurious statements of the form [A=A1 => U=U1], and will behave as expected.
This is the same guarantee that countable diagonal rule gives, albeit at the cost of having to know L.
Prisoner's dilemma
Prisoner's dilemma presents a situation where some measure of predictability is advantageous to both agents. Specifically, if an agent can prove that cooperating implies cooperation of the opponent, and defecting implies defection of the opponent, it can then cooperate, reaching the outcome (C,C) that is better than the equilibrium solution (D,D). It's harder to arrange cooperation without being able to predict the opponent's reaction to a hypothetical decision, so taking away all predictability of decisions will hurt both agents.
The trick is that UDT only wants that statements like [A1=C] be unprovable (in N steps), but statements like [A1=C => A2=C] may remain provable, and it's conditional statements like this that are needed to broker cooperation in PD. It seems that cooperation is possible both for simple agents without oracles or use of the diagonal step, and for agents with oracles that use countable diagonal step.
Agent simulates predictor
Finally, there is the ASP problem that involves a weak predictor and a powerful agent that need to cooperate on Newcomb's problem. The difficulty is that it seems that since the agent can anticipate predictor's decision by simulating it, it would take both boxes no matter what, and so the predictor has to predict two-boxing (which is unfortunate). The predictor is defenseless, it can't insist on making itself unpredictable, and as a result the agent's predictions of predictor's decision (given either hypothetical action of the agent) coincide.
Just as it's necessary to entertain multiple hypothetical actions to gauge their consequences, it's necessary for there to be multiple hypothetical outcomes for their comparison to yield a nontrivial decision. The preceding sections addressed the problem of making agent's own decision unpredictable, and in this case it seems that the agent has to make the decision of its opponent (the weak predictor) unpredictable (to the agent).
One way to patch this up seems to be requiring that the weak predictor is trying to prove that agent one-boxes (with however little computational power it has), and predicting two-boxing otherwise. This way, if predictor says that agent one-boxes, agent must really be one-boxing, and so we can use this condition in a diagonal step in the agent, making this situation unpredictable to the agent. Namely, the agent will two-box if it predicts that the predictor decides that the agent one-boxes (while running agent's inference system for at most M steps, as with finite diagonal step). As a result, the agent won't be able to predict that the predictor one-boxes (within M steps of agent's inference system), which might make the agent simple enough for the predictor to predict, and the two players seem to regain an equal footing.
Open problems
- Formalize this analysis of ASP, prove that predictor and agent one-box
- What happens if we try making the opponent in PD "unpredictable" in the same sense?
- See if making all kinds of facts unpredictable in this way can be made to retain their conditional predictability (predictability given an assumption of what agent's action is)
Then won't the predictor predict that the agent two-boxes?
There is a bit of terminological confusion here. Predictor makes a decision to either one-box or two-box, and the decision to one-box could be called "predicting that the agent one-boxes", but it isn't necessarily able to predict so unconditionally, so it's more like "predicting that the agent one-boxes given that the predictor one-boxes".
The predictor is supposed to one-box, but the agent isn't supposed to infer (within M steps) that the predictor one-boxes (just as in finite diagonal step, the objective is to make a decision unpredictable, not impossible). On the other hand, if this plan works out, the agent should be able to infer that the predictor one-boxes conditional on the agent one-boxing.
A common theme is that the diagonal rule could make events unpredictable, but still conditionally predictable. It's interesting whether it's possible to navigate this edge well.
I don't understand this answer and cousin_it doesn't either (I just asked him).
If the predictor outputs "one-box", then the agent must prove this if it enumerates all proofs within a certain length because there is a proof-by-simulation of this fact, of length proportional to the predictor's run time, right? I don't see how the diagonal step can prevent the agent from finding this proof, unless it makes the predictor not output "one-box".
The agent doesn't use enough steps to simulate the predictor, it decides early (because it finds a proof that predictor conditionally one-boxes early), which is also what might allow the predictor to conditionally predict agent's one-boxing within predictor's limited computational resources. The M steps where the agent protects the predictor from being unconditionally predictable is a very small number here, compared to agent's potential capability.
Neat.
How is the agent supposed to know which parts of the world are "opponents" that it should make unpredictable? This seems like a potentially show-stopping problem with your approach and I'm surprised it's not listed under open problems. Is there something obvious that I'm missing?
This post doesn't propose a complete decision algorithm, it merely collects several applications of what appears to be the same trick. Your question seems to fall in the scope of the third open problem: perhaps it's a good idea to make all sorts of facts (events in the world) unconditionally unpredictable (unpredictable when not assuming what agent's own decision would be), if at the same time it's possible to retain their conditional predictability (predictability when an assumption about agent's own decision is made).
(Making an event unconditionally unpredictable but conditionally predictable looks like a good candidate for what gaining control over that event means, and an agent would want to gain control over as many events as possible. In particular, gaining control over your opponent's decisions is probably a good idea.)
(It might be good to keep in mind Eliezer's point about how discorrelation is potentially a scarce resource (because correlation is a ratchet).)
That depends on the opponent's computational power. There are certainly cryptographic approaches to this problem.
Doesn't increasing N also change L? If N is part of the specification of the agent, then its value can affect the length of proofs about the agent. This indicates that there are probably agent designs for which we cannot just sufficiently increase N in order to make this diagonalization argument work.
It's possible. In the example, L doesn't depend on N, but it could. What we need is an L that works as an upper bound, even if we use M>N based on 2*L+ in the diagonal step.
I don't see what the problem is. You compare 'what happens if I do X?' with 'what happens if I do Y?' Not, 'If I do X, what would have happened if I did Y?'
You split the evaluation into cases with constant past decisions, then pick the best outcome. Then the AI doesn't even notice when it gets into a catch-22 condition. | https://www.lesswrong.com/posts/W6T93dSSm2xvHn9X6/predictability-of-decisions-and-the-diagonal-method | CC-MAIN-2022-05 | refinedweb | 2,734 | 53.04 |
JavaScript Testing Framework Comparison: Jasmine vs Mocha
Testing in JavaScript is becoming expected by developers more and more. But where do you start? There are so many framework choices out there. It can feel pretty overwhelming. This post is a quick overview of the differences between two popular JavaScript testing frameworks: Jasmine 2 and Mocha. We will also discuss commonly used libraries, Chai and Sinon, that are often used in conjunction with Jasmine and Mocha.
1. The API
The APIs of Jasmine and Mocha are very similar where you write your test suite with
describe blocks and each test, also called a spec, using the
it function.
describe('calculator add()', function() { it('should add 2 numbers togoether', function() { // assertions here }); });
The assertions, or expectations as they are often called, are where things start to differ. Mocha does not have a built in assertion library. There are several options though for both Node and the browser: Chai, should.js, expect.js, and better-assert. A lot of developers choose Chai as their assertion library. Because none of these assertion libraries come with Mocha, this is another thing you will need to load into your test harness. Chai comes with three different assertion flavors. It has the
should style, the
expect style, and the
assert style. The
expect style is similar to what Jasmine provides. For example, if you want to write an expectation that verifies
calculator.add(1, 4) equals 5, this is how you would do it with both Jasmine and Chai:
Jasmine
expect(calculator.add(1, 4)).toEqual(5);
Chai
expect(calculator.add(1, 4)).to.equal(5);
Pretty similar right? If you are switching from Jasmine to Mocha, the path with the easiest learning curve is to use Chai with the
expect style. In Jasmine, the assertion methods like
toEqual() use camel case whereas the compliment in Chai uses dot notation,
to.equal(). Both Jasmine and Mocha use
describe() and
it() functions.
2. Test Doubles
Test doubles are often compared to stunt doubles, as they replace one object with another for testing purposes, similar to how actors and actresses are replaced with stunt doubles for dangerous action scenes. In Jasmine, test doubles come in the form of spies. A spy is a function that replaces a particular function where you want to control its behavior in a test and record how that function is used during the execution of that test. Some of the things you can do with spies include:
- See how many times a spy was called
- Specify a return value to force your code to go down a certain path
- Tell a spy to throw an error
- See what arguments a spy was called with
- Tell a spy to call the original function (the function it is spying on). By default, a spy will not call the original function.
In Jasmine, you can spy on existing methods like this:
var userSaveSpy = spyOn(User.prototype, 'save');
You can also create a spy if you do not have an existing method you want to spy on.
var spy = jasmine.createSpy();
In contrast, Mocha does not come with a test double library. Instead, you will need to load in Sinon into your test harness. Sinon is a very powerful test double library and is the equivalent of Jasmine spies with a little more. One thing to note is that Sinon breaks up test doubles into three different categories: spies, stubs, and mocks, each with subtle differences.
A spy in Sinon calls through to the method being spied on whereas you have to specify this behavior in Jasmine. For example:
spyOn(user, 'isValid').andCallThrough() // Jasmine // is equivalent to sinon.spy(user, 'isValid') // Sinon
In your test, the original
user.isValid would be called.
The next type of test double is a stub, which acts as a controllable replacement. Stubs are similar to the default behavior of Jasmine spies where the original method is not called. For example:
sinon.stub(user, 'isValid').returns(true) // Sinon // is equivalent to spyOn(user, 'isValid').andReturns(true) // Jasmine
In your code, if
user.isValid is called during the execution of your tests, the original
user.isValid would not be called and a fake version of it (the test double) that returns
true would be used. In Sinon, a stub is a test double built on top of spies, so stubs have the ability to record how the function is being used.
So to summarize, a spy is a type of test double that records how a function is used. A stub is a type of test double that acts as a controllable replace as well as having the capabilities of a spy.
From my experience, Jasmine spies cover almost everything I need for test doubles so in many situations you won’t need to use Sinon if you are using Jasmine, but you can use the two together if you would like. One reason I do use Sinon with Jasmine is for its fake server (more on this later).
3. Asynchronous Testing
Asynchronous testing in Jasmine 2.x and Mocha is the same.
it('should resolve with the User object', function(done) { var dfd = new $.Deferred(); var promise = dfd.promise(); var stub = sinon.stub(User.prototype, 'fetch').returns(promise); dfd.resolve({ name: 'David' }); User.get().then(function(user) { expect(user instanceof User).toBe(true); done(); }); });
Above,
User is a constructor function with a static method
get. Behind the scenes,
get uses
fetch which performs the XHR request. I want to assert that when
get resolves successfully, the resolved value is an instance of
User. Because I have stubbed out
User.prototype.fetch to return a pre-resolved promise, no real AJAX request is made. However, this code is still asynchronous.
By simply specifying a parameter in the
it callback function (I have called it
done like in the documentation but you can call it whatever you want), the test runner will pass in a function and wait for this function to execute before ending the test. The test will timeout and error if
done is not called within a certain time limit. This gives you full control on when your tests complete. The above test would work in both Mocha and Jasmine 2.x.
If you are working with Jasmine 1.3, asynchronous testing was not so pretty.
Example Jasmine 1.3 Asynchronous Test
it('should resolve with the User object', function() { var flag = false; var david; runs(function() { var dfd = new $.Deferred(); var promise = dfd.promise(); dfd.resolve({ name: 'David' }); spyOn(User.prototype, 'fetch').andReturn(promise); User.get().then(function(user) { flag = true; david = user; }); }); waitsFor(function() { return flag; }, 'get should resolve with the model', 500); runs(function() { expect(david instanceof User).toBe(true); }); });
In this Jasmine 1.3 asynchronous test example, Jasmine will wait a maximum of 500 milliseconds for the asynchronous operation to complete. Otherwise, the test will fail.
waitsFor() is constantly checking to see if
flag becomes true. Once it does, it will continue to run the next
runs() block where I have my assertion.
4. Sinon Fake Server
One feature that Sinon has that Jasmine does not is a fake server. This allows you to setup fake responses to AJAX requests made for certain URLs.
it('should return a collection object containing all users', function(done) { var server = sinon.fakeServer.create(); server.respondWith("GET", "/users", [ 200, { "Content-Type": "application/json" }, '[{ "id": 1, "name": "Gwen" }, { "id": 2, "name": "John" }]' ]); Users.all().done(function(collection) { expect(collection.toJSON()).to.eql([ { id: 1, name: "Gwen" }, { id: 2, name: "John" } ]); done(); }); server.respond(); server.restore(); });
In the above example, if a
GET request is made to
/users, a 200 response containing two users, Gwen and John, will be returned. This can be really handy for a few reasons. First, it allows you to test your code that makes AJAX calls regardless of which AJAX library you are using. Second, you may want to test a function that makes an AJAX call and does some preprocessing on the response before the promise resolves. Third, maybe there are several responses that can be returned based on if the request succeeds or fails such as a successful credit card charge, an invalid credit card number, an expired card, an invalid CVC, etc. You get the idea. If you have worked with Angular, Sinon’s fake server is similar to the $httpBackend service provided in angular mocks.
5. Running Tests
Mocha comes with a command line utility that you can use to run tests. For example:
mocha tests --recursive --watch
This assumes your tests are located in a directory called
tests. The recursive flag will find all files in subdirectories, and the watch flag will watch all your source and test files and rerun the tests when they change.
Jasmine however does not have a command line utility to run tests. There are test runners out there for Jasmine, and a very popular one is Karma by the Angular team. Karma also allows support for Mocha if you’d like to run your Mocha tests that way.
Summary
In conclusion, the Jasmine framework has almost everything built into it including assertions/expectations and test double utilities (which come in the form of spies). However, it does not have a test runner so you will need to use a tool like Karma for that. Mocha on the other hand includes a test runner and an API for setting up your test suite.
So, if you were to choose a test framework setup today, what might it look like?
If you go with Jasmine, you will likely use:
- Karma (for the test runner)
- Sinon (possibly for its fake server unless your framework provides an equivalent, like
$httpBackendif you are using Angular)
If you go with Mocha, you will likely use:
- Chai (for assertions)
- Sinon (for test doubles and its fake server)
- Karma or
mochaCLI (for the test runner)
Trying to figure out testing libraries/frameworks to use for JavaScript can be tough but hopefully this article has made it more clear as to what some of the main differences are between Jasmine and Mocha. You can’t really go wrong with either choice. The important thing is that you!
Master JavaScript in 4 Weeks
Master JavaScript in 4 Weeks | https://www.codementor.io/javascript/tutorial/javascript-testing-framework-comparison-jasmine-vs-mocha | CC-MAIN-2017-22 | refinedweb | 1,710 | 64.71 |
CAN DBC to C (and CSV, JSON and XML) compiler using the mpc parser combinator library
This program turns a DBC file into a number of different formats.
dbcc is a program for converting a DBC file primarily into into C code that can serialize and deserialize CAN messages into structures that represent those messages and signals. It is also possible to print out the information contained in a structure.
See the license file for details of the license for this program, it is released under the MIT license. Dependencies, if linked against, may have their own license and their own set of restrictions if built against.
The sources file mpc.c and mpc.h originate from a parser combinator written in C called MPC and are licensed under the 3 Clause BSD license.
To build, you only need a C (C99) compiler and Make (probably GNU make, I make no effort to support other Make implementations). The dbcc program itself it written in what should be portable C with the only external dependency being your platforms C library.
You should be able to type:
make
To build, an executable called 'dbcc' is produced. To test run the tests, xmllint is required.
The code generator can make code to unpack a message (turn some bytes into a data structure), decode a message (apply a scaling/offset minimum and maximum values to the values in a data structure), and the inverse can be done (pack/encode).
You can look at the code generated from the DBC files within the project to get an understanding of how it should work.
If you want to process a CAN message that you have received you will need to call the 'unpack_message'. The code generate is agnostic to the CPUs byte order, it takes a 'uint64_t' value containing a single CAN packet (along with the CAN ID and the DLC for the that packet) and unpacks that into a structure it generates. The first byte of the CAN packet should be put in the least significant byte of the 'uint64_t'.
You can use the following functions to convert to/from a CAN message:
static uint64_t u64_from_can_msg(const uint8_t m[8]) { return ((uint64_t)m[7] << 56) | ((uint64_t)m[6] << 48) | ((uint64_t)m[5] << 40) | ((uint64_t)m[4] << 32) | ((uint64_t)m[3] << 24) | ((uint64_t)m[2] << 16) | ((uint64_t)m[1] << 8) | ((uint64_t)m[0] << 0); }
static void u64_to_can_msg(const uint64_t u, uint8_t m[8]) { m[7] = u >> 56; m[6] = u >> 48; m[5] = u >> 40; m[4] = u >> 32; m[3] = u >> 24; m[2] = u >> 16; m[1] = u >> 8; m[0] = u >> 0; }
The code generator will make a structure based on the file name of the DBC file, so for the example DBC file 'ex1.dbc' a data structure called 'can_obj_ex1_h_t' is made. This structure contains all of the CAN message structures, which in turn contain all of the signals. Having all of the messages/signals in one structure has advantages and disadvantages, one of the things it makes easier is defining the data structures needed.
/* reminder of the 'unpack_message' prototype */ int unpack_message(can_obj_ex1_h_t *o, const unsigned long id, uint64_t data, uint8_t dlc);
static can_obj_ex1_h_t ex1;
uint8_t can_message_raw[8]; unsigned long id = 0; uint8_t dlc = 0; your_function_to_receive_a_can_message(can_message_raw, &id, &dlc); if (unpack_message(&ex1, id, can_message_u64, dlc) < 0) { // Error Condition; something went wrong return -1; }
'unpack_message' calls the correct unpack function for that ID, as an example for ID '0x020':
case 0x020: return unpack_can_0x020_MagicCanNode1RBootloaderAddress(&o->can_0x020_MagicCanNode1RBootloaderAddress, data, dlc);
The unpack function populates the message object in the 'can_obj_ex1_h_t' structure for that ID. The individual signals can then be decoded with the appropriate functions for that signal. For example:
uint16_t b = 0; if (decode_can_0x020_MagicNode1R_BLAddy(o, &b)) { /* error */ }
To transmit a message, each signal has to be encoded, then the pack function will return a packed message.
Some other notes:
For a specification, as I understand it, of the DBC file format, see dbc.md. This is a work in progress.
There is a Vim syntax file for DBC files in the project, called dbc.vim
As well as C, XML can be generated, the project contains an XSD and XSLT file for the generated XML.
An XML based file that can be imported into Beyond Security's beSTORM and used to test CAN BUS infrastructure.
A flat CSV file can be generated, which is easier to import into Excel.
A JSON file can be generated, which is what all the cool kids use nowadays.
Consult the manual page for more information about the precise operation of the program.
It would be possible to generate nice (ASCII ART) images that show how a message is structured, which helps in understanding the message in question, and is useful for documentation purposes, for example, something like:
Message Name: Example-1 Message ID: 0x10, 16 DLC: 1 (8-bits) +-----+-----.-----.-----.-----+-----.-----+-----+ | | | | | | | | | | +-----+-----.-----.-----.-----+-----.-----+-----+ 0 1 2 3 4 5 6 7 Bit 0: Signal-Name-1, 1 bit signal, scalar 1.0, offset 0 Bits 1-2: Signal-Name-2, 4 bit signal, signed, Motorola, ... ... etcetera ...
Or something similar. This would be another output module. | https://xscode.com/howerj/dbcc | CC-MAIN-2021-10 | refinedweb | 852 | 58.01 |
Opened 8 years ago
Closed 8 years ago
Last modified 8 years ago
#2044 closed merge (fixed)
"Can't unify" error in debugger
Description
Debugging the attached array1.hs under GHCi gives the following error:
[haskell]$ ghci GHCi, version 6.8.2: :? for help Loading package base ... linking ... done. Prelude> :load array1.hs [1 of 1] Compiling Main ( array1.hs, interpreted ) Ok, modules loaded: Main. *Main> :break rsRandomArray Breakpoint 0 activated at array1.hs:(31,0)-(42,79) *Main> main Loading package array-0.1.0.0 ... linking ... done. Loading package old-locale-1.0.0.0 ... linking ... done. Loading package old-time-1.0.0.0 ... linking ... done. Loading package random-1.0.0.0 ... linking ... done. Array 1: array Stopped at array1.hs:(31,0)-(42,79) _result :: ST s (UArray Idx Double) = _ [array1.hs:(31,0)-(42,79)] *Main> :step Stopped at array1.hs:31:21-53 ghc-6.8.2: panic! (the 'impossible' happened) (GHC version 6.8.2 for i386-unknown-linux): Can't unify Please report this as a GHC bug: [array1.hs:31:21-53] *Main> :quit Leaving GHCi.
I'm running Fedora 8 with gcc version 4.1.2 20070925 (Red Hat 4.1.2-33) and ghc-6.8.2-2.fc8.
Attachments (2)
Change History (18)
Changed 8 years ago by r6144
comment:1 Changed 8 years ago by igloo
- difficulty set to Unknown
- Milestone set to 6.8.3
Thanks for the report; I can reproduce the problem.
comment:2 Changed 8 years ago by igloo
- Owner set to simonpj
...but not with the HEAD.
This program:
{-# LANGUAGE ScopedTypeVariables, ExistentialQuantification #-} import Control.Monad.ST.Strict import Data.Array.ST rsRandom :: ST s a rsRandom = undefined write :: Int -> ST s (forall ss . (STUArray ss Int Double) -> ST ss ()) write i = rsRandom >>= \x -> return (\buf -> writeArray buf i x)
is accepted by the 6.8 branch, but not the HEAD. I'd expect it to be rejected too (x is monomorphic, and generalisation won't make a higher rank type), so I think the HEAD is right, but I will let Simon PJ have the last word...
I don't think this is worth fixing just for 6.8.3, unless there are other programs that the HEAD also accepts that trigger the problem, so if the program ought to be rejected then I think that we can close this ticket.
comment:3 Changed 8 years ago by r6144
-XImpredicativeTypes (implied by -fglasgow-exts) appears to be necessary for array1.hs as well as igloo's simpler example.
To make the original array1.hs compile with GHC 6.9.20080323, I have to expand the do statements involving polymorphic lambda-bound variables, e.g. "do { w <- writeRandoms ; return (newArray_ (0,n-1) >>= w) }" into "writeRandoms >>= \w -> return (newArray_ (0,n-1) >>= w)". If I understand correctly, -XImpredicativeTypes allows w to be polymorphic.
After this modification, array1.hs (called array1-orig.hs below) compiles, but the original problem persists:
[haskell]$ ~/apps/ghc-6.9.20080323/bin/ghci GHCi, version 6.9.20080323: :? for help Loading package base ... linking ... done. Prelude> :load array1-orig.hs [1 of 1] Compiling Main ( array1-orig.hs, interpreted ) Ok, modules loaded: Main. *Main> :break rsRandomArray Breakpoint 0 activated at array1-orig.hs:(32,0)-(43,86) *Main> main Loading package array-0.1 ... linking ... done. Loading package old-locale-1.0 ... linking ... done. Loading package old-time-1.0 ... linking ... done. Loading package random-1.0 ... linking ... done. Array 1: array Stopped at array1-orig.hs:(32,0)-(43,86) _result :: ST s (UArray Idx Double) = _ [array1-orig.hs:(32,0)-(43,86)] *Main> :step Stopped at array1-orig.hs:32:21-53 ghc-6.9.20080323: panic! (the 'impossible' happened) (GHC version 6.9.20080323 for i386-unknown-linux): Can't unify Please report this as a GHC bug: [array1-orig.hs:32:21-53] *Main> :quit Leaving GHCi. [
Changed 8 years ago by r6144
Modified version of array1.hs that compiles with ghc 6.9.20080323
comment:4 Changed 8 years ago by simonpj
- Owner changed from simonpj to pepe
The "can't unify" message comes from RtsClosureInspect, which is Pepe and Simon's debugger. I suspect it's confused by the for-all in the type.
Ian is right, incidentally, that the short program he gives should be rejected unless you specify -XImpredicativeTypes.
So I'm assigning this bug to Pepe.
Simon
comment:5 Changed 8 years ago by simonpj
- Cc mnislaih@… added
And adding Pepe to the cc list. Simon
comment:6 Changed 8 years ago by mnislaih
- Owner changed from pepe to mnislaih
- Status changed from new to assigned
Thanks for CC'ing, I had missed this ticket.
At first I though this problem was an instance of #1995, but it turns out your suspicion was right. The RTTI mechanism panics when trying to reconstruct the type for buildBuf in line 3. This is the 'full' error obtained via initTcPrintErrors :
Top level: Cannot match a monotype with `ST s (forall s'. ST s' (STUArray s' Idx Double))' Expected type: ST s (forall s'. ST s' (STUArray s' Idx Double)) Inferred type: t ghc-6.9.20080404: panic! (the 'impossible' happened) (GHC version 6.9.20080404 for i386-apple-darwin): Can't unify
So GHC is refusing to unify the tyvar with an impredicative type. This tyvar is created as follows:
newVar kind = mkTyVarTy `fmap` newFlexiTyVar kind
in this case with kind argType.
How should the tyvars used by the RTTI mechanism be created to handle this situation ?
And, do we need to handle it at all? At runtime we handle values, which are monomorphically typed. It looks to me that the type recovered for buildBuf should be just:
buildBuf :: ST s (ST s' (STUArray s' Idx Double)
Does that make sense?
comment:7 Changed 8 years ago by simonpj
I don't fully grok the debugger type reconstruction, but newBoxyTyVar might be what you want. It does not insist on unifying with a monotype.
Simon
comment:8 Changed 8 years ago by mnislaih
The way I see it, :print is dealing with concrete values here, and a value has a factual type. It does not make sense to impose restrictions like class predicates or higher rank foralls on the value's type. Thus I believe those higher-rank foralls should be dropped.
If we have a function type on the other hand, the foralls should be respected. But :print should not touch the types of function types anyway.
comment:9 Changed 8 years ago by simonpj
A value can be
- A basic type like Int
- A function, like Int -> Int
- An overloaded function like forall a. Eq a => a -> a, or non-function like forall a. Num a => a
- A polymorphic function like forall a. [a] -> [a], or non-function like forall a. [a]
- With impredicative polymorphism, a data structure containing polymorphic values, like [forall a. a ->a] or [forall a. Eq a = a -> a]
These are all perfectly concrete values. A function of type forall a. Eq a => a -> a takes two arguments not one, for example. I'm not sure what you mean by a "factual type", nor what you mean by "should not touch the types of function types".
It's true that in the representation, the foralls are dropped, so a function of type forall a. [a] -> [a] takes just one argument.
Simon
comment:10 Changed 8 years ago by mnislaih
Sorry, by "should not touch the types of function types", I mean that :print can only reconstruct types for non-function values, and thus it does not deal with the types of function values. A function value for :print is a Fun closure.
When a call to a polymorphic function is done, the outer level foralls are instantiated and eliminated. The role of :print is to find out what is the particular instantiation. But this is true for outer level foralls only. For higher rank foralls inside Type Constructors, that is, impredicative types (is this the correct terminology ?) I am in doubt, since I don't understand the implications of impredicative types. These foralls are restrictions too after all, which have already been checked. Is it ok to drop them? I need to do some reading.
By the way an interesting question about typeclass predicates. Suppose we have a function type forall a. Show a => a -> a. If :print recovers a concrete type for the first arg., then by assumption this type is an instance of Show. If :print does not recover a type, it would be nice to pack the dictionary, which :print has access to, and say "x has type Show a => a and you can call show for it in GHCi", but I don't see how that can be expressed. But even more, maybe can we use the dictionaries themselves for recovering more types ?
comment:11 Changed 8 years ago by simonpj
I don't understand your debugger well enough to give you a coherent response. My guess is that newBoxyTyVar will get you past the current "cant unify", albeit perhaps present some other part of your debugger with a polymorphic type it didn't expect.
I suggest you have a chat with Simon M and/or Bernie initially.
Meanwhile this bug is only going to affect people using the more exotic GHC extensions, I think.
Still, doing something less unfriendly than crashing would be a useful step forward, and you can probably do that regardless?
Simon
comment:12 Changed 8 years ago by mnislaih
I tried with boxy tyvars and that makes the trick almost. The problem now is in the side-effect free unification procedure living in types/Unify.hs (previously TcGadt.hs). It fails when asked, at some point later in the debugger, to unify the type of rsRandomArray with itself.
I think I will simply switch to boxyUnify here too, and that should suffice to close this ticket.
comment:13 Changed 8 years ago by mnislaih
Oops, I mean the type of buildBuf
buildBuf :: ST s (forall s'. ST s' (STUArray s' Idx Double))
comment:14 Changed 8 years ago by mnislaih
- Cc igloo@… added
- Owner changed from mnislaih to igloo
- Status changed from assigned to new
- Type changed from bug to merge
Fixed, merge to stable
Mon Apr 21 10:13:22 PDT 2008 pepe <[email protected]> * Fix #2044 (:printing impredicatively typed things)
comment:15 Changed 8 years ago by igloo
- Resolution set to fixed
- Status changed from new to closed
- Test Case set to print033
Merged
comment:16 Changed 8 years ago by igloo
- Cc igloo@… removed
The offending program | https://ghc.haskell.org/trac/ghc/ticket/2044 | CC-MAIN-2015-48 | refinedweb | 1,775 | 67.25 |
For instance, here is an example of a BlogEntry class using SQLObject
Here, we have a blog entry abstraction. The BlogEntry class defines a meta class called sqlmeta. This meta class is used to specify table-specific information used by the database when the table is created. For instance, the underlying table in the example will be called blog_entry and will use the id column is the primary key. We have also defined several columns for our class. These columns will serve as attributes for any instances of this class. Once an instance of BlogEntry is created, the ORM will automatically create a table row in the database.
#SQLObject declaration example.
from sqlobject import *
class BlogEntry(SQLObject):
"""An abstraction representing a BlogEntry."""
class sqlmeta:
table ='blog_entry'
idName ='id'
uuid = StringCol(length=36,\
unique=True,\
alternateID=True,\
alternateMethodName='by_uuid',\
default=gen_uuid)
title=StringCol(length=80,default="Title Placeholder")
body=StringCol(default="")
user=ForeignKey('User', default=None)
I consider this to be a real strength of ORM technology. It drastically simplifies the abstraction storage requirement. There is no need to write SQL CREATE statements. Or INSERT and UPDATE statements for that matter. There is nothing specifically wrong is SQL. SQL is extremely expressive and powerful. The problem arises when combining SQL with application logic in an interleaved manor. This leads to unmaintainable systems.
One approach to decoupling the SQL required for persistent objects from the behavior implemented by the objects in an object-oriented system is define SQL templates. For example, we might have an define_blog_entry.sql template file. This file could then be read by some database module that then executes the SQL. The developer would then write several other templates for UPDATE, INSERT, and various other database activities. ORM libraries do this very well. There is a very transparent layer that manages persistence.
OK, so how about querying? How do we get our objects back from the database? Well, the ORM also does this. From the example, our BlogEntry class inherits a select() class method from the SQLObject class. Using this method we can pass various criteria in order to retrieve BlogEntry instances.
I think this is the key weakness in the ORM. In a large percentage of cases, it serves well. All we want to retrieve are blog entries. What about when we need multiple types of objects? There is really no way to do this. At least not sensibly. In our example, all we can do is BlogEntry.select(). There is no BlogEntryUser.select() method to retrieve BlogEntry instances and User instances in the same query. Multiple types means multiple queries in ORM land.
SQL along with relational databases are indispensable. Especially the SELECT statement. It is by fore the most effective way to retrieve complex data. ORM technology has done a great job exploiting most of the power SQL has to offer. I just don't thing the querying functionality is as flexible as it could be in most cases. | http://www.boduch.ca/2009/01/orm-strengths-and-shortcomings.html | CC-MAIN-2017-43 | refinedweb | 493 | 60.61 |
No Place Like Home
Our. That changes today!
Let’s build a homepage
By default,
cheerskevin.com tries to serve the
index.html file. Prior to this post, I had a manually-created file sitting there, just pointing to the most recent blog post. But now we can automatically build it as a React component:
There’s a lovely little static page. Though we don’t have to keep everything in a single file like this. The only constraint for our renderer is that whatever we
export default down at the bottom, needs to be a renderable React component. Content like the
<html lang='en'> is stuff I think we’re going to find ourselves reusing on most pages. So I’m going to go ahead and extract that to a new file,
PageWrapper.js:
Here, we’re creating another component that expects
children and a
title field, which it conveniently inserts for us. Now we can go back to our Homepage component and shrink it down a little bit!
Much nicer - and now we can reuse the PageWrapper component for other pages. We can just change the contents of that tag, and pass it a different title.
<PageWrapper title="About CheersKevin.com"> for an about page would work nicely!
Note that we use
import PageWrapper from './PageWrapper'; to pull in the wrapper component. Let’s use the same technique to pull in our article metadata we gathered in the last post.
Snagging the metadata
Our article metadata lives in a file called
manifest.yml, but if we try to import that outright, we’re going to run into a small issue: we can’t really just require a
yml file as though it were JavaScript. Remember that the file itself looks like this:
That’s…not JavaScript. Instead, we need to grab a library to convert YAML into a nice JavaScript object. A quick Google search finds
js-yaml, so let’s install that!
This library will convert YAML markup into a JS object, but importantly, we still need to read the YAML from the file ourselves. Thankfully, Node comes with the
fs filesystem library which can do that for us. Let’s update our Homepage component to pull in this information:
We grab the
manifest.yml file with
fs.readFileSync, then pass that to
yaml.safeLoad. That gives us the post information as a JavaScript array. That means that once inside our render method, we can use
map to transform each record into some HTML of its own. Here’s the result:
Not bad for a small amount of work! Of course, the manifest also has stuff like lead image and color scheme information, post dates, and more. So we can definitely expand on this (not to mention, style it up a fair bit). But now that we have our
manifest.yml set up, and the ability to create static HTML from React components, we’re all set to move forward with our great and awesome homepage!
That is, of course, outside of the scope of this article, so you’ll just have to come back later to see the fancy styled page in a week or two! | https://cheerskevin.com/no-place-like-home.html | CC-MAIN-2017-26 | refinedweb | 530 | 74.69 |
In Python's Tkinter OptionMenu, is it possible to have a list of display options, but on selection, it sets a value to be some other value?
Suppose I had
variable = tk.IntVar(master)
OptionMenu(master, variable, 1, 2).pack()
options = {1:"one",2:"two"}
You already have it. Use the dictionary to map your displayed options to the actual values you want.
EG:
import Tkinter as tk master = tk.Tk() variable = tk.StringVar(master) options = {"one": 1, "two": 2} tk.OptionMenu(master, variable, *options.keys()).pack() ... wanted = options[variable.get()]
Please note the splat operator,
*, used to unpack the keys as a comma separated list of arguments to
OptionMenu. Later when you want the option's "value" use
variable.get() as the "key" in the dictionary. | https://codedump.io/share/OMGeFAOjzUib/1/tkinter-optionmenu-displayoptions-and-assignment-values | CC-MAIN-2017-47 | refinedweb | 127 | 53.88 |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
Hi,
I have created a page under a particular namespace, which is not access restricted. When I am trying to view my page which i created I am getting following error
Page level restrictions have been applied to a parent of the current page. These restrictions limit access to certain users or groups and apply to all pages underneath the parent.
Can someone please help me with how to get my page back ? I am not admin of the parent page.
There is a contradiction in your question - you say the space is not access restricted, but the message you are getting clearly says that it is. That's a little confusing, but the error message is the important bit.
You'll need to talk to the space owners, your admins, or the owner of the parent page - these people will be able to explain the restrictions placed on there and update them to get your access. | https://community.atlassian.com/t5/Confluence-questions/I-am-not-able-to-view-my-page-which-I-created-in-wiki-labcollab/qaq-p/690705 | CC-MAIN-2018-39 | refinedweb | 179 | 68.5 |
Coding Destructible Pixel Terrain: How to Make Everything Explode
This Cyber Monday Envato Tuts+ courses will be reduced to just $3. Don't miss out.
In this tutorial, we'll implement fully destructible pixel terrain, in the style of games like Cortex Command and Worms. You'll learn how to make the world explode wherever you shoot it - and how to make the "dust" settle on the ground to create new land.
Note: Although this tutorial is written in Processing and compiled with Java, you should be able to use the same techniques and concepts in almost any game development environment.
Final Result Preview
You can play the demo yourself, too. WASD to move, left click to shoot explosive bullets, right click to spray pixels.
Step 1: The Terrain
In our sidescrolling sandbox, the terrain will be the core mechanic of our game. Similar algorithms often have one image for the terrain's texture, and another as a black and white mask to define which pixels are solid. In this demo, the terrain and its texture all are one image, and pixels are solid based on whether or not they're transparent. The mask approach would be more appropriate if you want to define each pixel's properties, like how likely it'll dislodge or how bouncy the pixel will be.
To render the terrain, the sandbox draws the static pixels first, then the dynamic pixels with everything else on top.
The terrain also has methods for finding out whether a static pixel at a location is solid or not, and methods for removing and adding pixels. Probably the most effective way of storing the image is as a 1 dimensional array. Getting a 1D index from a 2D coordinate is pretty simple:
index = x + y * width
In order for dynamic pixels to bounce, we'll need to be able to find out the surface normal at any point. Loop through a square area around the desired point, find all the solid pixels nearby and average their position. Take a vector from that position to the desired point, reverse and normalize it. There's your normal!
The black lines represent the normals to the terrain at various points.
Here's how that looks in code:
normal(x,y) { Vector avg for x = -3 to 3 // 3 is an arbitrary number for y =-3 to 3 // user larger numbers for smoother surfaces if pixel is solid at (x + w, y + h) { avg -= (x,y) } } } length = sqrt(avgX * avgX + avgY * avgY) // distance from avg to the center return avg/length // normalize the vector by dividing by that distance }
Step 2: The Dynamic Pixel and Physics
The "Terrain" itself stores all of the non-moving static pixels. Dynamic pixels are pixels currently in motion, and are stored separately from the static pixels. As the terrain explodes and settles, pixels get switched between static and dynamic states as they dislodge and collide. Each pixel is defined by a number of properties:
- Position and velocity (required for the physics to work).
- Not just the location, but also the pixel's previous location. (We can scan between the two points to detect collisions.)
- Other properties include the pixel's color, stickiness, and bounciness.
In order for the pixel to move, its position needs to be forwarded with its velocity. Euler integration, while inaccurate for complex simulations, is simple enough for us to efficiently move our particles:
position = position + velocity * elapsedTime
The
elapsedTime is the amount of time elapsed since the last update. The accuracy of any simulation can be entirely broken if the
elapsedTime is too variable or too large. This isn't as much of an issue for dynamic pixels, but it will be for other collision detection schemes.
We'll use fixed-size timesteps, by taking the elapsed time and splitting it up into constant sized chunks. Each chunk is a full "update" to the physics, with any left over being sent into the next frame. for (i = 0; i < timesteps; i++) { update(16/1000) // update physics }
Step 3: Collision Detection
Detecting collisions for our flying pixels is as simple as drawing some lines.
Bresenham's line algorithm was developed in 1962 by a gentleman named Jack E. Bresenham. To this day, it's been used for drawing simple aliased lines efficiently. The algorithm sticks strictly to integers and uses mostly addition and subtraction in order to efficeintly plot lines. Today we'll use it for a different purpose: collision detection.
I'm using code borrowed from an article on gamedev.net. While most implementations of Bresenham's line algorithm reorders the drawing order, this particular one allows us to always scan from start to end. The order is important for collision detection, otherwise we'll be detecting collisions at the wrong end of the the pixel's path.
The slope is an essential part of Bresenham's line algorithm. The algorithm works by splitting up the slope into its "rise" and "run" components. If, for example, the line's slope were 1/2, we can plot the line by placing two dots horizontally, going up (and right) one, and then two more.
The algorithm I'm showing here accounts for all scenarios, whether the lines has a positive or negative slope or if it's vertical. The author explains how he derives it on gamedev.net.
rayCast(int startX, int startY, int lastX, int lastY) { int deltax = (int) abs(lastX - startX) int deltay = (int) abs(lastY - startY) int x = (int) startX int y = (int) startY int xinc1, xinc2, yinc1, yinc2 // Determine whether x and y is increasing or decreasing if (lastX >= startX) { // The x-values are increasing xinc1 = 1 xinc2 = 1 } else { // The x-values are decreasing xinc1 = -1 xinc2 = -1 } if (lastY >= startY) { // The y-values are increasing yinc1 = 1 yinc2 = 1 } else { // The y-values are decreasing yinc1 = -1 yinc2 = -1 } int den, num, numadd, numpixels if (deltax >= deltay) { // There is at least one x-value for every y-value xinc1 = 0 // Don't change the x when numerator >= denominator yinc2 = 0 // Don't change the y for every iteration den = deltax num = deltax / 2 numadd = deltay numpixels = deltax // There are more x-values than y-values } else { // There is at least one y-value for every x-value xinc2 = 0 // Don't change the x for every iteration yinc1 = 0 // Don't change the y when numerator >= denominator den = deltay num = deltay / 2 numadd = deltax numpixels = deltay // There are more y-values than x-values } int prevX = (int)startX int prevY = (int)startY for (int curpixel = 0; curpixel <= numpixels; curpixel++) { if (terrain.isPixelSolid(x, y)) return (prevX, prevY) and (x, y) prevX = x prevY = y } return null // nothing was found }
Step 4: Collision Handling
The dynamic pixel can do one of two things during a collision.
- If it's moving slowly enough, the dynamic pixel is removed and a static one is added to the terrain where it collided. Sticking would be our simplest solution. In Bresenham's line algorithm, it's best to keep track of a previous point and a current point. When a collision is detected, the "current point" will be the first solid pixel the ray hits, while the "previous point" is the empty space just prior to it. The previous point is exactly the location wehre we need to stick the pixel.
- If it's moving too fast, then we bounce it off the terrain. This is where our surface normal algorithm comes in! Reflect the ball's initial velocity across the normal in order to bounce it.
The angle either side of the normal is the same.
// Project velocity onto the normal, multiply by 2, and subtract it from velocity normal = getNormal(collision.x, collision.y) // project velocity onto the normal using dot product projection = velocity.x * normal.x + velocity.y * normal.y // velocity -= normal * projection * 2
Step 5: Bullets and Explosions!
Bullets act exactly like dynamic pixels. Motion is integrated the same way, and collision detection uses the same algorithm. Our only difference is the collision handling
After a collision is detected, bullets explode by removing all static pixels within a radius, and then placing dynamic pixels in their place with their velocities pointed outwards. I use a function to scan a square area around an explosion's radius to find out which pixels to dislodge. Afterwards, the pixel's distance from the center is used to establish a speed.
explode(x,y, radius) { for (xPos = x - radius; xPos <= x + radius; xPos++) { for (yPos = y - radius; yPos <= y + radius; yPos++) { if (sq(xPos - x) + sq(yPos - y) < radius * radius) { if (pixel is solid) { remove static pixel add dynamic pixel } } } } }
Step 6: The Player
The player isn't a core part of the destructable terrain mechanic, but it does involve some collision detection which will be definitely relevant to problems that'll arrive in the future. I'll explain how collision is detected and handled in the demo for the player.
- For each edge, loop from one corner to the next, checking each pixel.
- If the pixel is solid, start at the center of the player and scan towards that pixel into you hit a solid pixel.
- Move the player away from the first solid pixel you hit.
Step 7: Optimizing
Thousands of pixels are being handled at once, resulting in quite a bit of strain on the physics engine. Like anything else, to make this fast I'd recommend using a language that's reasonably fast. The demo is compiled in Java.
You can do things to optimize on the algorithm level as well. For example, the number of particles from explosions can be reduced by lower the destruction resolution. Normally we find every pixel and turn it into a 1x1 dynamic pixel. Instead, scan every 2x2 pixels, or 3x3, and launch a dynamic pixel of that size. In the demo we use 2x2 pixels.
If you are using Java, garbage collection will be an issue. The JVM will periodically find objects in memory that aren't being used anymore, like the dynamic pixels that are discarded in exchange for static pixels, and try and get rid of those to make room for more objects. Deleting objects, tons of objects, takes time though, and every time the JVM does a cleanup, our game will freeze briefly.
One possible solutions it to use a cache of some sort. Instead of creating/destroying objects all the time, you can simply hold dead objects (like dynamic pixels) to be reused later.
Use primitives wherever possible. For example, using objects for positions and velocities is going to make things a little harder for the garbage collection. It would be even better if you could store everything as primitives in one-dimensional arrays.
Step 8: Making it Your Own
There are many different directions you can take with this game mechanic. Features can be added and customized to match any game style you'd like.
For example, collisions between dynamic and static pixels can be handled differently. A collision mask under the terrain can be used to define each static pixel's stickiness, bounciness, and strength, or likelihood of getting dislodged by an explosion.
There are a variety of different things you can do to guns as well. Bullets can be given a "penetration depth," to allow it to move through so many pixels before exploding. Traditional gun mechanics can also be applied, like a varied rate of fire or, like a shotgun, multiple bullets can be fired at once. You can even, like for the bouncy particles, have bullets bounce off of metal pixels.
Conclusion
2D terrain destruction isn't completely unique. For example, the classics Worms and Tanks remove parts of the terrain on explosions. Cortex Command utilizes similar bouncy particles that we use here. Other games might as well, but I haven't heard of them yet. I look forward in seeing what other developers will do with this mechanic.
Most of what I've explained here is fully implemented in the demo. Please take a look at its source if anything seems ambiguous or confusing. I've added comments to the source to make it as clear as possible. Thanks for reading!
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this postPowered by
| http://gamedevelopment.tutsplus.com/tutorials/coding-destructible-pixel-terrain--gamedev-45 | CC-MAIN-2015-48 | refinedweb | 2,059 | 60.75 |
China quality 7-speed high power fat electric bicycle 36V high speed
US $380-450 / Piece
1 Piece (Min. Order)
250W 26 inch electric bicycle
100 Pieces (Min. Order)
New Model 6061 Aluminum Alloy folding Electric Bicycle/Foldable Electric Bike
US $466-516 / Piece
1 Piece (Min. Order)
import cheap wholesale 26'' mountain electric bicycle bike
US $650-800 / Piece
10 Pieces (Min. Order)
Hot sale cheap motorcycle adult two wheel electrical scooter , electric bicycle , electric bike
US $315.0-358.0 / Piece | Buy Now
1 Piece (Min. Order)
250W 24V 16" Cheap Steel Frame Folding Electric Bicycle, Electric Folding Bike (EF06)
US $188-200 / Piece
30 Pieces (Min. Order)
new cheap 3 wheel electric bicycle
US $450-500 / Unit
5 Units (Min. Order)
26*4.0 1000W big power Fat tire electric Mountain bike/Snow bike/electric bicycle with CE
US $625.0-625.0 / Unit
1 Unit (Min. Order)
250W Cheap Small Folding Electric Bike, Cheap Electric Bicycle with EN15194 (EF01S-3)
US $188-200 / Piece
10 Pieces (Min. Order)
Factory price Cheap Foldable Electric Bicycle
US $1-500 / Unit
1 Unit (Min. Order)
Europe 3 wheel electric bicycle for adult
US $300-660 / Set
1 Set (Min. Order)
2016 hot sale new model foldable electric bicycle
US $510-600 / Piece
1 Piece (Min. Order)
High quality electric bike factory mountain fat tire;mountain electric bicycle
US $700-760 / Piece
10 Pieces (Min. Order)
China made green evs electric bicycle,hidden battery e-bike, hot sell electric bike
US $390-400 / Piece
1 Piece (Min. Order)
Small 48v450w three wheel bicycle for adults electric bicycle
US $230-350 / Piece
1 Piece (Min. Order)
2016 26 inch 48V 500W Chopper fat tire electric bicycle, driving on beach and Mountain
US $570-720 / Piece
10 Pieces (Min. Order)
MOTORLIFE/OEM EN15194 fair price 36v 250w folding electric bicycle
US $280-370 / Piece
10 Pieces (Min. Order)
Long running distance hybrid electric bicycle with good bike components
US $420-470 / Piece
1 Piece (Min. Order)
hidden battery powerful electric bicycle/ebike/ mountain ebike
US $540-750 / Piece
1 Piece (Min. Order)
20 inch Mountain electric bicycle ,electric bike,electric power assisted cycle with alloy wheel
US $230-320 / Piece
5 Pieces (Min. Order)
Super power electric bicycle 5000w stealth bomber electric bike the fastest electric bicycle china
US $2500-3200 / Piece
1 Piece (Min. Order)
Enduro ebike ! Full suspension 72V 5000W Electric Bike ! The most powerful Electric bicycle in the world !
US $3400-5500 / Piece
1 Piece (Min. Order)
36V 17AH MAX DRIVE motor electric bicycle 28inch
US $770-1170 / Piece
1 Piece (Min. Order)
12 Inch Mini Foldable Electric Bicycle Yellow SP12SD-Y
US $345-400 / Piece
20 Pieces (Min. Order)
Battery Power Electric Bicycle
US $699-820 / Unit
100 Units (Min. Order)
Green Environmental Protection Electric City Bike,Mini Folding Brushless Electric Bicycle, Lithium Battery Electronic Bicycle
US $770.0-770.0 / Set | Buy Now
1 Set (Min. Order)
Yunshine 2016 new experience 36v battery e bike electric bicycle
US $400-650 / Piece
1 Piece (Min. Order)
60V20AH 450W Motor 60KM Range Very Cheap Electric Bicycle
US $240.0-240.0 / Piece
1 Piece (Min. Order)
Most popular Chinese electric bike folding of Unisex cheap electric bicycle
US $380-420 / Piece
1 Piece (Min. Order)
cheap city electric bike with en15194 / cheap electric bicycle / classical city e bike
US $225.0-230.0 / Pieces
10 Pieces (Min. Order)
cheap electric bicycle/ lead acid bicycle/ lithium bicycle
US $200-280 / Piece
75 Pieces (Min. Order)
26inch or 700C City Electrical Bicycle,OEM E-bike with Good Optional Accessories
US $299-399 / Piece
1 Piece (Min. Order)
COOL 350W Cruiser Electric Bicycle for sale
US $450-520 / Piece
1 Piece (Min. Order)
snow electric bicycle/fatbike/fat mountain children electric bicycle
US $1-750 / Piece
5 Pieces (Min. Order)
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show electric bicycle or other products of your own company? Display your Products FREE now!
Related Category
Product Features
Supplier Features
Supplier Types
Recommendation for you
related suppliers
related Guide
Trade tools | http://www.alibaba.com/showroom/electric-bicycle.html | CC-MAIN-2016-44 | refinedweb | 693 | 66.33 |
Hi everyone! I’m a React developer and I have been building chat apps using CometChat and React for some tutorials. Along the way, I noticed that I have similar interface component that I used again and again in these tutorials. A chat window hardly change in my projects, so I began to think how great it would be to have an NPM module that I can just install and use, instead of copy pasting JSX and CSS code repeatedly.
That’s why I decided to write a reusable chat interface component to use with CometChat that works out of the box. Please welcome, React Chatbox Component library 👋
If you’re interested in jumping to the code, here is the repo.
But if somehow you’re interested in my thought process and experience in publishing this library to NPM, then feel free to read on.
Following this tutorial by Rao, I used Create React App to structure the project files so I can build the library and test it at the same time. The library is a React UI component, so I write all the code inside lib directory and create a named export for the component. This way, adding a new UI component into the library would be easy in the future.
Inside the test directory, I created a very basic React component which renders the library, and I called it from the src/index.js file. Since the entire library project can be run locally, developers can simply clone the repo, install the NPM modules and do npm start without creating another React project.
Finally, there is the npm run build command, which I simply copied from Rao’s tutorial. It will use Babel to transpile all the code inside lib directory while ignoring testing files. As of now this library doesn’t have any test files, but I think it will be useful in the future.
Now that you learned about the project structure, let’s talk about the library itself
The purpose of this library is to create a React component module that can be used to create a Chat component without having to write your own interface and styling code. I created a small, embed-able chat window with a single text input element that processes several props to create a working chat window.
In the chat component, there is a messages prop, an array of objects that contain the message and the sender. In order to differentiate the chat bubbles between the user and their contacts, the component will compare the uid of the user and the sender object. The currently logged in user’s message will be rendered with a blue chat bubble and aligned to the right, while the contacts will be rendered in a white chat bubble and aligned to the left, similar to other popular chat apps that you might have used before.
{% c-block language="javascript" %}
import {
ChatBox
} from 'react-chatbox-component';
const messages = [{
"text": "Hello there",
"id": "1",
"sender": {
"name": "Ironman",
"uid": "user1",
"avatar": "",
},
}, ]
const user = {
"uid": "user1"
}
render() {
return ( <
div className = 'container'
style = {
{
maxWidth: '800px',
paddingTop: '100px'
}
} >
<
div
<
h5 > React Chat Box Example < /h5> <
/div> <
ChatBox messages = {
messages
}
user = {
user
}
/> <
/div>
)
}
{% c-block-end %}
Just add a container and a header, and you’re ready to go!
Once the library is done, I need to find out how I can publish it to NPM. I googled how to publish NPM package, and after
It turns out you just need to register an account with npmjs.com and log in from your console.
{% c-line %} npm login{% c-line-end %}
Also, don’t forget to update your package.json with more details because npmjs.com did use them for showing information to visitors:
{% c-block language="markdown" %}
repository": {
"type": "git",
"url": "git+"
},
"keywords": [
"chat component",
"react component",
"chat box"
],
"author": "Nathan Sebhastian",
"license": "MIT",
"bugs": {
"url": ""
},
{% c-block-end %}
Oh and for a bonus, you might also want to include badges in your repo, I’ve included license, npm current version and pull requests into the repo by looking at the README markdown of React Helmet. Turns out you just needed to select the badge category you want to add and fill in the blank from shields.io.
Pro tip: instead of updating version manually from package.json after updating README with badges, you can use the npm version command to increment the version number of your package:
npm version patch
npm publish
The patch command will update the last number in your semantic version. You can update the second number with minor and the first number with major respectively.
Thank you for reading. I hope you learned a thing or two from this post 🙏 | https://www.cometchat.com/tutorials/react-chatbox-component | CC-MAIN-2020-34 | refinedweb | 787 | 55.98 |
Vijay> For a particular script which uses 'exit' calls, I am getting the Vijay> following error when I invoke the script with the -x option for Vijay> coverage. Vijay> Error in sys.exitfunc: Vijay> Traceback (most recent call last): Vijay> File "D:\Python23\lib\atexit.py", line 20, in _run_exitfuncs Vijay> func(*targs, **kargs) Vijay> File "D:\Python23\Lib\site-packages\coverage.py", line 207, in save Vijay> cache = open(self.cache, 'wb') Vijay> TypeError: an integer is required Vijay> Looks like coverage.py is not able to record the coverage data on Vijay> calling exit. Does anybody know how to solve this? Just a wild-ass guess, but I suspect there's a module imported like from somemodule import * which dumped an "open" symbol into the global namespace, thus hiding the open() builtin. You might try adding this line print open right before the call to open() to see if you're getting the builtin open or not. -- Skip Montanaro Got spam? skip at pobox.com | https://mail.python.org/pipermail/python-list/2004-August/292968.html | CC-MAIN-2014-15 | refinedweb | 167 | 67.45 |
Here's a simple program that uses a pointer. The program compiles but issues this warning. The compiler I use is gcc.
gcc -g -ansi -pedantic -Wall ex9-2-4.c -o ex9-2-4
ex9-2-4.c: In function 'main':
ex9-2-4.c:12 warning: int format, pointer arg (arg 2)
Here's the code.
What conversion specifier do I use for pointers?What conversion specifier do I use for pointers?Code:
/* ex9-2-4.c */
#include <stdio.h>
int main(void)
{
int cost, *p_cost;
p_cost = &cost;
cost = 100;
printf("\nPointer value: %d, points at value: %d\n\n", p_cost, *p_cost);
return 0;
}
P.S. If this question has been asked before on this message board, I'd appreciate someone giving me a link to the appropriate post. Thanks. | https://cboard.cprogramming.com/c-programming/113432-question-about-compiler-warning-printable-thread.html | CC-MAIN-2017-26 | refinedweb | 132 | 71 |
Many times we need to create junit unit tests where we need to create temporary folders or temporary files for executing the testcase. Many times we rely on having a temp folder at particular location and generate all temp files there. Well, it has it’s own disadvantages. Major disadvantage is that you need to cleanup these files manually.
Junit comes with
TemporaryFolder class which you can use for generating temp folders.
The
TemporaryFolder Rule allows creation of files and folders that should be deleted when the test method finishes (whether it passes or fails). Whether the deletion is successful or not is not checked by this rule. No exception will be thrown in case the deletion fails.
Sample usage of
TemporaryFolder Rule is :
public static class HasTempFolder { @Rule public TemporaryFolder folder= new TemporaryFolder(); @Test public void testUsingTempFolder() throws IOException { File createdFile= folder.newFile("myfile.txt"); File createdFolder= folder.newFolder("subfolder"); // ... } }
Let’s make a quick testcase and see how it works.
import java.io.File; import java.io.IOException; import junit.framework.Assert; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class TemporaryFolderTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Test public void testWrite() throws IOException { // Create a temporary file. final File tempFile = tempFolder.newFile("tempFile.txt"); // Write something to it. FileUtils.writeStringToFile(tempFile, "hello world"); // Read it from temp file final String s = FileUtils.readFileToString(tempFile); // Verify the content Assert.assertEquals("hello world", s); //Note: File is guaranteed to be deleted after the test finishes. } }
It’s really easy and useful feature of Junit. Use it next time and you will find it a great help.
Happy Learning !!
10 thoughts on “JUnit – Create Temporary File/Folder using TemporaryFolder @Rule”
When I call newFile(), I get this exception:
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
Any ideas why?
Check you path name – one more time – for typos. Make sure, the directory in which you are creating file – does exist and you have write permission on it.
Hi Lokesh,
Thanks for sharing. It’s helpful.
But I see some temp files getting created and still remain in temp location after running junit code. Can you please let me know is there anyway to avoid this.
Thanks,
Sri
As mentioned “File is guaranteed to be deleted after the test finishes”. There must be something wrong in text code. Please share your test code.
I’m afraid that the claim “File is guaranteed to be deleted after the test finishes” is not correct. From the Javadoc, “The TemporaryFolder Rule allows creation of files and folders that should be deleted when the test method finishes (whether it passes or fails). Whether the deletion is successful or not is not checked by this rule. No exception will be thrown in case the deletion fails.”
They changed the verbiage after 4.10 release. I will update the post.
Hi…….Dear Lokesh,
I m happy to say I m following you site since last year It really
helpful and beneficial.
1.Today I asked how many question you can create in java for a class.?
2.How could you know that how many connections are opened in hibernate ?
3.How can you find size of object in using java program?
4.How could count the repeated word/letters in String/word w/o using collection?
I really not able to find these question on net …..so please help here.
Thanks
Regards
kaushal
Hi Kaushal, You could not find the answers because they cannot be directly programmed using normal java programming. I tried to quick google search for your answers and below are answers which make sense to me.
1) I really do not understand the question properly. Please elaborate.
2) Hibernate does not manage connection pools and it ask the third party connection pool implementations for opening/closing a conneection; so you cannot ask this information from hibernate. One good way is to directly ask from connected database itself. e.g. for MySQL there is a command “show processlist”. It retuen the number of connections opened at any time + 1 (reserved for super user).
3) This one is also tricky and there is no direct solution. Please go through information in given SO thread. Answer mentioning “java.lang.instrument.Instrumentation” makes more sense to me.
4) This should not be too hard to solve. I wrote a quick example. Please modify as per your need.
I hope it helps.
can u provide about junit how we will use in real time in project developing… ?
Interesting. I will soon post a full article on this topic. | https://howtodoinjava.com/junit/junit-creating-temporary-filefolder-using-temporaryfolder-rule/ | CC-MAIN-2022-27 | refinedweb | 778 | 60.41 |
An index space for queries on parallel line overlap. More...
#include <vbl/vbl_ref_count.h>
#include <vbl/vbl_smart_ptr.h>
#include <vgl/vgl_fwd.h>
#include <vifa/vifa_typedefs.h>
Go to the source code of this file.
An index space for queries on parallel line overlap.
The vifa_line_cover class is an index which aids in finding parallel line covers. That is, we have a set of lines, some of which are parallel. The key function is to identify the subset of mutually parallel lines. It is assumed that there is a line space (an array) upon which a set of approximately parallel lines are projected. A measure of projection overlap is defined by the accumulated projected points along this line like shapes. That is, there are groups of parallel line segments having projection overlap.
Modifications: MPP Jun 2003, Ported to VXL from TargetJr
Definition in file vifa_line_cover.h.
Definition at line 68 of file vifa_line_cover.h. | http://public.kitware.com/vxl/doc/development/contrib/gel/vifa/html/vifa__line__cover_8h.html | crawl-003 | refinedweb | 153 | 61.12 |
Drawing with Pythonistas modules
Hey there.
I 've been trying to create the Pong Game in Pythonista.
I have created the game in my PC using python's tkinter module.
However, I am having a difficulty in which library to use. Scene? Ui?
Till now I have tried:
import scene class TutoScene1(scene.Scene): def setup(self): self.background_color = 'green' self.item = scene.ShapeNode(scene.rect(0,0,0,0), color = 'red', position = (self.size.w / 2, self.size.h / 2), anchor_point = (0.5, 0.5), parent = self) def update(self): max_speed = 5 x, y, z = scene.gravity() pos = self.item.position pos.x = self.item.position.x + x * max_speed pos.y = self.item.position.y + y * max_speed self.item.position = pos scene.run(TutoScene1(), scene.PORTRAIT)
And:
import scene import ui class TutoScene2(scene.Scene): def setup(self): self.background_color = 'black' self.paddle = ui.Path.rect(0, 0, 200, 50) self.ball = ui.Path.oval(100, 100, 400, 200) scene.run(TutoScene2(), scene.PORTRAIT)
In the first example dimensions don't work as they should (I get the same Rect no matter the x, y, width, height and in the 2nd example I don't know how to make things slow up (like give them colors etc)
Here is an example pong program. I hope it helps. (It is not well tested. It is just for illustration.) | https://forum.omz-software.com/topic/3367/drawing-with-pythonistas-modules | CC-MAIN-2019-13 | refinedweb | 228 | 64.07 |
Hi Bob,
That makes a lot of sense. Many of our objects cannot be instantiated
without arguments to the Constructors, so I've made sure that all of
them were set up previously and that the Form.copyTo wouldn't come
across anything null.
Form.copyTo() should only be coming across simple single-argument
setters. The object graph (past the Constructors) is very
straightforward. For the life of me I cannot see what's choking
Form.copyTo()...
If I come up with something brilliant, I'll let you know. :-)
Thanks again!
Alvin
On Sun, Oct 19, 2008 at 2:58 PM, Bob Schellink <sabob1@gmail.com> wrote:
> Hi Alvin,
>
> Alvin Townsend wrote:
>>
>> java.lang.IllegalArgumentException: wrong number of
>> net.sf.click.util.ContainerUtils.ensureObjectPathNotNull(ContainerUtils.java:592)
>> at
>> net.sf.click.util.ContainerUtils.copyContainerToObject(ContainerUtils.java:318)
>> at
>> net.sf.click.util.ContainerUtils.copyContainerToObject(ContainerUtils.java:355)
>> at net.sf.click.control.Form.copyTo(Form.java:1710)
>>
>
> This normally happens when an object is instantiated which does not have a
> default empty constructor.
> When you specify a path for your field e.g. new TextField("address.price"),
> Form.copyTo will navigate the
> object graph according to the path. Say you have the following:
>
> field = new TextField("address.price")
> ...
> form.copyTo(client);
>
> the copy logic will try and navigate to the Address from Client. But if
> Address is null on Client Click
> attempts to create a new Address. But the only way this works is if Address
> has a default no arg constructor:
>
> public class Address {
> public Address() {}
> }
>
> If your Address cannot have a no-arg constructor the best way to resolve
> this is to ensure your domain
> objects are valid before invoking form.copyTo(). You could do this by
> overriding Form.copyTo:
>
> public void onInit() {
> ...
> form.copyTo(client) {
> if (client.getAddress() == null) {
> client.setAddress(createAddress());
> }
> super.copyTo(client);
> };
> }
>
> Does this help?
>
> kind regards
>
> bob
>
> | http://mail-archives.apache.org/mod_mbox/click-user/200810.mbox/%3Cb61865290810191230n63cafe8fu66389bd965f1e3d0@mail.gmail.com%3E | CC-MAIN-2014-52 | refinedweb | 314 | 53.17 |
Greetings,
I want to get the position of the mouse inside the rhino viewport as a Point3d without using the getpoint method. Actually, I want to track the mouse all the time. Would you mind to help me find a solution?
Thanks
Greetings,
I assume you are working with RhinoCommon: in that case, you want to use the
MouseCallback class. For documentation, see
Thanks for the response. Yes, I am using rhino common and C#. I have already visited this class, but I did not understand how to get the position of the mouse in the viewport. I think this class is used to add more functionality to the mouse. I also found a method called : ClientToWorld(). Do you have any suggestion on how to use this method?
I was able to Trackdown the solution to this point:
System.Drawing.Point screenPos = System.Windows.Forms.Cursor.Position; Rhino.RhinoDoc doc = Rhino.RhinoDoc.ActiveDoc; RhinoView view = doc.Views.ActiveView; Line line = view.ActiveViewport.ClientToWorld(screenPos); Plane cplane = view.ActiveViewport.ConstructionPlane(); double t; Rhino.Geometry.Intersect.Intersection.LinePlane(line, cplane, out t); A = line.PointAt(t);
The problem is that there This is not the absolute position in top view. So this is the question: How can i get the absolute postition?MouseTracker.gh (10.4 KB)
Second, this is in 2D how can i get the 3d position?
you’ll need “screen to client” and “client to world”.
Thanks that solved the 2D. I’ll attach the solution.
MouseTracker.gh (3.9 KB)
for “3d” you need to do a raycast.Have a look at Intersect namespace or Ray class
If you have a reference to the view port, you can use the frustum line. This is a line in world (model) coordinates that originates from the screen point. See this method and its overrides:
Thankyou all, I used GetFrustumLine() and it workes perfectly for my task. | https://discourse.mcneel.com/t/mouse-position/79571 | CC-MAIN-2020-40 | refinedweb | 316 | 69.58 |
Summary.
In Python 2, UpdateCursor supports the iterator next method to retrieve the next row outside of a loop. In Python 3, the equivalent is performed by using the Python built-in next function.
Syntax
UpdateCursor (in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause})
Properties
Method Overview
Methods
deleteRow ()
Return Value
reset ()
updateRow (row)
Code sample
UpdateCursor example 1
Use UpdateCursor to update a field value by evaluating the values of other fields.
import arcpy fc = 'c:/data/base.gdb/well' fields = ['WELL_YIELD', 'WELL_CLASS'] # Create update cursor for feature class with arcpy.da.UpdateCursor(fc, fields) as cursor: # For each row, evaluate the WELL_YIELD value (index position # of 0), and update WELL_CLASS (index position of 1) for row in cursor: if (row[0] >= 0 and row[0] <= 10): row[1] = 1 elif (row[0] > 10 and row[0] <= 20): row[1] = 2 elif (row[0] > 20 and row[0] <= 30): row[1] = 3 elif (row[0] > 30): row[1] = 4 # Update the cursor with the updated list cursor.updateRow(row)
UpdateCursor example 2
Use UpdateCursor to update a field of buffer distances for use with the Buffer tool.
import arcpy arcpy.env.workspace = 'c:/data/output.gdb' fc = 'c:/data/base.gdb/roads' fields = ['ROAD_TYPE', 'BUFFER_DISTANCE'] # Create update cursor for feature class with arcpy.da.UpdateCursor(fc, fields) as cursor: # Update the field used in Buffer so the distance is based on road # type. Road type is either 1, 2, 3, or 4. Distance is in meters. for row in cursor: # Update the BUFFER_DISTANCE field to be 100 times the # ROAD_TYPE field. row[1] = row[0] * 100 cursor.updateRow(row) # Buffer feature class using updated field values arcpy.Buffer_analysis(fc, 'roads_buffer', 'BUFFER_DISTANCE') | https://desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-data-access/updatecursor-class.htm | CC-MAIN-2020-16 | refinedweb | 280 | 57.06 |
Problem Statement
Suppose you have an array of integers. Input values are all distinct elements. The problem “Find largest d in array such that a + b + c = d” asks to find out the largest element ‘d’ in the set such that a + b + c = d, where all elements are different from each other.
Example
arr[] = {1, 4, 6, 8, 11 }
11
Explanation: The three numbers a, b and c are 1, 4 and 6 and their sum is 11.
arr[] = {2,4,6,10,15 }
No such solution exists.
Explanation: As there are no three numbers, that sums up to a number.
Algorithm
1. Declare a Map. 2. While traversing through the array. 1. Add and insert the sum of two elements in a map with their indexes in a Map. 3. Set the number to the minimum value of an integer, which we have to find out. 4. Search for the third number in a map by checking the difference of two numbers is present in a map. 5. If true then check if their indexes should not be the same. 6. Check for the maximum of d and the maximum of arr[i] and arr[j] and store it to d. 7. Return d.
Explanation
Consider an integer array consisting of distinct integers. Our task is to find out the number in such a way there exist three numbers which sum up to that number. We are going to use Hashing. Hashing provides an efficient solution. Traverse the array and take two array elements at a time and store the sum of those pairs to map with their respective indexes.
We will store the pair because we are searching for d, such that a + b + c = d. Instead of this, we will be searching for a + b = d – c. So at first, when we store the pair and their indices. We will be able to check for element ‘d’ such that d – c exists in the map. This can be done by traversing the array, and then picking up two elements at once. Make the difference of both the elements and search for that difference if exists in the map. If this found to be true, check the current two elements should not be on the same index as the previous pairs on an index.
This is necessary to check if any of the elements should not be repeated on the same index, the repeated number can be considered in a, b, c and d, but their indices, meant to say, the number itself on the same index should not be considered. So we have to check for those indices plagiarism. Now, we need to find out the maximum of arr[i] and arr[j] and check that maximum to d to find out the maximum between them and store it to the d. Because, we have to find out the fourth number d, so we need to find the maximum of array elements, as d is always bigger among a, b, c and d.
Implementation
C++ program to find largest d in array such that a + b + c = d
#include<iostream> #include<unordered_map> using namespace std; int getSumThreeNumber(int arr[], int n) { unordered_map<int, pair<int, int> > MAP; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { MAP[arr[i] + arr[j]] = { i, j }; } } int d_number = INT_MIN; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int third = abs(arr[i] - arr[j]); if (MAP.find(third) != MAP.end()) { pair<int, int> obj = MAP[third]; if (obj.first != i && obj.first != j && obj.second != i && obj.second != j) d_number = max(d_number, max(arr[i], arr[j])); } } } return d_number; } int main() { int arr[] = { 1,4,6,8,11 }; int n = sizeof(arr) / sizeof(arr[0]); int res = getSumThreeNumber(arr, n); if (res == INT_MIN) cout << "No such solution exists"; else cout << res; return 0; }
11
Java program to find largest d in array such that a + b + c = d
import java.util.HashMap; class CheckIndex { int i, j; CheckIndex(int i, int j) { this.i = i; this.j = j; } int checkI() { return i; } int checkJ() { return j; } } class sumOfThreeElementToD { public static int getSumThreeNumber(int[] arr, int n) { HashMap<Integer, CheckIndex> map = new HashMap<>(); for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { map.put(arr[i] + arr[j], new CheckIndex(i, j)); } } int d_number = Integer.MIN_VALUE; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int third = Math.abs(arr[i] - arr[j]); if (map.containsKey(third)) { CheckIndex ci = map.get(third); if (ci.checkI() != i && ci.checkI() != j && ci.checkJ() != i && ci.checkJ() != j) { d_number = Math.max(d_number, Math.max(arr[i], arr[j])); } } } } return d_number; } public static void main(String[] args) { int arr[] = { 1, 4, 6, 8, 11 }; int n = arr.length; int output = getSumThreeNumber(arr, n); if (output == Integer.MIN_VALUE) System.out.println("No such solution exists"); else System.out.println(output); } }
11
Complexity Analysis to Find Largest d in Array such that a + b + c = d
Time Complexity
O(n2) where “n” is the number of elements in the array. We have achieved this complexity because we have used HashMap which allows insertion searching and other operations in O(1) time.
Space Complexity
O(n2) where “n” is the number of elements in the array. Since the HashMap stores addition of pair of different elements of the input. Because of this, the algorithm has quadratic space complexity. | https://www.tutorialcup.com/interview/hashing/find-largest-d-in-array-such-that-a-b-c-d.htm | CC-MAIN-2021-25 | refinedweb | 930 | 70.84 |
JP Hrubant4,108 Points
I need help adding 1 to the counter
In Ruby Loops, I am trying to add 1 to the counter for every time the (string) prints. I have tried various ways but have failed. Please help x
The task is as follows:
Challenge Task 1 of 1.
def repeat(string, times) fail "times must be 1 or more" if times < 1 counter = 0 loop do # YOUR CODE HERE
end end
2 Answers
Samuel Ferree31,715 Points
We can add one to variables in a couple ways, below are two common ways.
counter += 1 counter = counter + 1
Try putting one of them in the function below
def repeat(string, times) fail "times must be 1 or more" if times < 1 counter = 0 loop do puts string # YOUR CODE HERE break if counter > times end end
JP Hrubant4,108 Points
Thank you everyone!
Jeff Lange8,788 Points
Jeff Lange8,788 Points
This is more style preference, but it reads more clearly to me to avoid the break statement and use a while loop | https://teamtreehouse.com/community/i-need-help-adding-1-to-the-counter | CC-MAIN-2020-24 | refinedweb | 175 | 76.9 |
ordfunction
chrfunction.
cipher.pyEncoding
encode_charfunction
encode_char
encode_strfunction to encode 4-letter strings
encode_str
cipher.pyDecoding
decode_charfunction
decode_char
decode_strfunction to decode 4-letter strings
decode_str
In this lab you will gain practice writing functions by implementing Julius Caesar’s cipher to encode and decode secret 4-letter strings. For example, the string
"code" encodes to
"dpef". In a later exercise you will improve your functions to support encoding and decoding
str values of any length. Soon you’ll be able to send your crush secret love messages on zoom.
Before beginning, be sure you have completed Lesson 8 on Functions, Lesson 9 on Constants, and handed-in their respective questions on Gradescope.
The Caesar Cipher is one of the simplest ways to encode a message. It’s easily cracked. The idea is each letter is replaced by a letter some offset away from it in the alphabet. For our purposes, we will assume an offset shift of 1.
Thus, the mappings are:
a -> b b -> c c -> d .... y -> z z -> a
Notice when
z is encoded it “wraps around” to
a.
ordfunction
Under the hood our computer uses numeric codes to represent characters, or
strs of length one. The standard encoding is ASCII (“American Standard Code for Information Exchange”) which uses 7 binary digits (0s and 1s) to reresent each character. You’ll learn about this more in later classes, so no worries about the details here. The table of codes can be found here:. In the table, the
Dec column is the
int value of each character and the
Glyph column contains the character representation. Scroll down to
Dec
97 to see the lowercase range.
For this exercise, you will make use of the built-in
ord. The
ord function is short for “ordinal” and it gives the numerical
int ordering of a single-character
str in ASCII. For example, the character
n has corresponds to the
int value
110 in ASCII per the table linked above. You can confirm this with the following demo code:
>>> character:>> ascii_code: int = ord(character) >>> print(ascii_code) 110
chrfunction.
According to our cipher mapping, we want to encode each character with the letter following it in the alphabet. We can do this by performing integer arithmetic on the
ascii_code.
Building on the previous example, we will encode the
character variable, whose value is
n, and store the result in
encoded_character, whose value we expect to be
o.
The built-in
chr function, as first demonstrated in lesson 3, can be given an
int ASCII code and return a
str made of its corresponding character.
>>> character:>> ascii_code: int = ord(character) >>> encoded_ascii_code: int = ascii_code + 1 >>> encoded_character: str = chr(encoded_ascii_code) >>> print(encoded_character) o
Try running this code yourself in a REPL to make sure you are confident about what is going on!
What about if we have to wrap around? In the case of encoding
z, we can’t just add 1 to get back to
a. The character
z’s ASCII code is
122 while
a is
97.
Some clever arithmetic, in conjunction with our good friend the remainder operator
%, can help us achieve this! Since there are 26 lowercase letters, we can take the remainder of dividing any number by 26 and are guaranteed for it to result in a value of
0 through
25. This would be great if
a was
0 and
z was
25, because then
(25 + 1) % 26 would be
0 which is
a! The problem is, lowercase ASCII codes begin at
97 with
a and end at
122 with
z. For a fun challenge, pause here and see if you can figure out how we’ll get around this conundrum.
Are you ready for the spoiler? Ok, here goes! An oft-used trick in situations like this, (this comes up in 3D graphics, too!), is we’ll momentarily normalize our value so that
a is
0 and
z is
25 by subtracting
a’s ASCII value which is
97. Then, we’ll encode by adding 1 and performing the remainder operation, finally we’ll denormalize by adding
a’s ASCII value back so that we once again have a number in the correct range for lower case letters. This modification still works for all letters in the alphabet, not just
z.
>>> character:>> ascii_code: int = ord(character) >>> normalized_code: int = ascii_code - 97 >>> encoded_code: int = (normalized_code + 1) % 26 + 97 >>> encoded_character: str = chr(encoded_code) >>> print(encoded_character) 'a'
Give it a try in a REPL to convice yourself these steps work for any lowercase
character. No worries if this still seems a bit fuzzy or magical – we are more worried about the function writing in the next two sections.
Now that you have a sense for the steps to encode a single character string using a caeser cipher, let’s define a function to abstract away the details of all those steps into functions which are easier to use.
Open the course workspace in VS Code (File > Open Recent > comp110-workspace-…) and open the File Explorer pane. Expand
exercises.
Right click on the word
exercises and select “New Folder”.
Name the folder exactly:
ex02
cipher.pyEncoding
Right click on the
ex02 folder you setup above and select “New File”, name the file
cipher.py. In this part of the exercise, we will be walking through how to encode a
str.
encode_charfunction
Now that you’ve experimented with the process of encoding a single-length
str, it is your turn to write a function which carries out those same steps.
Define a function named
encode_char that given a single-length
str parameter returns the encoded version of that character.
Once you’ve defined your
encode_char function, save your work and try importing the function definition into a REPL to try out the function calls shown below.
>>> from exercises.ex02.cipher import encode_char >>> encode_char("c") 'd' >>> encode_char("z") 'a'
Wow! Behold the power of process abstraction! Once you have correctly implemented your function, notice how much easier it is to encode a single character using the function than moving through all those earlier steps!
encode_char
encode_char
strthat can be assumed to be single-length
str
strshould be the parameter given shifted one letter to the right in the alphabet, per the mapping shown above.
ordand
chrbuilt-in functions.
lowermethod:
some_variable_name: str = parameter_name.lower(). The
lowermethod is built-in to Python
strobjects and converts any uppercase characters in a string to lowercase.
encode_strfunction to encode 4-letter strings
Now that your
encode_char function is complete, you can use it to implement a function for encoding
strs of lengths greater than 1. For the purposes of this exercise, we will assume length 4. In a future exercise, you will rewrite this function to work with a
str of any length, but we need to learn a few more concepts first.
Define a new function called
encode_str that takes in a
str parameter and returns the encoded version of that
str.
Here’s an example of how you should be able to use the function, once implemented:
>>> from exercises.ex02.cipher import encode_str >>>> encode_str("abcz") 'bcda'
encode_str
encode_str
strthat can be assumed to have a length of 4.
strof length 4.
strwith each letter shifted one to the right.
encode_charinside this function for each letter of the parameter.
strindexing to get the individual characters without looping. Hint: you’ll want to use
strindexing.
cipher.pyDecoding
Now that we have learned how to encode a
str, we want undo this operation and
decode it. These next two functions will look VERY similar to the ones you wrote in Part 1. This is expected – the main goal of this exercise is to get comfortable with the function writing process.
decode_charfunction
Define a function named
decode_char that given a single-length
str parameter returns the originial, unencoded version of that character.
Example function call:
decode_char("c") --> returns "b"
decode_char
decode_char
strthat can be assumed to be single-length
str
strshould be the parameter given shifted one letter to the left in the alphabet, per the mapping shown above.
ordand
chrbuilt-in functions.
some_variable_name = <parameter_name>.lower(). The
lowerfunction is built into python and converts any string into lowercase.
decode_strfunction to decode 4-letter strings
We can now use our
decode_char function to help us decode
strs of length 4. Define a new function called
decode_str that takes in a
str parameter and returns the original, unencoded version of that
str.
Example function call:
decode_str("bdef") --> returns "acde"
decode_str
decode_str
strthat can be assumed to have a length of 4.
strof length 4.
strwith each letter shifted one to the left.
decode_charinside this function for each letter of the parameter.
strindexing to get the individual characters without looping. Hint: you’ll want to use
strindexing.
To check that your functions work as expected, you can load your
cipher file into a REPL by opening up a new
REPL, and then running
from exercises.ex02.cipher import encode_char, encode_str, decode_char, decode_str. From here you can practice calling your functions and seeing if the results match what you expected. Once you have completed parts 1 and 2, you should be able to try combining function calls to decode and encode.
For example,
decode_char and
encode_char are inverses of each other. This means if you apply
encode_char to something followed by
decode_char, you should end up with what you started with.
decode_char(encode_char("a")) --> returns "a"
This same property holds for
decode_str and
encode_str. You should see the following behavior:
decode_str(encode_str("flex")) --> returns "flex"
For the both parts of the.
Lastly, there should be no magic numbers in your code. Make any magic numbers into named constants. Hint: In the program snippets above there are 3 magic numbers. More info on this can be found here.02! | https://20f.comp110.com/students/exercises/ex02-basic-functions.html | CC-MAIN-2021-10 | refinedweb | 1,621 | 63.7 |
I’d like my neural network to output an ImageTuple as defined in the Siamese tutorial. This works fairly well, including the
show and
show_batch methods. However
show_results fails for the following reason.
Learner.show_results() calls
TfmDL.show_results(), so let’s start there:
def show_results(self, b, out, max_n=9, ctxs=None, show=True, **kwargs): x,y,its = self.show_batch(b, max_n=max_n, show=False) b_out = type(b)(b[:self.n_inp] + (tuple(out) if is_listy(out) else (out,))) x1,y1,outs = self.show_batch(b_out, max_n=max_n, show=False) res = (x,x1,None,None) if its is None else (x, y, its, outs.itemgot(slice(self.n_inp,None))) if not show: return res show_results(*res, ctxs=ctxs, max_n=max_n, **kwargs)
Note that my input is of the form
(TensorImage, ImageTuple(TensorImage, TensorImage, ...))
and output is
ImageTuple(TensorImage, TensorImage, ...).
Consequently, since
is_listy(ImageTuple(x, y,...)) evaluates to True,
tuple(ImageTuple(x, y,...)) = (x, y, ...)
we have that
b_out = (img, x, y, ...) (i.e. different structure than
b) and the call to
self.show_batch fails.
Unfortunately I don’t know how to fix this! Note that the issue is closely related to this one and may even share a similar resolution. | https://forums.fast.ai/t/show-results-fails-for-listy-outputs/85702 | CC-MAIN-2022-21 | refinedweb | 198 | 53.37 |
ActiveResource is a pretty amazing implementation of REST, made in Ruby, for Rails.
By the Rails core. Invented by DHH. It’s got good credentials. Sadly, it did
not make it into Rails 1.2, so there is tons of buzz about it, but very little
in the way of actual resources and active discussion. The only thorough
treatment of
ActiveResource out there I can find is by a Rails core member,
and it’s good. I’m not going to re-cover everything it says, so definitely
check it out.
Taking ARes Out For a Test Drive
The idea is that you can do something like this:
class User < ActiveResource::Base self.site = " end u = User.find 1 u.email = "new@email.com" u.save
By declaring a model in your app as inheriting from
ActiveResource::Base (as
opposed to
ActiveRecord::Base), you get to work with remote objects as if they
were local.
User.find is doing a
GET request to
/users/1.xml (at
in this example), and
u.save is doing a
PUT
request to /users/1. The
PUT is actually a
POST with a parameter
_method=put, but its heart is in the right place. Of course, the site you’re
getting objects remotely from has to support this, and the easiest way to do
this is with the new map.resources helpers that did make it into Rails 1.2.
Now I have the opportunity to use
ActiveResource at work, and I get to do it
in the most educational way I can think of—replacing a developed local
User model with a remote
User model. Naturally, I have pre-existing tests
written that I need to have pass in order for the refactor to be considered
complete. The idea is that permissions for this app (and other, sister apps)
will all be governed by a parent application, and each child app gets the
permissions for the logged in user from the parent app. We decided the easiest
way was by sharing the
User model through
ActiveResource.
I don’t need to change any user data, or search by anything but ID, so I really
only need a show action implemented. And, because I’m not just replacing a
User model, but also a
Role model (
User has_many :roles), I’m going to
have to return additional data in the
User object that acts like the
Role
model I used to have. I also have to omit certain fields in the remote
User
model that aren’t appropriate for the child app to know. Since it’s only one
action, and it’s going to have to contort the data, I don’t want to do
map.resources and override the remote
User model’s
to_xml
function—it makes more sense to just make my own .rxml view and fake the
resource.
ActiveResource‘s
to_xml format is very easy to fake, even
including a
has_many relationship.
At
/tools/:tool_id/users/:id.xml:
xml.instruct! xml.user do xml.email @user.email xml.tag! "first-name", @user.first_name xml.tag! "remote-id", @user.remote_id, :type => "integer" xml.roles do @user.roles_in(@tool).each do |role| xml << role.to_xml(:skip_instruct => true, :only => [:title, :context]) end end end
How to best test your
ActiveResource models is an open question right now, as
far as I can tell. There’s no documentation, or even blog posts, that I can
find, but there is an file included with
ActiveResource, that is
used in
ActiveResource in its own tests, to test itself. The setup in
ActiveResource’s test file for
Base looks (something) like this:
def setup @matz = { :id => 1, :name => 'Matz' }.to_xml(:root => 'person') @david = { :id => 2, :name => 'David' }.to_xml(:root => 'person') ActiveResource::HttpMock.respond_to do |mock| mock.get "/people/1.xml", {}, @matz mock.get "/people/2.xml", {}, @david mock.put "/people/1.xml", {}, nil, 204 mock.delete "/people/1.xml", {}, nil, 200 mock.get "/people/99.xml", {}, nil, 404 mock.get "/people.xml", {}, "<people>#{@matz}#{@david}</people>" end end
This approach is interesting, because instead of mocking out the behavior of the
Person model, they’re creating a mock Internet for the
Person model to talk
to. And, instead of using YAML
fixtures, they’re using XML
fixtures. And, because
ActiveResource’s XML format is so simple, they’re just making a hash with a root
and calling
to_xml, and that’s fine. That’s a lot to take in.
So here’s my method for integrating
ActiveResources into my unit and
functional tests, which for me only involved editing test_helper, and required
no change to any functional or unit test files. I’m sure it’s not the best
possible method, but it achieves my goal of not changing how I write unit and
functional tests. Here’s an excerpt of my test_helper.rb:
def self.all_fixtures fixtures :other, :normal, :models remote_fixtures end def self.user(name) path = File.join(RAILS_ROOT, "test", "remote_fixtures", "users", "#{name.to_s}.xml") return nil unless File.exists?(path) File.read path end def self.remote_fixtures ActiveResource::HttpMock.respond_to do |mock| mock.get "/tools/1/users/2.xml", {}, user(:eric) # some ActiveResource requests append these empty parameters, in any order # and you can't seem to use regexps with HttpMock right now mock.get "/tools/1/users/2.xml?include=&conditions=", {}, user(:eric) mock.get "/tools/1/users/2.xml?conditions=&include=", {}, user(:eric) mock.get "/tools/1/users/3.xml", {}, user(:matt) mock.get "/tools/1/users/4.xml", {}, user(:paper) mock.get "/tools/1/users/0.xml", {}, nil, 404 mock.get "/tools/1/users/.xml", {}, nil, 404 end end def users(name) case name when :eric User.find(2) when :matt User.find(3) when :paper User.find(4) else nil end end
This is assuming I have XML
files in test/remote_fixtures/users, named eric.xml, matt.xml, and paper.xml,
that are the mock responses I want
ActiveResource to think it is getting.
The primary drawback here is that I’m hard-coding specific fixture info into test_helper. I could address some of this by doing part of the logic dynamically, by reading filenames in the test/remote_fixtures/users directory. The secondary drawback is that you need to make sure remote_fixtures is being called in every test file. Since I was already using an all_fixtures helper at the top of each file to load in my YAML fixtures, I just included a call to remote_fixtures inside that, and I didn’t have to add anything.
ActiveResource is not at all meant to be ready for release, so any issues I
have with it should not be taken as complaints, just as information to be aware
of if you go to use it. The main issue that makes this process difficult is
that every possible route
ActiveResource could request needs to be listed in
HttpMock; there’s no support for regular expressions. Depending on your app,
there could be requests made to /users/.xml, or /users/0.xml, and if there is no
mock route specified, an error will be thrown and it will halt your tests.
Sometimes requests are made with empty parameters, like
?include=&condition=.
I’m not clear yet on when this happens, but it does. Of course, using
HttpMock may not be at all the way the developers of
ActiveResource
ultimately intend us to test
ActiveResource objects; perhaps we will actually
mock out the objects or the model, instead of The Internet.
Overall, my transition to using
ActiveResource has gone very smoothly. The
implementation is a beautiful example of the kind of convenience that REST is supposed to bring us.
Even if it’s not part of Rails 1.2, I think it’s ready to be used, in at least
small applications, right now. | https://thoughtbot.com/blog/activeresource-and-testing | CC-MAIN-2022-21 | refinedweb | 1,299 | 66.64 |
Noam,
__del__ is used for finalization when the obj is reclaimed by GC. On refcounting implementations like CPython, this occurs as soon as the refcount goes to zero. On Jython, this may occur whenever the GC does this, possibly after a number of rounds of GC. In other words, it's not a good idea to depend on it happening at a specific time.
Hi,
I defined in some class
def __del__(self):
print 'fooooooo'
though, even when i do
del X
for an object of the class above, I don't see any 'fooooooo' printed... Is there a reason? A way around it?
Thanks, No-
_______________________________________________
Jython-users mailing list
Jython-users@lists.sourceforge.net | http://sourceforge.net/p/jython/mailman/attachment/d03bb4010902111150o497ecdadt57013cf12e52cd9b@mail.gmail.com/1/ | CC-MAIN-2015-18 | refinedweb | 116 | 83.15 |
csv — Comma-separated Value Files¶
The
csv module can be used to work with data exported from
spreadsheets and databases into text files formatted with fields and
records, commonly referred to as comma-separated value (CSV) format
because commas are often used to separate the fields in a record.
Reading¶
Use
reader() to create a an object for reading data from a CSV
file. The reader can be used as an iterator to process the rows of
the file in order. For example
import csv import sys with open(sys.argv[1], 'rt') as f: reader = csv.reader(f) for row in reader: print(row)
The first argument to
reader() is the source of text lines. In
this case, it is a file, but any iterable is accepted (a
StringIO
instance,
list, etc.). Other optional arguments can be given to
control how the input data is parsed.
"Title 1","Title 2","Title 3","Title 4" 1,"a",08/18/07,"å" 2,"b",08/19/07,"∫" 3,"c",08/20/07,"ç"
As it is read, each row of the input data is parsed and converted to a
list of strings.
$ python3 csv_reader.py testdata.csv ['Title 1', 'Title 2', 'Title 3', 'Title 4'] ['1', 'a', '08/18/07', 'å'] ['2', 'b', '08/19/07', '∫'] ['3', 'c', '08/20/07', 'ç']
The parser handles line breaks embedded within strings in a row, which is why a “row” is not always the same as a “line” of input from the file.
"Title 1","Title 2","Title 3" 1,"first line second line",08/18/07
Fields with line breaks in the input retain the internal line breaks when they are returned by the parser.
$ python3 csv_reader.py testlinebreak.csv ['Title 1', 'Title 2', 'Title 3'] ['1', 'first line\nsecond line', '08/18/07']
Writing¶
Writing CSV files is just as easy as reading them. Use
writer()
to create an object for writing, then iterate over the rows, using
writerow() to print them.
import csv import sys unicode_chars = 'å∫ç' with open(sys.argv[1], 'wt') as f: writer = csv.writer(f) writer.writerow(('Title 1', 'Title 2', 'Title 3', 'Title 4')) for i in range(3): row = ( i + 1, chr(ord('a') + i), '08/{:02d}/07'.format(i + 1), unicode_chars[i], ) writer.writerow(row) print(open(sys.argv[1], 'rt').read())
The output does not look exactly like the exported data used in the reader example because it lacks quotes around some of the values.
$ python3 csv_writer.py testout.csv Title 1,Title 2,Title 3,Title 4 1,a,08/01/07,å 2,b,08/02/07,∫ 3,c,08/03/07,ç
Quoting¶
The default quoting behavior is different for the writer, so the
second and third columns in the previous example are not quoted. To
add quoting, set the
quoting argument to one of the other quoting
modes.
writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
In this case,
QUOTE_NONNUMERIC adds quotes around all columns
that contain values that are not numbers.
$ python3 csv_writer_quoted.py testout_quoted.csv "Title 1","Title 2","Title 3","Title 4" 1,"a","08/01/07","å" 2,"b","08/02/07","∫" 3,"c","08/03/07","ç"
There are four different quoting options, defined as constants in the csv module.
QUOTE_ALL
- Quote everything, regardless of type.
QUOTE_MINIMAL
- Quote fields with special characters (anything that would confuse a parser configured with the same dialect and options). This is the default
QUOTE_NONNUMERIC
- Quote all fields that are not integers or floats. When used with the reader, input fields that are not quoted are converted to floats.
QUOTE_NONE
- Do not quote anything on output. When used with the reader, quote characters are included in the field values (normally, they are treated as delimiters and stripped).
Dialects¶
There is no well-defined standard for comma-separated value files, so
the parser needs to be flexible. This flexibility means there are
many parameters to control how
csv parses or writes data.
Rather than passing each of these parameters to the reader and writer
separately, they are grouped together into a dialect object.
Dialect classes can be registered by name, so that callers of the
csv
module do not need to know the parameter settings in advance. The
complete list of registered dialects can be retrieved with
list_dialects().
The standard library includes three dialects:
excel,
excel-tabs, and
unix. The
excel dialect is for working
with data in the default export format for Microsoft Excel, and also
works with LibreOffice. The
unix dialect quotes all fields with
double-quotes and uses
\n as the record separator.
$ python3 csv_list_dialects.py ['excel', 'excel-tab', 'unix']
Creating a Dialect¶
If, instead of using commas to delimit fields, the input file uses
pipes (
|), like this
"Title 1"|"Title 2"|"Title 3" 1|"first line second line"|08/18/07
a new dialect can be registered using the appropriate delimiter.
import csv csv.register_dialect('pipes', delimiter='|') with open('testdata.pipes', 'r') as f: reader = csv.reader(f, dialect='pipes') for row in reader: print(row)
Using the “pipes” dialect, the file can be read just as with the comma-delimited file.
$ python3 csv_dialect.py ['Title 1', 'Title 2', 'Title 3'] ['1', 'first line\nsecond line', '08/18/07']
Dialect Parameters¶
A dialect specifies all of the tokens used when parsing or writing a data file. the table below lists the aspects of the file format that can be specified, from the way columns are delimited to the character used to escape a token.
import csv import sys csv.register_dialect('escaped', escapechar='\\', doublequote=False, quoting=csv.QUOTE_NONE, ) csv.register_dialect('singlequote', quotechar="'", quoting=csv.QUOTE_ALL, ) quoting_modes = { getattr(csv, n): n for n in dir(csv) if n.startswith('QUOTE_') } TEMPLATE = '''\ Dialect: "{name}" delimiter = {dl!r:<6} skipinitialspace = {si!r} doublequote = {dq!r:<6} quoting = {qu} quotechar = {qc!r:<6} lineterminator = {lt!r} escapechar = {ec!r:<6} ''' for name in sorted(csv.list_dialects()): dialect = csv.get_dialect(name) print(TEMPLATE.format( name=name, dl=dialect.delimiter, si=dialect.skipinitialspace, dq=dialect.doublequote, qu=quoting_modes[dialect.quoting], qc=dialect.quotechar, lt=dialect.lineterminator, ec=dialect.escapechar, )) writer = csv.writer(sys.stdout, dialect=dialect) writer.writerow( ('col1', 1, '10/01/2010', 'Special chars: " \' {} to parse'.format( dialect.delimiter)) ) print()
This program shows how the same data appears when formatted using several different dialects.
$ python3 csv_dialect_variations.py Dialect: "escaped" delimiter = ',' skipinitialspace = 0 doublequote = 0 quoting = QUOTE_NONE quotechar = '"' lineterminator = '\r\n' escapechar = '\\' col1,1,10/01/2010,Special chars: \" ' \, to parse Dialect: "excel" delimiter = ',' skipinitialspace = 0 doublequote = 1 quoting = QUOTE_MINIMAL quotechar = '"' lineterminator = '\r\n' escapechar = None col1,1,10/01/2010,"Special chars: "" ' , to parse" Dialect: "excel-tab" delimiter = '\t' skipinitialspace = 0 doublequote = 1 quoting = QUOTE_MINIMAL quotechar = '"' lineterminator = '\r\n' escapechar = None col1 1 10/01/2010 "Special chars: "" ' to parse" Dialect: "singlequote" delimiter = ',' skipinitialspace = 0 doublequote = 1 quoting = QUOTE_ALL quotechar = "'" lineterminator = '\r\n' escapechar = None 'col1','1','10/01/2010','Special chars: " '' , to parse' Dialect: "unix" delimiter = ',' skipinitialspace = 0 doublequote = 1 quoting = QUOTE_ALL quotechar = '"' lineterminator = '\n' escapechar = None "col1","1","10/01/2010","Special chars: "" ' , to parse"
Automatically Detecting Dialects¶
The best way to configure a dialect for parsing an input file is to
know the correct settings in advance. For data where the dialect
parameters are unknown, the
Sniffer class can be used to make
an educated guess. The
sniff() method takes a sample of the
input data and an optional argument giving the possible delimiter
characters.
import csv from io import StringIO import textwrap csv.register_dialect('escaped', escapechar='\\', doublequote=False, quoting=csv.QUOTE_NONE) csv.register_dialect('singlequote', quotechar="'", quoting=csv.QUOTE_ALL) # Generate sample data for all known dialects samples = [] for name in sorted(csv.list_dialects()): buffer = StringIO() dialect = csv.get_dialect(name) writer = csv.writer(buffer, dialect=dialect) writer.writerow( ('col1', 1, '10/01/2010', 'Special chars " \' {} to parse'.format( dialect.delimiter)) ) samples.append((name, dialect, buffer.getvalue())) # Guess the dialect for a given sample, and then use the results # to parse the data. sniffer = csv.Sniffer() for name, expected, sample in samples: print('Dialect: "{}"'.format(name)) print('In: {}'.format(sample.rstrip())) dialect = sniffer.sniff(sample, delimiters=',\t') reader = csv.reader(StringIO(sample), dialect=dialect) print('Parsed:\n {}\n'.format( '\n '.join(repr(r) for r in next(reader))))
sniff() returns a
Dialect instance with the settings to
be used for parsing the data. The results are not always perfect, as
demonstrated by the “escaped” dialect in the example.
$ python3 csv_dialect_sniffer.py Dialect: "escaped" In: col1,1,10/01/2010,Special chars \" ' \, to parse Parsed: 'col1' '1' '10/01/2010' 'Special chars \\" \' \\' ' to parse' Dialect: "excel" In: col1,1,10/01/2010,"Special chars "" ' , to parse" Parsed: 'col1' '1' '10/01/2010' 'Special chars " \' , to parse' Dialect: "excel-tab" In: col1 1 10/01/2010 "Special chars "" ' to parse" Parsed: 'col1' '1' '10/01/2010' 'Special chars " \' \t to parse' Dialect: "singlequote" In: 'col1','1','10/01/2010','Special chars " '' , to parse' Parsed: 'col1' '1' '10/01/2010' 'Special chars " \' , to parse' Dialect: "unix" In: "col1","1","10/01/2010","Special chars "" ' , to parse" Parsed: 'col1' '1' '10/01/2010' 'Special chars " \' , to parse'
Using Field Names¶
In addition to working with sequences of data, the
csv module
includes classes for working with rows as dictionaries so that the
fields can be named. The
DictReader and
DictWriter
classes translate rows to dictionaries instead of lists. Keys for the
dictionary can be passed in, or inferred from the first row in the
input (when the row contains headers).
import csv import sys with open(sys.argv[1], 'rt') as f: reader = csv.DictReader(f) for row in reader: print(row)
The dictionary-based reader and writer are implemented as wrappers
around the sequence-based classes, and use the same methods and
arguments. The only difference in the reader API is that rows are
returned as OrderedDict instances instead of
lists or tuples (under earlier verison of Python, the rows were
returned as regular
dict instances).
$ python3 csv_dictreader.py testdata.csv OrderedDict([('Title 1', '1'), ('Title 2', 'a'), ('Title 3', '08/18/07'), ('Title 4', 'å')]) OrderedDict([('Title 1', '2'), ('Title 2', 'b'), ('Title 3', '08/19/07'), ('Title 4', '∫')]) OrderedDict([('Title 1', '3'), ('Title 2', 'c'), ('Title 3', '08/20/07'), ('Title 4', 'ç')])
The
DictWriter must be given a list of field names so it
knows how to order the columns in the output.
import csv import sys fieldnames = ('Title 1', 'Title 2', 'Title 3', 'Title 4') headers = { n: n for n in fieldnames } unicode_chars = 'å∫ç' with open(sys.argv[1], 'wt') as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() for i in range(3): writer.writerow({ 'Title 1': i + 1, 'Title 2': chr(ord('a') + i), 'Title 3': '08/{:02d}/07'.format(i + 1), 'Title 4': unicode_chars[i], }) print(open(sys.argv[1], 'rt').read())
The field names are not written to the file automatically, but they
can be written explicitly using the
writeheader() method.
$ python3 csv_dictwriter.py testout.csv Title 1,Title 2,Title 3,Title 4 1,a,08/01/07,å 2,b,08/02/07,∫ 3,c,08/03/07,ç
See also | https://pymotw.com/3/csv/ | CC-MAIN-2018-51 | refinedweb | 1,850 | 55.44 |
2.8. Writing unit tests with py
Untested code is broken code. Manual testing is essential to ensuring that our software works as expected and does not contain critical bugs. However, manual testing is severely limited because bugs may be introduced at any time in the code.
Nowadays, automated testing is a standard practice in software engineering. In this recipe, we will briefly cover important aspects of automated testing: unit tests, test-driven development, test coverage, and continuous integration. Following these practices is fundamental in order to produce high-quality software.
Getting ready
Python has a native unit testing module that you can readily use (unittest). Other third-party unit testing packages exist. In this recipe, we will use py.test. It is installed by default in Anaconda, but you can also install it manually with
conda install pytest.
How to do it...
1. Let's write in a
first.py file a simple function that returns the first element of a list.
%%writefile first.py def first(l): return l[0]
Overwriting first.py
2. To test this function, we write another function, the unit test, that checks our first function using an example and an assertion:
%%writefile -a first.py # This is appended to the file. def test_first(): assert first([1, 2, 3]) == 1
Appending to first.py
%cat first.py
def first(l): return l[0] # This is appended to the file. def test_first(): assert first([1, 2, 3]) == 1
3. To run the unit test, we use the
pytest executable (the
! means that we're calling an external program from IPython):
===========
4. Our test passes! Let's add another example with an empty list. We want our function to return
None in this case:
%%writefile first.py def first(l): return l[0] F =================== FAILURES =================== __________________ test_first __________________ def test_first(): assert first([1, 2, 3]) == 1 > assert first([]) is None first.py:6: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ l = [] def first(l): > return l[0] E IndexError: list index out of range first.py:2: IndexError =========== 1 failed in 0.02 seconds ===========
5. This time, our test fails. Let's fix it by modifying the
first() function:
%%writefile first.py def first(l): return l[0] if l else None ===========
The test passes again!
How it works...
By definition, a unit test must focus on one specific functionality. All unit tests should be completely independent. Writing a program as a collection of well-tested, mostly decoupled units forces you to write modular code that is more easily maintainable.
In a Python package, a
test_xxx.py module should accompany every Python module named
xxx.py. This testing module contains unit tests that test functionality implemented in the
xxx.py module.
Sometimes, your module's functions require preliminary work to run (for example, setting up the environment, creating data files, or setting up a web server). The unit testing framework can handle this via fixtures. The state of the system environment should be exactly the same before and after a testing module runs. If your tests affect the file system, they should do so in a temporary directory that is automatically deleted at the end of the tests. Testing frameworks such as py.test provide convenient facilities for this use-case.
Tests typically involve many assertions. With py.test, you can simply use the builtin
assert keyword. Further convenient assertion functions are provided by NumPy (see). They are especially useful when working with arrays. For example,
np.testing.assert_allclose(x, y) asserts that the
x and
y arrays are almost equal, up to a given precision that can be specified.
Writing a full testing suite takes time. It imposes strong (but good) constraints on your code's architecture. It is a real investment, but it is always profitable in the long run. Also, knowing that your project is backed by a full testing suite is a real load off your mind.
First, thinking about unit tests from the beginning forces you to think about a modular architecture. It is really difficult to write unit tests for a monolithic program full of interdependencies.
Second, unit tests make it easier for you to find and fix bugs. If a unit test fails after introducing a change in the program, isolating and reproducing the bugs becomes trivial.
Third, unit tests help you avoid regressions, that is, fixed bugs that silently reappear in a later version. When you discover a new bug, you should write a specific failing unit test for it. To fix it, make this test pass. Now, if the bug reappears later, this unit test will fail and you will immediately be able to address it.
When you write a complex program based on interdependent APIs, having a good test coverage for one module means that you can safely rely on it in other modules, without worrying about its behavior not conforming to its specification.
Unit tests are just one type of automated tests. Other important types of tests include integration tests (making sure that different parts of the program work together) and functional tests (testing typical use-cases).
There's more...
Automated testing is a wide topic, and we only scratched the surface in this recipe. We give some further information here.
Test coverage
Using unit tests is good. However, measuring test coverage is even better: it quantifies how much of our code is being covered by your testing suite. The coverage.py module () does precisely this. It integrates well with py.test.
The coveralls.io service brings test-coverage features to a continuous integration server (refer to the Unit testing and continuous integration section). It works seamlessly with GitHub.
Workflows with unit testing
Note the particular workflow we have used in this example. After writing our function, we created a first unit test that passed. Then we created a second test, which failed. We investigated the issue and fixed the function. The second test passed. We could continue writing more and more complex unit tests, until we are confident that the function works as expected in most situations.
Run
pytest --pdbto drop into the Python debugger on failures. This is quite convenient to find out quickly why a unit test fails.
We could even write the tests before the function itself. This is test-driven development, which consists of writing unit tests before writing the actual code. This workflow forces us to think about what our code does and how one uses it, instead of how it is implemented.
Unit testing and continuous integration
A good habit to get into is running the full testing suite of our project at every commit. In fact, it is even possible to do this completely transparently and automatically through continuous integration. We can set up a server that automatically runs our testing suite in the cloud at every commit. If a test fails, we get an automatic e-mail telling us what the problem is so that we can fix it.
There are many continuous integration systems and services: Jenkins/Hudson, Travis CI (), Codeship (), and others. Some of them play well with GitHub. For example, to use Travis CI with a GitHub project, create an account on Travis CI, link your GitHub project to this account, and then add a
.travis.yml file with various settings in your repository (see the additional details in the references below).
In conclusion, unit testing, code coverage, and continuous integration are standard practices that should be used in all significant projects.
Here are a few references:
- Test-driven development, at
- Documentation of Travis CI in Python, at | https://ipython-books.github.io/28-writing-unit-tests-with-pytest/ | CC-MAIN-2019-09 | refinedweb | 1,282 | 66.84 |
When we released our first Betas of the BlackBerry® 10 WebWorks™ SDK and Ripple Emulator at the BlackBerry 10 Jam conference in May, we spoke about our desire to bring frequent updates of these tools to you, our dedicated developer community. We want to keep fueling your creativity and desire to build the best BlackBerry 10 applications leading up to the official release. So, here is your next BlackBerry WebWorks and Ripple fix.
This update brings a few new APIs (and emulation thereof in Ripple) along with a host of fixes and a slight change to how we handle whitelisting of events.
First up is the addition of the blackberry.ui.dialog APIs that will be very familiar to existing BlackBerry WebWorks developers. This API provides two methods that allow you to launch asynchronous dialogs requesting feedback from the user. These dialogs leverage the standard system level dialogs so you can get a consistent look and feel for your application with the rest of the system. standardAskAsync provides a predefined set of buttons for your dialog, whereas customAskAsync allows you to customize the dialog buttons.
We have also added an API that, in conjunction with the standard HTML5 onLine API, will let you know just how connected you really are. The standard navigator.onLine property and online/offline events are supported to let you know if your application has connectivity in general. If you would like to know what type of connection you have and when the type of connection changes, check out our blackberry.connection.type property, and listen for the connectionchange event. This will tell you if you are on VPN, BlackBerry® Bridge™, WiFi®, etc.
Speaking of events, we have adjusted how these work slightly from the first release. In the initial beta, all events were defined in the blackberry.event namespace. Without getting into gory details, this proved to be somewhat inefficient on the final code size, so we have moved the event definitions into the namespace that contains the functionality related to that event – i.e. the battery events are now defined in the blackberry.system namespace. Note that you no longer need to whitelist blackberry.event, since it only has the add and remove listener functions (these will always be available to call), but you will have to whitelist any namespace that has an event you are specifically interested in. Please check out the API reference.
In terms of bug fixes, there are a couple of key ones that I want to call out. If you use a module loader, you can now also use BlackBerry WebWorks, hooray! In the first release, the last one included into your app would work but break the first. Now webworks.js and module loaders play nicely together.
In the first release, you also could not sign your application at the same time as enabling remote web inspector. You can now do this so you can test your application on secure devices without needing to worry about debug tokens. That said, be sure to turn off web inspector before you submit your application to the BlackBerry App World™ storefront. ;)
The team here at Research In Motion® (RIM®) is hard at work on the next Beta refresh, currently slated to land in early July. If you are really eager/curious/have lots of free time, feel free to check out our progress in GitHub, and let us know whether we are heading in the right direction on new features and APIs.
For BlackBerry WebWorks SDK work, check out:
Ripple? Check out:
Looking forward to a great summer of BlackBerry 10 and BlackBerry WebWorks coding! | https://devblog.blackberry.com/2012/06/blackberry-10-webworks-sdk-ripple-update/ | CC-MAIN-2015-11 | refinedweb | 604 | 61.77 |
#include <MTrimBoundaryArray.h>
This class implements an array of MObjectArray objects. Each MObjectArray is a collection of curves (edges, in fact) that represent a trim boundary.
This class owns all of the MObjectArrays in the class. It doesn't hold a reference to any other MObjectArray.
Default constructor. The instance is set to contain no elements.
Copy Constructor.
Class destructor
This method is used to reserve the capacity of the array.
This method returns the length of the trim boundary array.
This method returns the size of the trim boundary array. The size and the length are the same.
The index operator. NOTE: no bounds are checked by this method.
The method returns the MObjectArray specified by the index. NOTE: no bounds are checked by this method.
This method is used to replace an existing boundary array.
This method adds a new boundary into the "index" position.
Add a new boundary array at the end of the list.
This method removes an existing boundary from the list.
This method clears the trim boundary array.
This function create a curve that represent all curves of the boundary. The original boundary edges are not changed. Note that the resulting curve is not added to the current model but is owned by an MObject which is of type kNurbsCurveData. | http://download.autodesk.com/us/maya/2009help/api/class_m_trim_boundary_array.html | CC-MAIN-2014-42 | refinedweb | 216 | 78.04 |
stream and string array
Discussion in 'Java' started by focode, Aug 6, 2009.
- Similar Threads
Doing readline in a thread from a popen4('rsync ...') stream blocks when the stream ends.Rasmusson, Lars, Apr 28, 2004, in forum: Python
- Replies:
- 1
- Views:
- 926
- popov
- Apr 30, 2004
- Replies:
- 9
- Views:
- 878
- Alex Buell
- Apr 27, 2006
get stream mode flags from an opened streamAlexander Korsunsky, Feb 17, 2007, in forum: C++
- Replies:
- 1
- Views:
- 608
- John Harrison
- Feb 17, 2007
what is the different between byte stream and character stream?dolphin, Mar 17, 2007, in forum: Java
- Replies:
- 6
- Views:
- 739
- Thomas Fritsch
- Mar 18, 2007
Stream operator in namespace masks global stream operatormrstephengross, May 9, 2007, in forum: C++
- Replies:
- 3
- Views:
- 554
- James Kanze
- May 10, 2007
Conversion from Input Stream to Output StreamKashif Ur Rehman, May 17, 2007, in forum: Java
- Replies:
- 2
- Views:
- 1,020
- Tom Hawtin
- May 17, 2007
Why no diagnostic for stream << stream?Anand Hariharan, Mar 17, 2009, in forum: C++
- Replies:
- 2
- Views:
- 363
- Anand Hariharan
- Mar 18, 2009
byte stream vs char stream bufferRoedy Green, May 7, 2014, in forum: Java
- Replies:
- 20
- Views:
- 627
- Silvio
- May 18, 2014 | http://www.thecodingforums.com/threads/stream-and-string-array.693841/ | CC-MAIN-2016-22 | refinedweb | 197 | 64.38 |
Understanding Null in Python
Like most programming languages, Python has a number of ways to represent null values.
Some languages use this as a pointer that points to nothing. Other times, null is used to represent when a variable is empty or to describe variables that have been instantiated but not yet defined.
With so mayn details to consider, null values can be difficult to understand. This tutorial will teach you everything you need to know about null values in Python.
Table of Contents
You can skip to a specific section of this Python null value tutorial using the table of contents below:
- What is Null?
- Assigning None to variables in Python
Understanding more about None
- Using None for Comparison
- Using None as a Value in Python
- None in Tracebacks
- Final Thoughts
What is Null?
Null means no value is defined. Null is used to represent a pointer that doesn't point to anything or when a variable or an argument is empty. In many other programming languages, Null is often defined to be 0. Java and PHP are two popular languages that use Null.
Let’s see how Null is used in PHP and Java.
PHP
<?php $exampleVariable = NULL; ?>
Java
exampleVariable = null;
However, the concept of Null is quite different in Python as Python has None to define Null objects or variables. While None serves the same purpose as the Null, None doesn’t define 0 or any other value. None is its own object in python.
Check the examples below
exampleVariable = None
exampleVariable = None print(type(exampleVariable))
RESULT
Assigning None to variables in Python
In other programming languages, variables can be declared without assigning an initial value to them. Also Null can only be assigned to specific types of variables. However, you can’t declare variables without assigning values as it will give an error.
See the example below.
Variable print(Variable)
Result
In such instances, you can assign None at the variable declaration But in Python, you need to assign a value to a variable at the initial declaration and None can be assigned to any type of variable.
noneVariable = None print(noneVariable)
RESULT
If a variable is not defined properly, it will cause a NameError. When None is declared, the variable will be a Null object. In Python, None is only equal to None. It is not equal to an empty string, the Boolean value False, or the numerical value 0.
The IF statement in the python code below demonstrates this clearly. It checks if the “noneVariable” is equal to the empty string, 0, False, or None. The IF condition only validates when the variable compares with None object.
noneVariable = None if noneVariable == "": print("None is Equal to an empty string") elif noneVariable == 0: print("None is Equal to 0") elif noneVariable == False: print("None is Equal to False") elif noneVariable == None: print("None is Equal to None")
RESULT
Understanding more about None
Any function without a proper return statement returns None. In Python, None object is so ubiquitous in REPL, it won’t print None unless the user explicitly tells it to. The following examples show how None is identified in Python.
Python None as a return value.
def examplefunction(): pass examplefunction() print(examplefunction())
RESULT
In this instance, when a function is created with no explicit return value, Python returns None as the result. Because Python REPL won’t print None unless explicitly declared we use the print statement to identify the output.
print() print(None) print(print('Hello'))
RESULT
In the python print() function, there is no return value to the function itself. Because of this, the first print() statement in the above example returns no explicit value. When the None object passes to the The second print statement, it returns None. Finally, in the nested print() statement the print(‘Hello’) returns the Hello string as the result. But as the print statement itself has no explicit return object, it will be shown as None.
None to identify missing or default parameters.
Let's look at the docs of list.sort function.
help(list.sort)
RESULT
As you can see in the output, None is assigned to the “key” parameter. Although the key parameter is required here, it is not provided. So, it indicates None as the default parameter.
Using None for Comparison
The identity operators and equality operators can be used to test whether two variables are referring to the same object. So, you can use them to test when a variable has been assigned as None. Both the equality operator(“==”) or the identity operator “is” can be used to check this.
# Equality Operator x = None if x == None: print("x is equal to None") else: print("x is equal to None") # Identity Operator y = None if y is None: print("y is equal to None") else: print("y is equal to None")
RESULT
However, there is a difference between the identity operator “is” and the equality operator “==”.
The identity operator checks if both the operands are referring to the same object while the equality operator checks if both operands are equal in value. The below examples demonstrate how these operations can be used properly in comparison tasks.
Check if an object is None
import re stringvalue = "Barry" # Check if "stringvalue" matches "Harry" match = re.match(stringvalue, "Harry") # Check if match is a None object if match is None: print("item do not match") else: print("item do match")
RESULT
In this example, we check if two values match with each other. . The match function will return a None object if the two values passed to it do not match. Then we use identity operators to validate the results.
If you want to correctly verify a value is a None object, using identity operators is the most optimal as equality operators can be fooled when other user defined objects that override the value. The following example shows this scenario.
class CheckComparison: def __eq__(self, other): return True x = CheckComparison() # Equality Operator print(x == None) # Identity Operator print(x is None)
RESULT
The equality operator has been overridden by the object equality (eq) of the class CheckComparision and this results in an incorrect output. As identity operators cannot be overridden, the intended result is displayed.
Using None as a Value in Python
In python, None can be added to a set as an item. Similarly, it can be used as a function parameter.
To illustrate that, we will check the following example. We create an empty class that will be used as the signal not to append. Then create the function “addto_list” with two parameters to add an element to a given “set”.
#(initial_set=colours))
RESULT
As we have defined default values for each parameter, it is not necessary to pass both values for each parameter. We pass the “colours” set as the initial set. This results in output returning the “colours” set back as it's not a None object. Please note that because sets are unordered, the resulting set shows the items in a random order.
#(None, initial_set=colours))
RESULT
In the above instance, we pass both parameters. But for the newelement, we pass a None object, and for initialset, we pass the colours set. As you can see the None object is added to the set. When None is a valid input item, it can be added to a set.
None in Tracebacks
Let’s have a look at one of the common issues related to None. If you see an error like “AttributeError: NoneType object has no attribute …”, it means you have tried to use None keyword in an incorrect way. One of the common reason for it could be calling a method on a variable that is defined to be Null.
Let us consider the following examples.
# fruits set with items fruits = {"cherry", "banana", "apple"} fruits.add("orange") print(fruits)
RESULT
In this instance, we create a set called “fruits”, and add another value called “orange”. Here, the code executes successfully as the Python sets contain the add method. However, the following code won’t be successful
# fruits as a None Object fruits = None fruits.add("strawberry") print(fruits)
RESULT
In the above example the “fruits” variable is declared as a None type object. As there is no add method associated with None object this results in an error.
So next time, when you get a traceback like this in your code, first, check the attribute that raised the error. In the above example, it was the add() method. Then you can find the object on which the method was called. After figuring out how the object became None, you can work on fixing the code.
Final Thoughts
All in all, as a first-class citizen in python, None plays a significant role in programming. None can be used for various tasks such as checking missing values, comparing results. Being an immutable keyword None is a solid choice for parameters in functions over mutable types. | https://nickmccullum.com/understanding-null-in-python/ | CC-MAIN-2021-31 | refinedweb | 1,496 | 63.19 |
Although the Windows NT API is not object-oriented, NT uses objects internally to provide support for certain features uniformly across a variety of different entities. Internally, files, events, mutexes, pipes, and so on, are all implemented as objects. This allows NT to perform some operations, such as security checks, in a generic fashion for different types of objects. The object manager is a part of the NT executive that provides services that allow other NT subsystems to operate on objects. Most parts of these services are not currently documented, but this article describes how you can access some of them to discover information such as how many partitions a disk has.
The Object Manager Database
To allow symbolic access to NT objects, NT allows them to have names. Rather than have a single global namespace and require all object names to be unique, the NT object manager organizes object names into a hierarchy, just like the hierarchical names you give to DOS files (in fact, the file system is conceptually just a subtree of the overall NT object namespace tree). You may have run into this hierarchical namespace when, for example, creating a pipe; named pipes have names of the form \\<server>\pipe\<pipename>, where <server> is the name of the server that created the pipe (or .. to indicate a local pipe), and <pipename> is the name of the individual pipe you want to refer to. You can think of this as though the object manager reserves a directory called pipe for holding the names of pipes created for any given server.
Just as a particular part of the object namespace is reserved for named pipes, other object directories in the namespace are reserved for other purposes. For example, the Device directory contains a list of objects that represent devices, such as Floppy0, HardDisk0, and so on. A variety of interesting information is available, if you could just traverse the object managers namespace.
The object manager also supports symbolic links. As the name implies, these are place holders that refer to other objects in the namespace tree. Symbolic links allow NT to make the same object available under different names. For example, NT may have named your floppy drive \Device\Floppy0, but by creating a symbolic link called A: that refers to it, you can use familiar DOS names to access the floppy drive.
The namespace is created dynamically by the object manager at runtime, so theres no disk file you can use to traverse it. Instead, you have to find a way to access the API that the object manager provides for other NT subsystems.
Viewing the Object Manager Namespace
There are some user-level tools available to view the namespace. ObjDir is part of the DDK and WinObj is available from. But if you look in the DDK documentation you will notice that functions to access the namespace are not documented. Sometimes it is useful to programmatically find out which drivers are installed or how many disk partitions are available.
If you look at the exported symbols of ntdll.dll (e.g., by using DUMPBIN, which is part of MS VC 4.x) you will find lots of functions that are not documented. Of particular interest are NtOpenDirectoryObject(), NtQueryDirectoryObject(), NtOpenSymbolicLinkObject(), and NtQuerySymbolicLinkObject(). When you peek into ntdll.lib (the import library of ntdll.dll) with a hex editor, you find a hint for the number of parameters the functions expect. Visual C++ demands export libraries that use mangled names, even if the names in the corresponding DLL are not mangled, and the mangling includes an indication of the number of bytes of parameters the function takes. The number after the @ of the mangled symbol name is the total size in bytes of all parameters.
In Win32 every parameter is at least four bytes (there are 64-bit parameters, but not here). Almost all Windows NT executive functions return a status code, so the four functions here would probably do so, too. For the two NTOpenXxxx() functions, it was easy to guess that they have parameters similar to the documented functions in the DDK that open objects. Interestingly, the access flags for directory and symbolic link objects are already in ntddk.h. Discovering the arguments to NtQueryDirectoryObject() was not that easy, but you can find out what the parameters may mean by disassembling, for example, ObjDir and then playing around with the function.
NtQueryDirectoryObject() is used to get the name and type of the objects in a directory object. A specific object is referenced by a zero-based index. An error is returned if the index is too large. The type of an object is a string such as Device, Directory, SymbolicLink, and so on. For the additional parameters of this function see the comments in objlst.h (Listing 1).
In a similar way, you can find out about NtQuerySymbolicLinkObject(), which is easier because it has fewer parameters. The function resolves a symbolic link and returns the name of the object to which the link points.
The header file objlst.h shows the prototypes for the functions. The naming convention and types are similar to ntddk.h of the DDK. You may have noticed that there are similar functions in the export list of ntdll.dll that start with ZwXxxx instead of NtXxxx. These functions differ only in the way they do internal parameter checking. The ZwXxxx functions are called from device drivers and the parameters are not checked, whereas the NtXxxx functions are called from subsystems and the parameters are validated (detailed parameter checking depends on the mode from which a function is called; NtXxxx functions always set the previous mode to user mode).
An Example
The sample program objlst.c (Listing 2) is a simple tool which uses the four functions. It recursively lists the directories of the Object Manager. DumpAllObjects() is the workhorse; it traverses a directory, resolves symbolic links if necessary, and recurses into other directories if it finds one. An optional parameter for the program specifies the directory to start with (e.g., OBJLST \Device to list the device directory).
objlst.c requires ntddk.h (and all included headers) and ntdll.lib from the DDK. It shows how to write a simple Win32 console application that uses Windows NT executive functions and that can be compiled without using the standard DDK build tool. Of course, you can use the functions in a kernel-mode driver also. You can also use the ZwXxxx functions instead of the NtXxxx counterparts.
Note that a Microsoft-specific extension of the format strings for the printf() function class is used. %Z and %wZ are used to print PANSI_STRING and PUNICODE_STRING parameters. PANSI_STRING and PUNICODE_STRING do not directly point to the string buffer they point to a structure which contains the number of characters in the buffer, the maximum length of the buffer, and a pointer to the buffer itself. The string in the buffer is not guaranteed to be zero-terminated.
Conclusion
Sometimes you need to use undocumented functions to solve a problem. There is always the issue of whether it is safe to use them. Of course, they are not supported by Microsoft and they may change without notice in the next release or service pack (NT executive functions probably wont). But you can perform many interesting tasks which are otherwise nearly impossible. There are still a lot of things to uncover in Windows NT.
Dieter Spaar is a self-employed software developer doing high-level and low-level programming since 1990. When not working for clients, he relaxes by uncovering undocumented features in various pieces of software. Dieter can be reached at spaar@mirider.augusta.de.
Get Source Code | http://www.drdobbs.com/using-nts-undocumented-object-manager-in/184416468 | CC-MAIN-2014-23 | refinedweb | 1,283 | 55.13 |
The path to proceed should be...
The problem i had was a "minor one", but one that delayed the answer one (more) day. For short, the method cohomology_ring of the constructed wedge of spheres WS works only for a WS which is immutable. The default constructor makes it mutable.
In order to explain (myself) the answer, so that i'll understand it also tomorrow, here are first some examples. This is...
sage: version() 'SageMath version 7.3, Release Date: 2016-08-04'
(1) Let us take a Klein bottle and ask for the cohomology ring over rationals and over the two elements field. The rings will have generators. We compute the relevant products.
K = simplicial_complexes.KleinBottle() HK = K.cohomology_ring( QQ ) print "H( K, Q ) has the following generators:" print HK.gens() # there are two gen(erator)s a, b = HK.gens() # they've got names, a and b print "We rename them a, b." print "Their degrees are %s, %s" % ( a.degree(), b.degree() ) print "Then we have for instance b*b = %s" % (b*b) print "Is b*b zero? %s" % ( (b*b).is_zero() ) print HK2 = K.cohomology_ring( GF(2) ) print "H( K, GF(2) ) has the following generators:" print HK2.gens() # there are FOUR gen(erator)s print "We rename them a, b, c, d." a, b, c, d = HK2.gens() # they've got names, a, b, c, d print "Their degrees are %s, %s, %s, %s" % ( a.degree(), b.degree(), c.degree(), d.degree() ) print "The values b*b, b*c, c*b, c*c are respectively %s, %s, %s, %s" % ( b*b, b*c, c*b, c*c ) print "Is b*b == 0? %s" % bool( b*b == 0 ) print "Is b*c == d? %s" % bool( b*c == d ) print "Is c*b == d? %s" % bool( c*b == d ) print "Is c*c == d? %s" % bool( c*c == d )
And we get so far (after a %cpaste into the sage interpreter):
H( K, Q ) has the following generators: (h^{0,0}, h^{1,0}) We rename them a, b. Their degrees are 0, 1 Then we have for instance b*b = 0 Is b*b zero? True H( K, GF(2) ) has the following generators: (h^{0,0}, h^{1,0}, h^{1,1}, h^{2,0}) We rename them a, b, c, d. Their degrees are 0, 1, 1, 2 The values b*b, b*c, c*b, c*c are respectively 0, h^{2,0}, h^{2,0}, h^{2,0} Is b*b == 0? True Is b*c == d? True Is c*b == d? True Is c*c == d? True
(2) Let us define a function that computes a wedge of spheres. This is a quick solution, there is no raise in case a bad argument. We expect as argument a tuple of integers > 0.
def WedgeOfSpheres( spheresTuple ): """ return the corresponding wedge of spheres for dimensionsTuple (1,3,4) we return for instance S1 /\ S3 /\ S4. """ for k in range( len( spheresTuple ) ): if k == 0: S = simplicial_complexes.Sphere( spheresTuple[k]) else : S = S.wedge( simplicial_complexes.Sphere( spheresTuple[k]) , is_mutable=False ) return S
There is one delicate point above: we really need the is_mutable=False option. Else the forthcomming method quotient_ring fails! (As i said, this may cost a day...)
(3) Then we can construct:
S = WedgeOfSpheres( (1,4,6) ) HS = S.cohomology_ring( QQ ) print "S = %s" % S print "Computing H( S, QQ ) ... be patient..." print HS gens = [ g for g in HS.gens() if g.degree() > 0 ] print "CUP PRODUCT matrix:" for g in gens: for h in gens: print g*h, print print "Is the CUP PRODUCT zero? %s" % all( [ not(g*h) for g in gens for h in gens ] )
and we get:
S = Simplicial complex with 15 vertices and 17 facets Computing H( S, QQ ) ... be patient... Cohomology ring of Simplicial complex with 15 vertices and 17 facets over Rational Field CUP PRODUCT matrix: 0 0 0 0 0 0 0 0 0 Is the CUP PRODUCT zero? True
(4) Resumed: In order to see if the pairing is trivial on the cohomology ring of a space X, the following call would do the job:
def is_zero_cup_product( X, base_ring=QQ ): generators = [ g for g in X.cohomology_ring( base_ring ).gens() if g.degree() > 0 ] for g in generators: for h in generators: if g*h: # print "%s * %s = %s" % ( g, h, g*h ) return False return True
For instance:
sage: K = simplicial_complexes.KleinBottle() sage: K Minimal triangulation of the Klein bottle sage: is_zero_cup_product( K, QQ ) True sage: is_zero_cup_product( K, GF(2) ) False sage: is_zero_cup_product( K, GF(5) ) True sage: P2 = simplicial_complexes.RealProjectiveSpace( 2 ) sage: P2 Minimal triangulation of the real projective plane sage: is_zero_cup_product( P2, QQ ) True sage: is_zero_cup_product( P2, GF(2) ) False sage: M7 = simplicial_complexes.MooreSpace( 7 ) sage: M7 Triangulation of the mod 7 Moore space sage: M7.cohomology_ring( GF(7) ).gens() (h^{0,0}, h^{1,0}, h^{2,0}) sage: a,b,c = _ sage: b * b 0 sage: is_zero_cup_product( M7 ) True | https://ask.sagemath.org/answers/37252/revisions/ | CC-MAIN-2021-49 | refinedweb | 832 | 74.9 |
Hello again,
I would like to know if I should keep on starting my JS functions with the document.ready function? Below is an example:
// Start Game
$(document).ready(function() {
$('.startgame').click(function() {
if ( progress === 1) {
var startGame = confirm("Your current game will be lost, are you sure you want to start a new game?");
if ( startGame === 1) {
location.reload(true);
}
}
else {
location.reload(true);
}
});
});
// New game
$(document).ready(function() {
$('newgame').click(function() {
var newGame = confirm("Start a new game with the above settings?");
if ( newGame === 1) {
location.reload(true);
}
});
});
Thanks in advance.
You only need to use $(document).ready(function() { ... }); once per file.You can just amalgamate all of your code in this.
$(document).ready(function() { ... });
Saying that, if you move all of your JS down to just before the closing </body> tag, you can very probably do away with the call to $(document).ready(function() { ... }); altogether.
Thanks, sir. So its fine if I do it like this?
$(document).ready(function() {
// Global Variables
var progress = 0;
// Functions
function gameInit() {
var gameInit = confirm("Your current game will be lost, are you sure you want to start a new game?");
if ( gameInit === true) {
location.reload(true);
}
};
// Start Game && New Game
$('.startgame,.newgame').click(function() {
if ( progress === 1) {
gameInit();
}
else {
var gameSettings = confirm("You are about to start a new game. Start the game with the above settings?");
if ( gameSettings === 1) {
location.reload(true);
}
else {
gameSettings();
}
}
});
});
Hi there,
This is a good start, although in your code, this line will throw an error:
gameSettings();
The reason for this is that you have previously assigned the variable gameSettings to the result of a confirm dialogue.
gameSettings
var gameSettings = confirm("You are about to start a new game. Start the game with the above settings?");
The disadvantage of this approach is that everything is in the global namespace and you have different bits of functionality intertwined throughout your code.
Now might be a good time to think about how to structure and organize your code, especially as it seems you are making a game - something that cannot usually be done in a few lines of Javascript.
One way of doing this, might be to use the module pattern.You can read more about it here:
I have taken the liberty of rewriting the code you have so far:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Game</title>
</head>
<body>
<button class="startgame">Start Game</button>
<button class="newgame">New Game</button>
<script src="" type="text/javascript"></script>
<script>
var s,
Game = {
settings: {
buttons: $('.startgame, .newgame'),
progress: 0,
existingGameMessage: "Your current game will be lost, are you sure you want to start a new game?",
newGameMessage: "You are about to start a new game. Start the game with the above settings?"
},
bindUIActions: function(){
s.buttons.on("click", function(){
Game.initializeNewGame();
});
},
getConfirmation: function(msg){
return confirm(msg);
},
invokeSettings: function(){
//Do stuff here
},
displayExistingGameDialogue: function(){
if (this.getConfirmation(s.existingGameMessage)){
location.reload(true);
}
},
displayNewGameDialogue: function(){
if (this.getConfirmation(s.newGameMessage)){
location.reload(true);
} else {
Game.invokeSettings();
}
},
initializeNewGame: function(){
if(s.progress){
Game.displayExistingGameDialogue();
} else {
Game.displayNewGameDialogue();
}
},
init: function(){
s = this.settings;
this.bindUIActions();
}
}
Game.init();
</script>
</body>
</html>
Admittedly this results in a few more lines of code, but I'm sure you'll agree, it is more readable and configurable.
HTH
You don't even need document.ready at all - just move you script tag to immediately before the </body> tag and you will get the benefits of document.ready without that code and also the rest of your page will load faster because the JavaScript will be loaded after everything else.
Hey felgall,
I was trying to think of an occasion when document.ready would make sense given that you have your JS directly before the closing </body> tag, but couldn't.Can you?
This is in contrast to $(window).ready which executes when complete page is fully loaded and might be useful if you are doing something with images (for example).
Substituting a local image for any remote images that failed to load is the only example I have of where it is necessary to delay the execution of the JavaScript when it is attached just before the </body> tag. In that instance everything in the page needs to have loaded first as there isn't an event triggered when all images have loaded but where other files may still not have finished loading.
Most other scripts that use images would work just as well if they started running immeediately even if all the images they use haven't finished loading yet.
With the script just before the </body> the document.ready should trigger immediately so the only effect will be the very small extra delay to download the script due to that extra unnecessary statement. Getting rid of the document.ready call would make the code start running a minute fraction of a microsecond sooner and result in one less line of code to maintain.
Wow, that is a good read, sir. Thank you!
Nice answer felgall, thank you.I bookmarked the link.
Thinking about this over the last couple of days, I realised that one advantage of $(document).ready() is that it allows people who are less confident with JavaScript to place arbitrary code anywhere on the page and have it execute at the right time.
$(document).ready()
Possibly another situation might be where you're using a script loader (eg. yepnope.js) to load your JS files asynchronously, and you have a callback that fires once a script has loaded, which may be before the DOM is ready.
So, you mean (for example) to avoid a situation where inline code which relies on an external library being loaded by yepnope, is executed before its dependency is ready?
I was thinking more of the situation where you might have a plugin that turns all divs with a certain class into some kind of widget. With a loader like yepnope, you can have a callback which will init the plugin as soon as it's loaded, but as the code is being loaded in tandem with the markup, it's possible that the callback could fire before the DOM is ready. Using the document ready function you could guard against that happening.
Ahh, I see. That makes sense. Thanks.
I have only come across two instances wherew JavaScript needs to be attached in the head of the page. In those cases it is because you need it to run before the page content loads. When properly written every other JavaScript can go at the bottom before the </body> tag.
So document.ready is only really useful for those beginners who haven't yet learnt how to write JavaScript properly - either because they simply copy other people's antiquated code or they are learning from sites that were set up to teach how to write JavaScript for the Netscape browser that haven't been updated to teach the completely different approach that ought to be used with modern browsers (there are lots of sites teaching outdated JavaScript and few teaching modern JavaScript).
This then would be a good occasion to help educate people that they shouldn't place their scripting code anywhere else but at the end of the body, because loading a script is a blocking action that prevents anything else from happening on the page until after the script has been loaded and executed.
Placing the script at the end of the body achieves multiple benefits - not just that the page content is faster to appear, but in that your script has an easier time interacting with elements on the page.
Yup, will do (and have been doing).What do you think about the use case that fretburner described?
Let's take a look:
In that case, it would make sense to pass the callback to the plugin so that the callback is only called after the plugin is complete. This tends to be something where a specific example becomes useful for the discussion and exploration of the problem - otherwise a lot of handwaving occurs.
I think there's a misunderstanding of what I was saying - the callback does fire after the plugin is loaded, that's not the problem. The problem is that because the script is loaded in tandem with the page, there's a chance for the plugin to be loaded and ready (and hence the callback to be fired) before the DOM is ready. This would especially be the case on the second visit to a page once the JS files have been cached by the browser. I've actually had this problem recently while using require.js.
Ahh, I can see that it would be a problem if YepNope is started before the end of the body. The rules change when doing such things, that's for sure. | https://www.sitepoint.com/community/t/document-ready-function/32280 | CC-MAIN-2017-09 | refinedweb | 1,473 | 63.19 |
Suppose you have been asked to migrate an existing multi-tier application to .NET where the business layer is written in Java. Normally you would have no option but to recode and port the entire application to any .NET language (e.g. C#). However this is where IKVM.NET comes to the rescue.
IKVM.NET is an open source implementation of Java for Mono /Microsoft .NET Framework and makes it possible both to develop .NET applications in Java, and to use existing Java API's and libraries in applications written in any .NET language. It is written in C# and the executables, documentation and source code can be downloaded from here.
IKVM.NET consists of the following three main parts:
However before we get any further into this topic, let’s discuss about few of the main components of the IKVM.NET package which we would be using later in this article.
Now back to our problem of migrating the existing Java business classes so that they can be accessed by the newly proposed .NET application. We would also like to use the various existing Java API and libraries in our .NET application. Let’s start by doing just that.
Download the binary distribution from the sourceforge site and unzip the contents to C:\ikvm (or X:\ikvm where X is your drive). You would find the ikvm executables and DLLs in the C:\ikvm\bin directory. Open a command or shell window, cd to C:\ikvm\bin, and type ‘ikvm’.
If your system is operating correctly, you should see the following output:
usage: ikvm [-options] <class> [args...] (to execute a class) or ikvm -jar [-options] <jarfile> [args...] (to execute a jar file)
For Linux based systems, the setup is similar as above. This is all you need to do for running the demo application.
public class JavaToNet
{
public static void main(String[] args)
{
System.out.println("This is a demonstration Program which\n");
System.out.println("shows the conversion of Java class to\n");
System.out.println("a .NET dll\n");
}
public static double AddNumbers(double a,double b){
double c = 0;
c = a + b;
return c;
}
public static double SubNumbers(double a,double b){
double c = 0;
c = a - b;
return c;
}
public static double MulNumbers(double a,double b){
double c = 0;
c = a * b;
return c;
}
public static double DivNumbers(double a,double b){
double c = 0;
c = a / b;
return c;
}
}
Our Java class is very simple. It has four functions for add, subtract, multiply and divide that take two double values and return a result. Our objective is to access these functions through our C# application. Compile the above Java file to get the JavaToNet.class. We will use this Java class file to generate the .NET DLL to be referenced in our C# program.
Copy the above Java class file (JavaToNet.class) to the C:\ikvm\bin directory. Now run the following command:
This would create the JavaToNet.dll from the JavaToNet.class file. There are other command line option for ikvmc.exe. For example: ‘ikvmc –target:exe javaToNet.class’ would create an EXE and not a DLL. You can get all the options by typing ‘ikvmc’ in the command line.
ikvmc –target:exe javaToNet.class
Start by creating a C# Windows application project.
Drag and drop controls into the form as shown:
Add the following DLLs as references to the project. Both DLLs are present in the C:\ikvm\bin folder.
Add the following code to the button click event of the ‘Calculate’ button:
private void btnCal_Click(object sender, System.EventArgs e)
{
if (rdAdd.Checked == true)
{
txtResult.Text = Convert.ToString(JavaToNet.AddNumbers
(Convert.ToDouble(txtNum1.Text),Convert.ToDouble(txtNum2.Text)));
}else if (rdSub.Checked ==true)
{
txtResult.Text = Convert.ToString(JavaToNet.SubNumbers
(Convert.ToDouble(txtNum1.Text),Convert.ToDouble(txtNum2.Text)));
}
else if (rdMul.Checked == true)
{
txtResult.Text = Convert.ToString(JavaToNet.MulNumbers
(Convert.ToDouble(txtNum1.Text),Convert.ToDouble(txtNum2.Text)));
}
else
{
txtResult.Text = Convert.ToString(JavaToNet.DivNumbers
(Convert.ToDouble(txtNum1.Text),Convert.ToDouble(txtNum2.Text)));
}
}
Add the following using directive on the top of the *.cs file:
using
using TimeZone = java.util.TimeZone;
Add the following code to the button click event of the ‘Time Zone’ button.
private void btnTimeZone_Click(object sender, System.EventArgs e)
{
MessageBox.Show(TimeZone.getDefault().getDisplayName());
}
Compile and run the application. The C# application would now call the AddNumbers(), SubNumbers(), MulNumbers() and DivNumbers() functions present in the JavaToNet.dll and return the result.
AddNumbers()
SubNumbers()
MulNumbers()
DivNumbers()
Click on the ‘Time Zone’ button. The application accesses the java.util.TimeZone class and displays the exact time zone of the place.
java.util.TimeZone
Since these methods had originally been written in Java, IKVM.NET provides us an easy and viable way to access those classes and methods from a .NET application. Similarly as shown above in the ‘Time Zone’ example, you can access most of the existing Java packages (e.g. java.io, java.util, etc.) and use them in your application.
However there are certain drawbacks. IKVM.NET, while still being actively developed, has limited support for AWT classes and hence porting Java GUI can be ruled out at present. Also some of the default Java classes are still being ported so you might not get all the functionalities you require. Also if your application depends on the exact Java class loading semantics, you might have to modify it to suit your. | https://www.codeproject.com/Articles/13549/Using-Java-Classes-in-your-NET-Application?fid=283780&df=90&mpp=10&sort=Position&spc=None&tid=3859236 | CC-MAIN-2017-51 | refinedweb | 903 | 51.65 |
Our idea is that ontology translation is best thought of in terms of ontology merging. We define ontology as a formal specification of a vocabulary of concepts, including axioms relating these concepts. The merge of two ontologies is obtained by taking the union of the axioms defining them, using XML namespaces to avoid name clashes. We then add bridging axioms that relate the terms in one ontology to the terms in the other. Inferences can be conducted in this merged ontology in either a demand-driven (backward-chaining) or data-driven (forword chaining) way.
Software Description
OntoMerge serves as a semi-automated nexus for agents and humans to find ways of coping with notational differences between ontologies with overlapping subject areas. OntoMerge is developed on top of PDDAML (PDDL-DAML Translator) and OntoEngine (inference engine). (These are built using some code from other people's programs, such as Jena (from HP Research) and JTP (from SRI/KSL).)
Try it!
OntoMerge is available over the World Wide Web. Please visit our online service to have a try.
What can it do?:
OntoMerge accepts
We have added a query-driven (backward-chaining) version in which the translation runs the other way, from target to source, as queries come in. The choice of data-driven or query-driven depends on how many queries one expects.
For OntoMerge to work, it has to have stored in its library merged ontologies that explain how terms from different ontologies relate. Currently its library is meager, but you never know. You may be assured that if you give us an ontology-translation problem OntoMerge can't handle, you will have our prompt attention. That means fast e-mail feedback and (we hope) a practical solution within days.
We have developed some semi-automatic ontology mapping and merging tools to help users to generate merged ontologies by themselves.
Once OntoMerge has a merged ontology for a set of domains, it should be able to handle any data involving those domains. This is not an ad-hoc tool for grinding out syntactic differences between assertion formats, but an inference engine which aims for consistent and complete solutions to problems. | http://www.cs.yale.edu/homes/dvm/daml/ontology-translation.html | CC-MAIN-2018-17 | refinedweb | 360 | 54.02 |
IN THIS ARTICLE
Welcome to Part Two of our tutorial series on building a mobile multiplayer tic tac toe game with React Native and PubNub. In this section, we will work on the actual game itself and testing the game using two methods.
If you haven’t already, check out and go through Part One before working on this section, as we initialized the project and set up the lobby.
Implementing the Game Component
From the project root directory, go to src/components and create a new file named Game.js. All the game logic will be inside of this file. Add the following code to the file:
import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableHighlight, Alert } from 'react-native'; import range from 'lodash'; const _ = range; export default class Game extends Component { constructor(props) { super(props); // Winning combinations this.possible_combinations = [ [0, 3, 6], [1, 4, 7], [0, 1, 2], [3, 4, 5], [2, 5, 8], [6, 7, 8], [0, 4, 8], [2, 4, 6] ]; // Corresponds to the square number on the table this.ids = [ [0, 1, 2], [3, 4, 5], [6, 7, 8] ]; // For the 3x3 table this.rows = [ _.range(3).fill(''), _.range(3).fill(''), _.range(3).fill(''), ]; this.state = { moves: _.range(9).fill(''), x_score: 0, o_score: 0, } this.turn = 'X' // Changes every time a player makes a move this.game_over = false; // Set to true when the game is over this.count = 0; // used to check if the game ends in a draw } }
We do several things in the base constructor:
- First, we set up an array of possible combinations to win the game. If a player matches with any of the combinations, that player is the winner of the game.
- Second, we set up another array named ids that labels every square of the table with a unique id to check if a square has been occupied or not.
- Then, we set up rows which contain three empty arrays with each size of three.
- After, for the state objects, we initialize moves to be an array with empty string values and initialize the score for both players to 0. The array moves will be used to check if there is a winner, as we will see later on.
- Finally, we add three variables, turn, game_over and count that will be useful throughout the game.
Setting up the UI
Let’s set up the UI for the component, which includes the table and the current score and username for each player. Also, include the styles.
GitHub RepoGitHub Repo
render() { return ( <View style={styles.table_container}> <View style={styles.table}> {this.generateRows()} </View> <View style={styles.scores_container}> <View style={styles.score}> <Text style={styles.user_score}>{this.state.x_score}</Text> <Text style={styles.username}>{this.props.x_username} (X)</Text> </View> <View style={styles.score}> <Text style={styles.user_score}>{this.state.o_score}</Text> <Text style={styles.username}>{this.props.o_username} (O)</Text> </View> </View> </View> ); } } const styles = StyleSheet.create({ table_container: { flex: 9 }, table: { flex: 7, flexDirection: 'column', color: 'black' }, row: { flex: 1, flexDirection: 'row', borderBottomWidth: 1, }, block: { flex: 1, borderRightWidth: 1, borderColor: '#000', alignItems: 'center', justifyContent: 'center' }, block_text: { fontSize: 30, fontWeight: 'bold', color: 'black' }, scores_container: { flex: 2, flexDirection: 'row', alignItems: 'center' }, score: { flex: 1, alignItems: 'center', }, user_score: { fontSize: 25, fontWeight: 'bold', color: 'black' }, username: { fontSize: 20, color: 'black' } });
Notice that for the username, we use this.props since we get the value from App.js. As a refresher, here are the values that we’ll be using from App.js.
<Game pubnub={this.pubnub} channel={this.channel} username={this.state.username} piece={this.state.piece} x_username={this.state.x_username} o_username={this.state.o_username} is_room_creator={this.state.is_room_creator} endGame={this.endGame} />
To build the tic tac toe table, we call the method generateRows(), which calls generateBlocks(). These methods are responsible for creating the table.
generateRows = () => { return this.rows.map((row, col_index) => { return ( <View style={styles.row} key={col_index}> {this.generateBlocks(row, col_index)} </View> ); }); } generateBlocks = (row, row_index) => { return row.map((block, col_index) => { let id = this.ids[row_index][col_index]; return ( <TouchableHighlight key={col_index} onPress={ this.onMakeMove.bind(this, row_index, col_index) } underlayColor={"#CCC"} style={styles.block}> <Text style={styles.block_text}> { this.state.moves[id] } </Text> </TouchableHighlight> ); }); }
We use TouchableHightlight so players can touch any square on the table. In order for their corresponding piece to be placed on that square, set the block text to be the value of this.state.moves[id], which will contain the correct piece for the player that made the move. This will be explained more below.
Adding the Logic
Make a call to onMakeMove() with row_index, the row that the piece was placed on, and col_index, the column the piece was placed on, as the method arguments.
onMakeMove(row_index, col_index) { let moves = this.state.moves; let id = this.ids[row_index][col_index]; // Check that the square is empty if(!moves[id] && (this.turn === this.props.piece)){ moves[id] = this.props.piece; this.setState({ moves }); // Change the turn so the next player can make a move this.turn = (this.turn === 'X') ? 'O' : 'X'; // Publish the data to the game channel this.props.pubnub.publish({ message: { row: row_index, col: col_index, piece: this.props.piece, is_room_creator: this.props.is_room_creator, turn: this.turn }, channel: this.props.channel }); this.updateScores.call(this, moves); } }
We get the integer id of the square pressed by getting the value of this.ids[row_index][col_index]. The if statement checks if the square the player touched is empty and if it’s that player’s current turn to place their piece. We ignore the touch if these two conditions are not met. If the conditions are met, we add the piece to the array moves with id as the index.
For example, if the room creator makes a move on row 0 column 2 on the table, then this.ids[0][2] returns the integer 2.
this.ids = [ [0, 1, 2], [3, 4, 5], [6, 7, 8] ];
The piece X is added to the array moves on the second index: [“”, “”, “X”, “”, “”, “”, “”, “”, “”]. Later in updateScores(), we will see how moves is used to check for a winner.
Getting back to onMakeMove(), after we change the state for moves, we update turns so the next player can make their move. We publish the data to the game channel, such as the piece that moved and the position it was placed at. The other player’s table updates with the current data. Finally, make a call to updateScores() to check if there is a winner or if the game ended in a draw.
Before we get to updateScores(), implement the channel listener in componentDidMount() to listen to incoming messages from the channel.
componentDidMount() { // Listen for messages in the channel this.props.pubnub.getMessage(this.props.channel, (msg) => { // Add the other player's move to the table if(msg.message.turn === this.props.piece){ let moves = this.state.moves; let id = this.ids[msg.message.row][msg.message.col]; moves[id] = msg.message.piece; this.setState({ moves }); this.turn = msg.message.turn; this.updateScores.call(this, moves); } }); }
Both players will receive this message since both are subscribed to the same channel. When the message is received, we do several of the same steps we did for onMakeMove(), in particular, update the table and check if there’s a winner. But, we don’t want the player that made the move to do the steps over again. So, we do an if statement to make sure that only the opposite player performs the steps. We do so by checking if turn (which is either X or O) matches the player’s piece.
Let’s now implement the method updateScores().
updateScores = (moves) => { // Iterate the double array possible_combinations to check if there is a winner for (let i = 0; i < this.possible_combinations.length; i++) { const [a, b, c] = this.possible_combinations[i]; if (moves[a] && moves[a] === moves[b] && moves[a] === moves[c]) { this.determineWinner(moves[a]); break; } } }
To determine if there is a winner, we have to iterate possible_combinations to check if any of the combinations are present in the table. This is where the array moves comes in handy. We use [a,b,c] to get each array of possible_combinations. Then check if that matches any pattern in moves. To make this more clear, let’s follow an example.
Let’s say the room creator makes a winning move on row 2 column 2, with an id of 8, on the table. The table will look like the image below:
As you can see, the winning moves are in positions 2, 5, and 8, according to their id’s. The array moves is now: [“O”, “”, “X”, “”, “O”, “X”, “”, “”, “X”]. In updateScores(), we iterate through every possible winning combination.
For this example, the winning combination is [2,5,8]. So when [a,b,c] has the values of [2,5,8], the if statement in the for loop with be true since [2,5,8] all have the same value of X. A call is made to determineWinner() to update the score of the winning player, which in this case, is the room creator. Before we get to that method, let’s finish the rest of updateScores().
If no winner is found and the game ends in a draw, then neither player gets a point. To check if there is a draw, add the following code below the above for loop.
this.count++; // Check if the game ends in a draw if(this.count === 9){ this.game_over = true; this.newGame(); }
Every time a square is pressed on the table, updateScores() is called. If no winner is found, then count increments by one. If the count is equal to 9, the game ends in a draw. This occurs when a player makes a final move on the last square of the table that is not a winning move, so count is incremented from 8 to 9. The method newGame() is then called.
We will get back to newGame() in a bit. Let’s first implement determineWinner().
determineWinner = (winner) => { var pieces = { 'X': this.state.x_score, 'O': this.state.o_score } // Update score for the winner if(winner === 'X'){ pieces['X'] += 1; this.setState({ x_score: pieces['X'] }); } else{ pieces['O'] += 1; this.setState({ o_score: pieces['O'] }); } // End the game once there is a winner this.game_over = true; this.newGame(); }
We check if the winner is the room creator or the opponent and we increment the winner’s current score by 1 point. Once the score has been updated, we set game_over to true and call the method newGame().
Game Over
new_game = () => { // Show this alert if the player is not the room creator if((this.props.is_room_creator === false) && this.game_over){ Alert.alert('Game Over','Waiting for rematch...'); this.turn = 'X'; // Set turn to X so opponent can't make a move } // Show this alert to the room creator else if(this.props.is_room_creator && this.game_over){ Alert.alert( "Game Over!", "Do you want to play another round?", [ { text: "Nah", onPress: () => { this.props.pubnub.publish({ message: { gameOver: true }, channel: this.props.channel }); }, style: 'cancel' }, { text: 'Yea', onPress: () => { this.props.pubnub.publish({ message: { reset: true }, channel: this.props.channel }); } }, ], { cancelable: false } ); } }
We show two different alerts to the room creator and the opponent. The alert for the room creator has a message asking them if they want to play another round or exit the game.
For the opponent, we show them an alert with a message telling them to wait for a new round, which will be decided by the room creator.
If the room creator decides to end the game, then the message gameOver is published to the channel; else the message restart is published to the channel. We take care of these messages by adding some more logic inside of getMessage() in componentDidMount().
componentDidMount() { // Listen for messages in the channel this.props.pubnub.getMessage(this.props.channel, (msg) => { ... if(msg.message.reset){ this.setState({ moves: _.range(9).fill('') }); this.turn = 'X'; this.game_over = false; } if(msg.message.gameOver){ this.props.pubnub.unsubscribe({ channels : [this.props.channel] }); this.props.endGame(); } }); }
If the room creator wants to play another round, then we reset the table as it was at the start of the game. We do so by setting the array moves to its original state. We reset turn to be X again and reset game_over to false.
But if the room creator decides to end the game, then both players unsubscribe from the current channel and a call to the method endGame() is made. This method will end the game and take the players back to the lobby since is_playing is reset to false. The method endGame() is a prop from App.js, so we have to go back to App.js to implement it.
// In App.js endGame = () => { // Reset the state values this.setState({ username: '', rival_username: '', is_playing: false, is_waiting: false, isDisabled: false }); // Subscribe to gameLobby again on a new game this.channel = null; this.pubnub.subscribe({ channels: ['gameLobby'], withPresence: true }); }
We reset all the state values back to its original state and reset the value of channel to null since there will be a new room_id when the Create button is pressed again. Finally, subscribe again to the “gameLobby” channel so the players can continue playing tic tac toe if they choose to.
That is all we need for our React Native tic tac toe game to work! Now, it’s time to test the app and play around with it.
Testing the App
Before running the app, we need to enable the Presence feature to detect the number of people in the channel. To turn it on, go to the PubNub Admin Dashboard and click on your application. Click on Keyset and scroll down to Application add-ons. Toggle the Presence switch to on. Keep the default values the same.
To run the app, make sure you are in the project folder and enter the following command in the terminal:
react-native run-ios
This command will open the simulator and run the app. You can also run the app on the Android emulator by replacing run-ios with run-android (Note: Make sure you open an emulator first before running the command). Once the simulator opens, the lobby UI will be displayed.
We can test the app by either using PubNub’s Debug Console or by running the React app version of the tic tac toe game. The React app is already connected to the React Native app and the necessary logic is taken care of. All you need to do is insert the same Pub/Sub keys from the React Native app.
This section will be broken into two parts to go into detail on how to test the app using the above two methods. For each section, there will be a video that goes over what we did in that section. If you prefer to watch the video instead of reading, go to the end of the section.
Play the Game using the Debug Console
In this section, we will use the debug console to create a channel and the simulator to join that channel. Make sure you have the app opened in the simulator.
To get into the debug console, go the PubNub Admin Dashboard and click on Debug Console that’s on the left sidebar.
On the top bar, select the app and the keys you are using for this project.
You should now see a panel where you can enter the channel name. Change the default channel to “gameLobby” and add the client.
Once the client has been created, replace the default message with:
{"is_room_creator":true, "username":"Player X"}
You can put any username, but for this example, we will be using Player X for the room creator and Player O for the opponent. Click the Send button and you should see the message in the console. Here is a screenshot of what the debug console should look like:
Next, we have to create a new channel for the game. Go to the panel next to the current panel we used and change the default channel to “tictactoe–gameChannel” (Note: While we chose a fixed channel name for the game, in the app if the player presses the Create button, a random channel name will be generated).
Add the client to connect to the new channel. Go back to the previous panel where we sent the first message and unsubscribe from that channel as we won’t be using it anymore.
Now, go to the simulator and for the username type Player O. Click the “Join” button and enter the channel name “gameChannel” (Note: “tictactoe–” will be appended to the channel name, so you don’t have to include that).
Once you press OK, the lobby component will be replaced with the game component and the table UI will be displayed. Since we used the simulator to join the channel, you won’t be able to do anything on the table since the room creator makes the first move. So, on the debug console, replace the default message with:
{"row":0, "col":1, "piece":"X", "is_room_creator":true, "turn":"O"}
Make sure to capitalize both “X” and “O”. Send the above message and you should see an “X” on the simulator’s table. Here is a screenshot of the debug console and the simulator:
Now you are able to make a move in the simulator. To continue playing, only change the values of row and col in the debug console, when it’s the room creator’s turn, to place “X” in different parts of the table. If a player has won that round, the score for the winning player will update in the simulator. An alert message in the simulator will notify the opponent to wait for a new round.
If you want to play another round, type the following message in the debug console:
{"reset":true}
The above message will reset the table in the simulator for a new round. To end the game, type the following message instead:
{"gameOver":true}
Ending the game will send the opponent back to the lobby.
You might have noticed that there are a lot of manual steps when using the debug console. In the app itself, a lot of the manual steps we did are automated, like unsubscribing from “gameLobby” or subscribing to a new channel for the game. We used the debug console because there might be some complications when running two simulators or emulators on your machine. The debug console is a better approach to simulate gameplay of the app.
Instead of the debug console, you could also use the React version of the app to simulate gameplay. By using the React app, you don’t have to worry above manually running commands since everything will be automated, as it should be in the app.
Play the Game using the React App
We will use the simulator to create a channel and the React app to join that channel (Note: The React app is currently set up to only join channels and not create them). You can clone the React app from this repo. Once you open the project, go to the file Game.js and in the constructor, add the same Pub/Sub keys you used for the React Native app. That’s all you have to edit for the React project.
Run the following command in the terminal to install the dependencies:
npm install
To run the app, type the following command in the terminal:
npm start
The app will open in with an empty table and two input fields.
Go to the simulator and in the lobby, type Player X for the username and press the “Create” button to create a new room id. Go back to the browser and for the username field, type Player O. In the room name field, type the room id that was created in the simulator.
Once both fields are filled in, press the Submit button and the game will start for both players. Since the simulator is the room creator, press any square on the table to place an X. You should see the X in both the simulator and in the browser. Try pressing another square in the simulator’s table and you will notice that nothing happens as it’s the opponent’s turn to make a move. In the browser, press any square to place an O.
Keep playing until someone wins or the game ends in a draw. If there is a winner, the winner will be announced in the browser along with the winning squares background color turned to green. In the simulator, the score for the winning player will update and an alert will ask the room creator if they want to play another round or exit the game.
If the room creator decides to play another round, both the simulator’s and the browser’s table will reset for the new round. If the room creator decides to exit the game, the room creator will be taken to the lobby while the browser resets the table. You can create a new channel in the simulator and in the browser you can join that new channel.
What’s Next
If you want to see more examples on how to use PubNub for a React Native project, check out all our React Native tutorials. Or if you want to see the different ways that PubNub is used to power multiplayer games, check out our multiplayer gaming tutorials.
Have suggestions or questions about the content of this post? Reach out at devrel@pubnub.com. | https://www.pubnub.com/blog/multiplayer-mobile-tic-tac-toe-react-native-ios-android-part-two/ | CC-MAIN-2019-51 | refinedweb | 3,597 | 73.47 |
I am working on a plugin and would like to write messages to the output panel, rather than the console with the "print" command. Searching the forums I found out that this has been asked before and was resolved by using the build commands, but in my case I don't think that will work. Is there any way to write to the output panel from a python plugin? Thanks!
There isn't a way to do this yet, but 20090922 does introduce a new feature of scratch buffers - if you create a new buffer, and call view.isScratch(True), then it'll be a more appropriate place to send plugin output: the user won't get prompted to save it.
Thanks for the response and the scratch buffer is cool, but not quite what I had in mind for output. Really I am just looking for a way to display results just as it is in the console or output panel. Console is actually fine, it's just that there is quite a bit of other things being printed there and it would be nice to have a clean panel to send plugin output to.
I tried the scratch panel setting(with beta 20090923) but it didn't seem to work. Here is the python
window = view.window()
results = window.newFile()
results.isScratch(True)
and here is the error in the console
Traceback (most recent call last):
File ".\sublimeplugin.py", line 118, in execTextCommand
File ".\Repl.py", line 35, in run
Boost.Python.ArgumentError: Python argument types in
View.isScratch(View, bool)
did not match C++ signature:
isScratch(class slate::SP<class TextBufferView>)
Try
results.setScratch(results.bufferId())
But I agree we need a way to write to output panel!something like sublime.outputGet() /sublime.outputWrite()
I'll take that back, with setScratch and setReadOnly APIs we can have as many output panels as we want
So I was able to get output printed to a scratch buffer and I can now see some real benefits to using them over the output panel or console and perhaps we don't even need a way to print to output console. One idea I am thinking about would be to create a syntax definition for the scratch buffer to make it more readable. My initial preference was just to be able to have an area at the bottom of the screen to display output and history... perhaps a new layout that had the a pane on bottom that spanned all vertical panes above might be a valuable layout to add and would serve the same purpose but also be tabbed, etc...
** A note for others that might be trying to do the same thing as me. results.setScratch(results.bufferId()) worked perfectly. In order to find the same panel on a second run of the plugin I had to set the name of the scratch buffer and then loop through the all the views and check the name of each one to find the same buffer on a second run of the plugin. I tried results = window.openFile(name) but it just said that it couldn't find the open file with that name, which might be a bug.
I think you just need to use:
results.setScratch(True)
results.bufferId() evaluates to True, that's why it works.
You can keep the scratch buffer in a class variable:
**EDIT: **there's a problem with the code below: if the user closes the "My output" buffer, the plugin will not be aware of it and "self.Results in view.window().views()" always returns false
class MyCommand(sublimeplugin.TextCommand):
Results = ''
def run(self, view, args):
output = "blablabla"
if not self.Results:# or not self.Results in view.window().views():
# Need to create Results scratch buffer
self.Results = view.window().newFile()
self.Results.setScratch(True)
self.Results.setName("My output")
self.Results.insert(-1, output + "\n")
view.window().focusView(self.Results) | https://forum.sublimetext.com/t/write-to-output-panel-from-python-plugin/274 | CC-MAIN-2017-22 | refinedweb | 658 | 72.56 |
I’m working through the Lists and Keys section of the React tutorial.
I’ve created a component,
Board (code below), which draws a tic-tac-toe board made up of buttons contained in
Square (code omitted) components. The
Square components are items in row arrays which are themselves items in a board array to form a grid made up of nested arrays.
I have a question about the following paragraph from the tutorial.
Extracting Components with Keys
Keys only make sense in the context of the surrounding array. For example, if you extract a
ListItemcomponent, you should keep the key on the
<ListItem />elements in the array rather than on the
<li>element in the
ListItemitself.
In my code below, I have a method,
renderSquare, which returns individual elements in the form of
Square components. These elements are stored in an array, so they need a
key prop for React to work its rendering magic. Because
renderSquare is an unbound old-style function/method, I think it takes on the execution context of
gridBuilder, so there’s no problem with assigning the key within the
renderSquare method. However, I’m not sure if using an arrow function for
renderSquare would break the
key rule I quoted above.
Can anyone tell me if I’m understanding the tutorial correctly in regards to the
key prop? Do list-item factories like
renderSquare break how array keys work in React? Does the key absolutely need to be assigned where the list is being created, or are there exceptions?
class Board extends React.Component { renderSquare(i) { return ( <Square key={"square"+i} value={this.props.squares[i]} onClick={() => this.props.onClick(i)} /> ); } // replaced hard-coded grid with loop gridBuilder() { let gridElems = []; let rowElems = []; for (let i = 0; i < 9; i++) { // is it a problem if renderSquare key assignment // doesn't happen in the gridBuilder context? let elem = (this.renderSquare(i)); rowElems.push(elem); if ((i + 1) % 3 === 0) { let row = ( <div className="board-row" key={"row" + ((i+1)/3)}> {rowElems} </div>); gridElems.push(row); rowElems = []; } } return <div>{gridElems}</div> } render () { return ( this.gridBuilder() ); } } | https://forum.learncodethehardway.com/t/react-list-key-context/2557 | CC-MAIN-2022-40 | refinedweb | 349 | 55.64 |
Powerful and simple mechanism of data controller URL parameters allows easy manipulation of the page behavior in Code On Time web applications. For example, consider Products page at. If you navigate to the page and login as admin/admin123% then you will see the following screen with a list of products.
If you want to navigate to a specific product then try the following link. The same page will open in edit mode on the product with the primary key equal to 7.
Data controller parameters offer a simple and powerful method of affecting user interface presentation. Couple that with robust Access Control Rules implementation and your web app will provide an excellent and secure mechanism of navigation to specific records.
Sometimes you may want to prevent any possibility of external commands sent to your application via URL parameters unless the commands were initiated by the web application itself or an external “friendly” source.
Unlimited edition of Code On Time offers a new feature called URL Hashing, which is available as a component of EASE (Enterprise Application Services Engine). The purpose of URL Hashing is to ensure that only encrypted commands can be passed in the URL of your web application.
Start the web application generator, select your project and click Next button a few times until your reach the Features page. Enable URL Hashing under EASE Configuration.
Proceed to generate the project.
Navigate to any page of your web application displaying data and try passing any parameter in the URL. For example, if you are looking at Products.aspx page then change the URL in the address bar of the browser to Products.aspx?AnyParam=Hello and hit enter key to navigate to the page.
You will see the following response.
All applications pages are now protected and will not allow inclusion of any URL parameters.
Your web application may be using URL parameters for its own purpose. For example, configure a Navigate action in the Northwind sample as explained next.
Select your project on the start page of the web app generator and click Design. Select Products data controller on All Controllers tab and activate Action Groups page.
Select action group ag1 with the scope of Grid and switch to Actions tab.
Add a new action with the following properties. Note that Command Argument must be entered without line breaks.
The value of command argument instructs the application to navigate to the current page that hosts the data controller view and pass the ProductID of selected row in the URL. The other URL parameters will force the data controller to open the specified product in editForm1 in Edit mode.
Save the new action, exit the Designer and generate your project.
Navigate to Products page and select the context menu of a product row.
Your browser will navigate to the currently active page with the URL that looks as follows. Notice that there is a parameter “_link” with the cryptic looking value in the address bar of the browser.
URL Hashing mechanism embedded in your application only allows this particular parameter and demands that the value of “ _link” parameter is encrypted.
Alter any portion of the parameter or add any additional URL parameters and the request will fail to display the page with the same HTPP error code 403 presented above.
Sometimes you may need to pass URL parameters from an external web application. If URL Hashing feature is enabled then this task becomes impossible unless you encrypt the URLs passed by external web application.
The implementation of encryption can be found in the StringEncryptorBase class of your application source code. The partial code below shows encryption key (Key) and initialization vector (IV). Both properties are passed by methods Encrypt and Decrypt as arguments to the default implementation of Advanced Encryption Standard (AES) available in Microsoft.NET Framework.
C#:
public class StringEncryptorBase
{
public virtual byte[] Key
{
get
{
return new byte[] {
253,
124,
8,
201,
31,
27,
89, . . . .
153};
}
}
public virtual byte[] IV
{
get
{
return new byte[] {
87,
84,
163,
98,
205, . . . .
112};
}
}
public virtual string Encrypt(string s)
{
. . . . . . }
public virtual string Decrypt(string s)
{
. . . . . .
}
}
VB:
Public Class StringEncryptorBase
Public Overridable ReadOnly Property Key() As Byte()
Get
Return New Byte() {253, 124, . . . ., 153}
End Get
End Property
Public Overridable ReadOnly Property IV() As Byte()
Get
Return New Byte() {87, 84, 163, 98, . . . ., 112}
End Get
End Property
Public Overridable Function Encrypt(ByVal s As String) As String . . . . .
End Function
Public Overridable Function Decrypt(ByVal s As String) As String . . . . .
End Function
End Class
Copy this class to the external application and make sure to encrypt the URLs that are passed to a Code On Time web application with URL Hashing enabled.
You may also want to change the key and initialization vector. The default values are hard-coded and shared by all applications generated with Unlimited edition of Code On Time.
URL Hashing is always performed for History and permalinks. If the application is generated without URL Hashing enabled then the permalinks are simply encoded with base-64 encoding to mask the nature of URL parameters.
Advanced encryption with hash code validation will be performed on links create with View Details command and on results of any actions with Command Name set to Navigate.
Code On Time update 5.0.0.71 has introduced the following enhancements and bug fixes.
We expect to release the next update by the end of the next week and are planning to roll out DotNetNuke Factory. SharePoint Factory will follow shortly thereafter.
New project releases were delayed to allow stabilization of the recent changes to the core application framework and client library. | https://codeontime.com/blog?min-date=2011-09-01T00:00:00&max-date=2011-09-30T23:59:59 | CC-MAIN-2020-16 | refinedweb | 938 | 55.34 |
Look at this code:
#include <iostream> using namespace std; void modify(int *m, int val) { *m = val; cout << *m << endl; } void create(int *m, int val) { m = new int; *m = val; cout << *m << endl; } int * create(int val) { int *n = new int; *n = val; cout << *n << endl; return n; } int main(int argc, const char * argv[]) { int *one; one = new int; modify(one, 1); cout << one << " " << *one << endl << endl; int *two; two = new int; *two = 100; create(two, 2); cout << two << " " << *two << endl << endl; int *three; three = create(3); cout << three << " " << *three << endl << endl; return 0; }
Its output on my (yours may use different addresses) machine:
Quote
1
0x100105470 1
2
0x100105480 100
3
0x1001054a0 3
0x100105470 1
2
0x100105480 100
3
0x1001054a0 3
Looks fine right? No, there's a problem with the second set. We thought it would output 2, but it held onto 100. What happened?
It's easy to forget that in C/C++ parameters are generally passed by value (arrays decay to pointers) by default. Even pointers are passed by value, so in line 11 the new generates a new address that is assigned to the copy of the pointer received, not the original pointer. We've basically created a memory leak since this copy can't be accessed beyond the scope of the function, and we don't intend to delete the object (it doesn't have to be just an int) here, we want to continue using it after the function returns. The first and third functions are alternative methods for doing just that. They don't create leaks! | http://www.dreamincode.net/forums/topic/381666-pointers-and-a-possible-problem-if-youre-not-careful/ | CC-MAIN-2017-17 | refinedweb | 266 | 64.98 |
in reply to Re: The History of Acme::Bleach and Acme::EyeDropsin thread The History of Acme::Bleach and Acme::EyeDrops
It's worth pointing out that when Damian demonstrated to the module to London.pm, it was simply called "Bleach". BackPan confirms that version 1.000 of Bleach.pm was uploaded on 21 Feb 2001. It was only with release 1.012 on 21 May 2001 that it acquired its more recognisable name. So it looks like Acme::Buffy and Acme::Pony both beat it into the Acme namespace.
All of which makes me wonder if Leon had more to do with the invention of the Acme namespace than Damian says above. After all, he's been using the nick "acme" on IRC since well before this all happened :-)
See the Copyright notice on my home node.
Perl training courses
All of which makes me wonder if Leon had more to do with the invention of the Acme namespace than Damian says above.
Damian
he may well have been mind-controlling me without my knowledge
That sounds likely to me. It's always seemed suspicious that Acme and Uri were the only Perl programmers with their own CPAN namespaces :-)
He bestowed his most aranciate blessing on the choice:
Thunder fish
Shocky knifefish
TBD
Electric eels were invented at the same time as electricity
Before electricity was invented, electric eels had to stun with gas
Results (293 votes). Check out past polls. | http://www.perlmonks.org/?node_id=967813 | CC-MAIN-2017-09 | refinedweb | 242 | 71.85 |
Technical Support
On-Line Manuals
RL-ARM User's Guide (MDK v4)
#include <RTL.h>
#include <rl_usb.h>
U32 usbh_ohci_hw_reg_rd (
U32 reg_ofs
);
The usbh_ohci_hw_reg_rd function is used for reading a
value from the OHCI USB Host register.
The usbh_ohci_hw_reg_rd function is part of the RL-USB
Host software stack.
You can modify this function to suit different OHCI controller
register interface. This function will need to be changed if OHCI
controller is used on a chip that does not yet have a low level
driver provided.
The usbh_ohci_hw_reg_rd function returns 32-bit value read
from OHCI register._wr
U32 usbh_ohci_hw_reg_rd (U32 reg_ofs) {
return (*((U32 *)(USBH_OHCI_ADR + reg. | http://www.keil.com/support/man/docs/rlarm/rlarm_usbh_ohci_hw_reg_rd.htm | CC-MAIN-2020-05 | refinedweb | 106 | 58.99 |
C#
Back when I was doing GameDev.Tv‘s Unity 2D class, I really wanted to know how to do multiplayer games (I also wanted some better support on using Xbox/PS3 remotes in games). Well, this year they released their Multiplayer class. So, naturally, I bought it up. I started working on it, resulting in two Github Repos. In the first section we were learned the basics of the Mirror add-on. I’m currently working through the second section, where we will create a basic RTS. I haven’t reached a real differentiation point from the GameDev folks. That may come later after we get past the basics.
Scratch
This summer when I was doing Scratch projects with the kids, I’d bookmarked a couple and then I went back to work on a normal schedule. So I wanted to finally get to these. Since Scarlett really loves art, I chose to do the Pattern Pen project with her. It was a great project to do, as it taught me about lists in Scratch as well as the Pen module, which, essentially, add capabilities like the Turtle programming language. The final program looked like this:
In order to get the values for the degrees and increase lists, there was an intermediate step where the program would ask the user for values. Then the programmer was supposed to take note of the ones they liked for use in the final version. Scarlett preferred the interactivity so we did save off a version of the program at that point in development so she could play with it some more in the future. I thought she’d like it because she’s art oriented, I had no idea how much she’d love it.
Here’s a video of it in action:
Python
Since the last time I wrote about my programming projects, I had mostly been focused on the C# Unity Multiplayer class and getting the footage ready for the End of the Year video game post. But it turned out that I still had a couple Python Morsels left in my free trial and then I happened to be on discord when the Python discord mentioned something called Advent of Code…
Python Morsels
This one turned out not to be too bad. Trey wanted us to “write a function that takes a nested list of numbers and adds up all the numbers”. I somewhat tried to outsmart myself trying to be Pythonic. After a while I gave up and went for recursion. I ended up with:
def sums(iterable): sum = 0 for number in iterable: if isinstance(number, list): if len(number) == 0: sum = sum + 0 else: sum = sums(number) + sum else: sum = number + sum return sum def deep_add(iterable): # print(f"The iterable {iterable}") return sums(iterable)
Turns out I wasn’t too far off from one of Trey’s recommended solutions. The only thing he did to make it more efficient was to make it use a generator in the recursion. Bonus 1 had to take in any iterable, not just a list. Bonus 2 adds a start value. Basically an extra number to add in addition to the iterable. Bonus 3 had to work on anything “number-like”. That meant things like time deltas. My final code looked like:
from collections import Iterable def sums(iterable, start): sum = start for number in iterable: if isinstance(number, Iterable): if len(number) == 0: sum = sum + 0 else: sum = sums(number, sum) else: sum = number + sum return sum def deep_add(iterable, start=0): # print(f"The iterable {iterable}") return sums(iterable, start)
Overall, thanks to all that I’d learned during my various Python Morsels lessons, it was an easy problem set and I only needed a small break during part 3 to get my brain to solve it for me.
Advent of Code
As I mentioned above, I heard about Advent of Code in the Python discord. It’s a series of brain teaser programming word problems with an over-arching story being told within the problems. This year, the programmer is going to take a vacation from helping Santa. Each day presents another aspect of his journey where programming helps him solve a problem and get on to the next task. As I write this, today is Day 9. So far, Day 7 has given me the most trouble. In fact, I still haven’t finished part 2 of the Day 7 task. Outside of Day 7 I’ve been having a blast. Some puzzles have been really hard while others (like Days 8 and 9) have been really easy. Day 9 was especially easy because I learned about deques in Python Morsels. Each day, accomplishing the teaser for that day fills me with a sense of joy akin to any other puzzle solving endeavor. I also love seeing how others are solving the problems, including someone who is coding each problem in Unreal Engine. Here’s an example:
I’ve got a Github repo where I’m keeping track of all of my solutions. I’ll certainly have more to say about this during the end of year wrapup blog post on programming. | http://www.ericsbinaryworld.com/2020/12/09/programming-update/?shared=email&msg=fail | CC-MAIN-2021-10 | refinedweb | 867 | 69.31 |
Hi,
I'm sorry I misunderstand your requirement.
Your original requirement is adding extra namespace for the client
request soap message generated by SOAPUI, right? As your client side
is SOAPUI, it has nothing to do with cxf, so cxf interceptors can't
take effect anyway.
The interceptor way we discussed here is only applicable if you use
cxf client to send out soap message.
In SOAPUI, I think you can alway manually edit the request soap
message based on the default one generated from wsdl, so that you get
changes to add extra namespace, not sure how SOAPUI can add extra
namespace automatically.
Freeman
On 2011-3-31, at 下午12:53, Dipti Vaidya wrote:
> Hi Freeman,
>
> I've been trying out what is described by Dan in the post you
> mentioned, but
> it doesn't seem to work for me.
> I'm not sure if I'm doing something wrong.
>
> Here's what my custom interceptor looks like
>
> myCustomInterceptor extends AbstractSoapInterceptor
> {
> super.phase(Phase.PRE_STREAM);
> addBefore(SoapOutInterceptor.class.getName());
> }
>
> handleMessage(SoapMessage message)
> {
> Map<String, String> nsMap = new HashMap<String, String>();
> nsMap.put("ns2", "");
> mesage.put("soap.env.ns.map", nsMap);
> }
>
> I've added myCustomInterceptor to the list of of OutInterceptors in my
> Spring service bean endpoint bean definition.
>
> When I run in debug mode, I see the constructor for
> MyCustomInterceptor is
> being called..but the handleMessage method is never called.
>
> What am I missing here? When is the handleMessage called? Is the map
> to be
> populated in the handleMessage method or is there someother method
> in the
> code that the map should be populated?
>
> Please let me know.
> Thanks,
> Dipti
>
> --
> View this message in context:
> Sent from the cxf-user mailing list archive at Nabble.com.
---------------------------------------------
Freeman Fang
FuseSource
Web: fusesource.com
Twitter: freemanfang
Connect at CamelOne May 24-26
The Open Source Integration Conference | http://mail-archives.apache.org/mod_mbox/cxf-users/201104.mbox/%3C0DDFA882-771A-4B6A-931A-9BF207E233DE@gmail.com%3E | CC-MAIN-2014-52 | refinedweb | 306 | 56.86 |
This action will force synchronization from Nrush/nr_micro_shell, which will overwrite any changes that you have made since you forked the repository, and can not be recovered!!!
Synchronous operation will process in the background and will refresh the page when finishing processing. Please be patient.
v1.0.1
In debugging and maintenance, it is often necessary to interact with the MCU to obtain, set parameters or perform some operations, nr_micro_shell is a basic command-line tool written for MCU with less resources to meet this demand. Although a powerful finsh command-line interaction tool has been provided in the RT_Thread component. However, for a MCU with less ROM and RAM resources, finsh is still too large. If you want to retain use a command-line tool on these platforms, nr_micro_shell may be a good choice.
nr_micro_shell has the following advantages
Less resources, simple use, flexibility and convenience. Only two functions, shell_init() and shell() , are involved in the use process. It is convenient to use this tool without additional coding work on a MCU with RTOS or a bare MCU.
Good interaction experience. It is exactly similar to the Linux shell command line. When the serial port terminal supports ANSI (such as hypertrm terminal), it not only supports the basic command line interaction, but also provides the function of tab command completion, query history command, and direction key moving cursor modification.
Good expansibility. nr_micro_shell provides users with standard function prototypes of custom commands. When you want difine your own command, just write command functions and register command functions.
Comparison of resources occupied by nr_micro_shell and finsh (finsh does not use MSH) under the same configuration.
the configuration:
the demonstration of nr_micro_shell
nr_micro_shell package follows MIT license. Please refer to the 'license' file for details.
None
You need to select nr_micro_shell package from rt_thread package manager. The specific path is as follows:
RT-Thread online packages miscellaneous packages ---> [*] nr_micro_shell:Lightweight command line interaction tool. --->
After pressing the 'sapce' key to select the relevant settings, press' Enter 'to configure the relevant parameters. Then let the package manager of rt_thread update automatically, or use the 'Pkgs --update' command to update the package to BSP.
If you need to run the samples, please ensure that the 'using console for kt_printf.' option in rt_thread configuration is turned on, kt_printf can work normally, and the 'use components automatically initialization.' option is turned on. nr_micro_shell can be used for direct download or simulation. When the command line is blank, press tab to display all supported commands. For the test sample command, see the use gifs under doc/pic. For the customized command process, please refer to the method in the following 3 Using nr_micro_shell package without RTOS.
All configuration work can be done in the nr_micro_shell_config.h. For details, see the comments in the file.
Make sure all files have been added into your project.
Make sure the Macro function 'shell_printf(),ansi_show_char()' can be used in your project.
An example is given as follow
#include "nr_micro_shell.h" int main(void) { /* Initialization */ shell_init(); while(1) { if(USART GET A CHAR 'c') { /* nr_micro_shell receives characters. */ shell(c); } } }
Before using hardware input directly, it is recommended to use the following code (ensure that information can be printed normally) to verify whether nr_micro_shell can work.
#include "nr_micro_shell.h" int main(void) { unsigned int i = 0; /* NR_SHELL_END_OF_LINE 0 */ char test_line[] = "test 1 2 3\n" /* Initialization */ shell_init(); /* test */ for(i = 0; i < sizeof(test_line)-1; i++) { shell(test_line[i]); } while(1) { if(USART GET A CHAR 'c') { /* nr_micro_shell接收字符 */ shell(c); } } }
STEP1:
You should realize a command function in nr_micro_shell_commands.c. The prototype of the command function is as follow
void your_command_funtion(char argc, char *argv) { ..... }
argc is the number of parameters. argv stores the starting address and content of each parameter. If your input string is
test -a 1
then the argc will be 3 and the content of argv will be
------------------------------------------------------------- 0x03|0x08|0x0b|'t'|'e'|'s'|'t'|'\0'|'-'|'a'|'\0'|'1'|'\0'| -------------------------------------------------------------
If you want to know the content of first or second parameter, you should use
/* "-a" */ printf(argv[argv[1]]) /* "1" */ printf(argv[argv[2]])
STEP2:
You need to register commands before using them. There are two ways to register commands.
const static_cmd_st static_cmd[] = { ..... {"your_command_name",your_command_funtion}, ..... {"\0",NULL} };
Attention: DO NOT DELETE {"\0",NULL} !
NR_SHELL_CMD_EXPORT(your_command_name,your_command_funtion);
Use NR_SHELL_USING_EXPORT_CMD to select the command registration method according to your usage habits.
When using static_cmd[], ensure that a registry exists in your project
const static_cmd_st static_cmd[] = { ..... {"\0",NULL} };
When using NR_SHELL_CMD_EXPORT(), make sure that NR_SHELL_CMD_EXPORT() supports the compiler used, otherwise an error will be reported.
ESC key not supported. | https://portrait.gitee.com/gaat_yin/nr_micro_shell/blob/master/README_EN.md | CC-MAIN-2020-50 | refinedweb | 768 | 56.35 |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <persons> <person> <id>person0</id> <name>name0</name> </person> <person> <id>person1</id> <name>name1</name> </person> ...
There is a corresponding Person Java object for the Person entity in the XML
..
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "id", "name" }) public class Person { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String value) { this.name = value; } }
and a PersonList object to represent a collection of Persons.
@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "persons") public class PersonList { @XmlElement(name="person") private List<person> personList = new ArrayList<person>(); public List<person> getPersons() { return personList; } public void setPersons(List<person> persons) { this.personList = persons; } }
The approaches investigated were:
- Various flavours of JAXB
- SAX
- DOM
implementations for JAXB, SAX and DOM were used. The Woodstox STAX parsing was then used. This would have been called in some of the JAXB unmarshalling tests.
The tests were carried out on my Dell Laptop, a Pentium Dual-Core CPU, 2.1 GHz running Windows 7.
Test 1 – Using JAXB to unmarshall a Java File.
@Test public void testUnMarshallUsingJAXB() throws Exception { JAXBContext jc = JAXBContext.newInstance(PersonList.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); PersonList obj = (PersonList)unmarshaller.unmarshal(new File(filename)); }
Test 1 illustrates how simple the progamming model for JAXB is. It is very easy to go from an XML file to Java objects. There is no need to get involved with the nitty gritty details of marshalling and parsing.
Test 2 – Using JAXB to unmarshall a Streamsource
Test 2 is similar Test 1, except this time a Streamsource object wraps around a File object. The Streamsource object gives a hint to the JAXB implementation to stream the file.
@Test public void testUnMarshallUsingJAXBStreamSource() throws Exception { JAXBContext jc = JAXBContext.newInstance(PersonList.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); StreamSource source = new StreamSource(new File(filename)); PersonList obj = (PersonList)unmarshaller.unmarshal(source); }
Test 3 – Using JAXB to unmarshall a StAX XMLStreamReader
Again similar to Test 1, except this time an XMLStreamReader instance wraps a FileReader instance which is unmarshalled by JAXB.
@Test public void testUnMarshallingWithStAX() throws Exception { FileReader fr = new FileReader(filename); JAXBContext jc = JAXBContext.newInstance(PersonList.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); XMLInputFactory xmlif = XMLInputFactory.newInstance(); XMLStreamReader xmler = xmlif.createXMLStreamReader(fr); PersonList obj = (PersonList)unmarshaller.unmarshal(xmler); }
Test 4 – Just use DOM
This test uses no JAXB and instead just uses the JAXP DOM approach. This means straight away more code is required than any JAXB approach.
@Test public void testParsingWithDom() throws Exception { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(filename); List personsAsList = new ArrayList(); NodeList persons = doc.getElementsByTagName("persons"); for (int i = 0; i <persons.getLength(); i++) { Element person = (Element)persons.item(i); NodeList children = (NodeList)person.getChildNodes(); Person newperson = new Person(); for (int j = 0; j < children.getLength(); j++){ Node child = children.item(i); if (child.getNodeName().equalsIgnoreCase("id")) { newperson.setId(child.getNodeValue()); } else if (child.getNodeName().equalsIgnoreCase("name")) { newperson.setName(child.getNodeValue()); } } personsAsList.add(newperson); } }
Test 5 – Just use SAX Test 5 uses no JAXB and uses SAX to parse the XML document. The SAX approach involves more code and more complexity than any JAXB approach. The Developer has to get involved with the parsing of the document.
@Test public void testParsingWithSAX() throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); final List<person> persons = new ArrayList<person>(); DefaultHandler handler = new DefaultHandler() { boolean bpersonId = false; boolean bpersonName = false; public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("id")) { bpersonId = true; Person person = new Person(); persons.add(person); } else if (qName.equalsIgnoreCase("name")) { bpersonName = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { } public void characters(char ch[], int start, int length) throws SAXException { if (bpersonId) { String personID = new String(ch, start, length); bpersonId = false; Person person = persons.get(persons.size() - 1); person.setId(personID); } else if (bpersonName) { String name = new String(ch, start, length); bpersonName = false; Person person = persons.get(persons.size() - 1); person.setName(name); } } }; saxParser.parse(filename, handler); }
The tests were run 5 times for 3 files which contain a collection of Person entities. The first first file contained 100 Person entities and was 5K in size. The second contained 10,000 entities and was 500K in size and the third contained 250,000 Person entities and was 15 Meg in size. In no cases was any XSD used, or any validations performed. The results are given in result tables where the times for the different runs are comma separated.
TEST RESULTS
The tests were first run using JDK 1.6.26, 32 bit and the reference implementation for SAX, DOM and JAXB shipped with JDK was used.
JDK 1.6.26 Test comments
- The first time unmarshalling happens is usually the longest.
- The memory usage for the JAXB and SAX is similar. It is about 2 Meg for the file with 10,000 persons and 36 – 38 Meg file with 250,000. DOM Memory usage is far higher. For the 10,000 persons file it is 6 Meg, for the 250,000 person file it is greater than 130 Meg.
- The performance times for pure SAX are better. Particularly, for very large files.
The exact same tests were run again, using the same JDK (1.6.26) but this time the Woodstox implementation of StAX parsing was used.
JDK 1.6.26 + Woodstox test comments
- Again, the first time unmarshalling happens is usually proportionally longer.
- Again, memory usage for SAX and JAXB is very similar. Both are far better
than DOM. The results are very similar to Test 1.
- The JAXB (StAX) approach time has improved considerably. This is due to the
Woodstox implementation of StAX parsing being used.
- The performance times for pure SAX are still the best. Particularly
for large files.
The the exact same tests were run again, but this time I used JDK 1.7.02 and the Woodstox implementation of StAX parsing.
JDK 7 + Woodstox test comments:
- The performance times for JDK 7 overall are much better. There are some anomolies – the first time the 100 persons and the 10,000 person file is parsed.
- The memory usage is slightly higher. For SAX and JAXB it is 2 – 4 Meg for the 10,000 persons file and 45 – 49 Meg for the 250,000 persons file. For DOM it is higher again. 5 – 7.5 Meg for the 10,000 person file and 136 – 143 Meg for the 250,000 persons file.
Note: W.R.T. all tests
- No memory analysis was done for the 100 persons file. The memory usage was just too small and so it would have pointless information.
- The first time to initialise a JAXB context can take up to 0.5 seconds. This was not included in the test results as it only took this time the very first time. After that the JVM initialises context very quickly (consistly < 5ms). If you notice this behaviour with whatever JAXB implementation you are using, consider initialising at start up.
- These tests are a very simple XML file. In reality there would be more object types and more complex XML. However, these tests should still provide a guidance.
Conclusions:
- The peformance times for pure SAX are slightly better than JAXB but only for very large files. Unless you are using very large files the performance differences are not worth worrying about. The progamming model advantages of JAXB win out over the complexitiy of the SAX programming model. Don’t forget JAXB also provides random accses like DOM does. SAX does not provide this.
- Performance times look a lot better with Woodstox, if JAXB / StAX is being used.
- Performance times with 64 bit JDK 7 look a lot better. Memory usuage looks slightly higher.
Reference: JAXB, SAX, DOM Performance from our JCG partner Alex Staveley at the Dublin’s Tech Blog .
Related Articles : | http://www.javacodegeeks.com/2011/12/jaxb-sax-dom-performance.html | CC-MAIN-2014-52 | refinedweb | 1,324 | 51.65 |
Code: Select all
>>> i2c.scan() [60]
1) Should i use I2C from the pyb library or machine library? Which is correct and best way?
Python rule 13 -There should be one-- and preferably only one --obvious way to do it.
2) From the machine library here ( ... e.I2C.html) it says that the class is constructed like this: class machine.I2C(id=-1, *, scl, sda, freq=400000)
Does this mean that we have 2 key words that are defaulted if you don't provide them which are id and freq? So you can construct the object by just providing the scl and sda arguments right? And those arguments have to be pin objects specifying the pin to use? So why does this work:
Code: Select all
>>> import machine >>> i2c = machine.I2C('X') >>> i2c.scan() [60]
3) If I try and create an I2C object and provide it with the correct values it does not seem to work for me, maybe someone can spot my school boy error!!!!
Code: Select all
>>> i2c = I2C(id=-1, scl=machine.Pin(9), sda=machine.Pin(10), freq=400000) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't convert 'int' object to str implicitly
So from here: ( ... e.Pin.html)
It says:
Code: Select all
from machine import Pin # create an output pin on pin #0 p0 = Pin(0, Pin.OUT)
Code: Select all
>>> i2c = I2C(id=-1, scl=machine.Pin('X9'), sda=machine.Pin('X10'), freq=400000) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: extra keyword arguments given
4) I'm guessing this, but for the pyboard 'D' it's already setup to use pin X9 and X10 is this correct?
OK - I'm off for a coffee and some chicken... Please someone cheer me up and answer this post!
Kind regards, Nicholas. | https://forum.micropython.org/viewtopic.php?p=36809 | CC-MAIN-2019-51 | refinedweb | 309 | 82.34 |
String [] split (String regex):This method splits the invoking string into substrings at each match for a specified regular expression regex and returns a reference to an array of substrings. For example, consider the statements.
String str = "Hello Java";
String[] s = str.split("[]");
The first statement defines the string to be analyzed. The second statement calls the split () method for the str object to decompose the string. The regular expression includes the delimiterspace so it will return a reference to array of strings where s[0] contains Welcome, s[1] contains toand s[2] contains Java.
public class StringSplit
{
public static void main(String[] args)
{
String str3 = "Where there is a Will , there is a way";
String str[] = str3.split(" ");
for(int i=0;i<str.length;i++)
System.out.println("str[" + i + "] : " + str | http://ecomputernotes.com/java/array/string-split | CC-MAIN-2020-16 | refinedweb | 134 | 66.64 |
Quoting T?r?k Edwin (edwin@gurde.com):> On Tuesday 18 April 2006 22:50, Arjan van de Ven wrote:> >> > I would suspect that the "filename" thing will be the biggest achilles> > heel...> > after all what does filename mean in a linux world with> > * hardlinks> > * chroot> > * namespaces> > * bind mounts> > * unlink of open files> > * fd passing over unix sockets> > * relative pathnames> > * multiple threads (where one can unlink+replace file while the other is> > in the validation code)> > FYI fireflier v1.1.x created rules based on filenames.> In the current version we intended to use mountpoint+inode to identify > programs. This reduces the potential problems from your list to: fd passing.> > Can't AppArmor use inodes in addition to filenames to implement its rules? > The user could still make its choice based on a "filename" (in an interactive Doesn't help with, for instance, /etc/shadow. Run passwd once and theinode number is obsolete.So either you find a way to decisively use the pathname to identify it,or you make sure that anyone who can replace it, labels it.> - use extended attributes to label files, using selinux's setfiles. Most > secure option IMHOAgain, xattrs alone may be insufficient if the file can be replaced.> - store rules based on mountpoint+inode+program hash/checksum, and then get > selinux to label files according to this. Not sure how to do this, and if it > is worth at allAgain, you're only addressing initial labeling. But I guess you'relabeling executables so that should be fine.-serge-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2006/4/18/225 | CC-MAIN-2018-13 | refinedweb | 282 | 64.61 |
Hello!
So I have a program that is split into different functions.
I have a main menu and depending on what option I select a function is called. My problem is, the screen only renders new things when the program returns from a function. How can I make it render new things while still inside the function?
For example:
def screen_test(): global screen, prev_screen prev_screen = lv.scr_act() screen = lv.obj() authLabel = lv.label(screen, None) authLabel.align(None, lv.ALIGN.CENTER, -80, -10) authLabel.set_text("Test Screen") lv.scr_load(screen) prev_screen.delete() utime.sleep(5)
It will only render after the 5 seconds. Is there a way to render whenever I want from inside a function?
Thanks! | https://forum.lvgl.io/t/how-screen-rendering-works/1981 | CC-MAIN-2020-24 | refinedweb | 117 | 71.31 |
need help to create a tool for the blind users
By
nacerbaaziz, in AutoIt General Help and Support
Recommended Posts
Similar Content
- By Skyrimfus
How can i determine wich button was pressed when I use more than one button, without delcaring the button in a variable.
happylukeKhác với các nhà cái trong top 10 nhà cái mà BettingTop10 đã giới thiệu, là các nhà cái chuyên về cá cược thể thao nói chung và cá cược bóng đá nói riêng, HappyLuke là một nhà cái Casino, chuyên về các trò chơi như Baccarat, Xì Dách, Rồng Hổ, Roulette, Sicbo và nhiều trò chơi khác … và không cung cấp dịch vụ cá cược thể thao, cược bóng đá ở thời điểm hiện tại. HappyLuke được cấp phép hoạt động tại Philippines thông qua Tổ Chức Cá Cược Quốc Tế PAGCOR và chấp thuận nghiêm ngặt các quy tắc riêng của mỗi thị trường mà mình tham gia hoạt động.[/img]
Example:
#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #Region ### START Koda GUI section ### Form= $Form1 = GUICreate("Form1", 600, 600, 192, 124) GUISetState(@SW_SHOW) For $i=0 to 5 GUICtrlCreateButton("Button"&$i,0,$i*50,60,30) Next #EndRegion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case 3 to 8 MsgBox(0,0,"You pressed button:") EndSwitch W.
-
- | https://www.autoitscript.com/forum/topic/199425-need-help-to-create-a-tool-for-the-blind-users/ | CC-MAIN-2019-35 | refinedweb | 221 | 62.14 |
Does Call by reference Java supports?
This is a very basic question asked in every interview and should known to each programmer also.
Everyone says "no" as Java does not support pointers. No one actually see the address of the object in Java. No one can dream of call by reference without pointers with their experience of C/C++.
Of course, they are very correct.
In Java the method parameters can be primitive data types or object references. Both are passed as value only but small tricky explanation is here for object references. I repeat, when primitive data types are passed as method parameters, they are passed by value (a copy of the value) but incase of object references, the reference is copied (of course, here also a copy only) and passed to the called method. That is, object reference is passed as a value. So, original reference and the parameter copy both will refer the same Java object. As both refer the same object, if the calling method changes the value of its reference (passed from calling method), the original object value itself changes. Note that object itself is not passed, but it’s references is passed.
Object reference is a handle to a Java object. Do not compare this reference term with the used in C/C++. In C/C++, the reference directly points to the memory address of a variable and can be used for pointer manipulations.
Finally to say, in Java, everyone is passed by value. But with objecct, the value of the reference is passed.
Let us see two programs on call by value and call by reference.
Case 1: Call-by-value or Pass-by-value
In the following program, a data type int is passed as parameter to a method call.
public class CallByValue { public void display(int y) { y = 20; } public static void main(String args[]) { CallByValue cbv = new CallByValue(); int x = 10; cbv.display(x); System.out.println(x); // prints 10 and not 20 } }
The variable x value 10 is passed to parameter of y of display() method. As copy of x is passed, changing y does not change x value in main() method.
Case 2: Call by reference Java or Pass-by-reference
Here, for display() method the reference of StringBuffer object is passed.
public class CallByReference { public void display(StringBuffer sb2) { sb2.append("World"); System.out.println(sb2); // prints HelloWorld } public static void main(String args[]) { CallByReference cbr = new CallByReference(); StringBuffer sb1 = new StringBuffer("Hello"); cbr.display(sb1); System.out.println(sb1); // prints HelloWorld } }
The value of object reference sb1 is passed to sb2. sb1 literal value "Hello" is passed to sb2. Now sb1 reference and sb2 reference refer the same object. Changing sb2 affects sb1 also. Both sb1 and sb2 prints "HelloWorld".
View All for Java Differences on 90 Topics
6 thoughts on “Call by value and Call by reference Java Tutorial”
What do you think about this program? Is it call by value or reference as per your post?
class Test {
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println(“i = ” + i + “, j = ” + j);
}
}
public class Test
{
int x=12, y=25;
public static void main()
{
int x=5, z=10;
String s= “Java is Fun”;
System.out.println(x+” “+ y + “ “ + z);
Function1(x,z);
System.out.println(x+ “ “+y + “ “+z);
System.out.println(s);
Function2(s);
System.out.println(s);
}// end of main
public static void Function2( String s)
{
System.out.println(x+” “+ y );
s=”Java is Platform Independent”;
System.out.println(s);
return;
} // end of Function2
public static void Function1(int x, int z)
{
System.out.println(x+ “ “+y + “ “+z);
x++; z++; y++;
System.out.println(x+ “ “+y + “ “+z);
return;
} // end of Function1
}// end of class
1. Identify the calling and the called methods.
2. Which function is called using CBV and which is called using CBR?
3. Identify the local variables in each method.
4. Identify the global variables.
5. Identify the composite datatypes in the above code
6. Give the output of the above code
class CallByReference
{
public void display(StringBuffer sb2)
{
sb2.append(“World”);
System.out.println(sb2); // prints HelloWorld
}
public void setData(Integer i) {
++i;
}
public static void main(String args[])
{
CallByReference cbr = new CallByReference();
StringBuffer sb1 = new StringBuffer(“Hello”);
cbr.display(sb1);
System.out.println(sb1); // prints HelloWorld
Integer a = new Integer(19);
cbr.setData(a); //It should append the value of a
System.out.println(a); //It should print 20 as per the code which you explained but its giving 19
}
}
thank u sir
but there is little confusion in pass by reference .. plz try it in more easy way
how can we use call by reference in numeric data……?
You cannot use on numeric data. If required, convert int to Integer and then use. | https://way2java.com/java-general/call-by-value-and-call-by-reference-in-java-tutorial/ | CC-MAIN-2022-33 | refinedweb | 826 | 58.18 |
daylight, timezone, tzname, tzset - sets and accesses time
zone conversion information
#include <time.h>
void tzset(void);
extern int daylight; extern long timezone; extern char
*tzname[];
Standard C Library (libc.so, libc.a)
Interfaces documented on this reference page conform to
industry standards as follows:
tzset(): POSIX.1, XSH4.2
Refer to the standards(5) reference page for more information
about industry standards and associated tags.
The tzset() function uses the value of the environment
variable TZ to set time conversion information used by
several other functions, including ctime(), ctime_r(),
getdate(), getdate_r(), localtime(), localtime_r(),
mktime(), strftime(), and strptime().
If the TZ variable is not set, tzset() uses implementation-dependent
default time zone information. This information
is located in the /etc/zoneinfo/localtime file. See
the section Time Zone Handling for details.
The tzset() function sets the external variable tzname as
follows:
tzname0 = "std"; tzname1 = "dst";
where std indicates the standard time zone and dst designates
the alternative time zone (such as Daylight Savings
Time). (These variables are described below in the section
TZ Environment Variable.)
The tzset() function also sets the external variable daylight
to 0 if Daylight Savings Time conversions should
never be applied for the time zone in use. Otherwise, daylight
is set to a nonzero value.
The external variable timezone is set to the difference,
in seconds, between Coordinated Universal Time (UTC) and
local standard time. For example:
---------------
TZ timezone
---------------
EST 5*60*60
GMT 0*60*60
JST -9*60*60
MET -1*60*60
MST 7*60*60
PST 8*60*60
---------------
Time Zone Handling [Toc] [Back]
The operating system uses a public-domain time zone handling
package that puts time zone conversion rules in easily
accessible and modifiable files. These files are in
the directory /etc/zoneinfo/sources. The time zone compiler
zic(8) converts these files to a special format
described in tzfile(4) and places them in the /etc/zoneinfo
directory. This format is readable by the C library
functions that handle time zone information.
The tzset() function uses the tzfile-formatted file linked
by /etc/zoneinfo/localtime to set the time zone conversion
information. The /etc/zoneinfo/localtime link is set during
installation to a file in the /etc/zoneinfo directory.
For example, for time zone information consistent with the
city of New York on the American continent, /etc/zoneinfo/localtime
is linked to /etc/zoneinfo/America/New_York.
If the TZ environment variable is defined, the defined
value overrides the time zone information in /etc/zoneinfo/localtime.
TZ can be set by a user as a regular
environment variable for converting to alternate time
zones. See the section TZ Environment Variable for
details.
Getting Time Zone Information [Toc] [Back]
The libc routines ctime() and localtime() return the local
time and time zone information. The ctime() routine
returns a string that corresponds to the local time; for
example, Tue Oct 27 13:35:29 1992.
The localtime() routine returns a pointer to a tm structure
(defined in <sys/time.h>) that contains the local
time expressed in fields of the tm structure. For time
zone information, there are three relevant fields: A
option that is set to 1 if daylight savings time is currently
in effect. Otherwise, the option is set to 0. Seconds
east of Greenwich. For example, -18000 means 5 hours
west of Greenwich. Abbreviation for the current time zone
(for example, EST, PDT, GMT).
Setting Time Zone Information [Toc] [Back]
The /etc/zoneinfo/localtime link can be changed by the
system administrator to any file in the /etc/zoneinfo
directory.
For example, the following command changes the local time
zone to be consistent with the city of New York on the
American continent:
# ln -sf /etc/zoneinfo/America/New_York /etc/zoneinfo/localtime
Subsequent calls to the time zone related functions in
libc (ctime() and localtime()) use this link for the
default time zone information.
If the time zone and daylight savings time information in
the /etc/zoneinfo/sources directory is incorrect for your
time zone, you can change the information in the source
files and then use the zic command to generate a corresponding
/etc/zoneinfo file.
A user can override the default time zone information by
setting the TZ environment variable as described in the
section TZ Environment Variable.
TZ Environment Variable [Toc] [Back]
When TZ appears in the environment and its value is not a
null string, the value has one of three formats:
: :pathname stdoffset[dst[offset][,start[/time],end[/time]]]
[Tru64 UNIX] If TZ has the single colon format (:), Coordinated
Universal Time (UTC) is used.
[Tru64 UNIX] If TZ has the colon-pathname format (:pathname),
the characters following the colon specify the
pathname of a tzfile(4) format file from which to read the
time conversion information. A pathname beginning with a
slash (/) represents an absolute pathname; otherwise, the
pathname is relative to the system time conversion information
directory /etc/zoneinfo.
If TZ does not begin with a colon (:), the components of
the string are as follows: Three or more characters that
are the designation for the standard (std) or alternative
(dst) time zone (such as Daylight Savings Time). Only std
is required. If dst is not supplied, the alternative time
does not apply to the locale. Upper- and lowercase letters
are explicitly allowed. Any characters, except digits, a
leading colon (:), comma (,), minus (-), plus (+), and
ASCII NUL, are allowed. Indicates the value to be added
to the local time to arrive at GMT. The offset has the
form:
hh[:mm[:ss]]
The minutes (mm) and seconds (ss) are optional. The
hour (hh) is required and can be either one or two
digits. The offset following std is required. If no
offset follows dst, the alternative time is assumed
to be one hour ahead of standard time. One or more
digits can be used; the value is always interpreted
as a decimal number. The hour value must be
between zero and 24. The value for the minutes and
seconds, if present, must be between zero and 59.
If preceded by a minus sign (-), the time zone is
east of the Prime Meridian; otherwise it is west,
which can be indicated by a preceding plus sign
(+). Indicates when to change to and return from
alternative time. The start argument is the date
when the change from standard to alternative time
occurs; end is the date for changing back. If start
and end are not specified, the default is the US
Daylight Saving Time start and end dates. The format
for start and end must be one of the following:
The Julian day n (1 <= n <= 365). Leap days are not
counted. That is, in all years, including leap
years, February 28 is day 59 and March 1 is day 60.
It is impossible to explicitly refer to February
29. The zero-based Julian day (0 <=n <= 365). Leap
days are counted making it possible to refer to
February 29. The dth day (0 <= d <= 6) of week n
of month m of the year (1 <= n <= 5, 1 <= m <= 12).
When n is 5, it refers to the last d day of month m
which may occur in either the fourth or fifth week.
Week 1 is the first week in which the dth day
occurs. Day zero is Sunday. Describes the time
when, in current time, the change to or return from
alternative time occurs. The time parameter has the
same format as offset, except that there can be no
leading minus (-) or plus (+) sign. If time is not
specified, the default is 02:00:00.
As an example, the TZ variable value
EST5EDT4,M4.1.0,M10.5.0 describes the rule defined in 1987
for the Eastern time zone in the US. EST (Eastern Standard
Time) is the designation for standard time, which is 5
hours behind GMT. EDT (Eastern Daylight Time) is the designation
for alternative time, which is 4 hours behind
GMT. EDT starts on the first Sunday in April and ends on
the last Sunday in October. In both cases, since time was
not specified, the changes occur at the default time,
which is 2:00 A.M. Note that the start and end dates did
not need to be specified since they are the defaults.
[Tru64 UNIX] For users of the SVID2 habitat, TZ is
defined by default in the following format:
stdoffset[dst[offset]]
[Tru64 UNIX] For users of the SVID3 habitat, TZ is
defined by default in the following format:
:pathname
See the section TZ Environment Variable for definitions of
the parameters used in these formats.
Functions: ctime(3), ctime_r(3), difftime(3), getdate(3),
getdate_r(3), getenv(3), localtime(3), localtime_r(3),
mktime(3), strftime(3), strptime(3), time(3)
Commands: date(1), zdump(8), zic(8)
Files: tzfile(4)
Standards: standards(5)
timezone(3) | http://nixdoc.net/man-pages/Tru64/man3/tzname.3.html | CC-MAIN-2013-20 | refinedweb | 1,468 | 53.61 |
What’s NPOI you may ask. So here it goes:
NPOI is the .NET version of POI Java project. POI is an open source project which can help you read/write Office 2003/2007 files.
NPOI advantages
a. It's totally free to use
b. Cover most Excel features (cell styles, data formats, formulas and so on)
c. Supports .xls, .xlsx, .docx
d. Designed to be interface-oriented (in NPOI.SS namespace)
e. Supports not only export but also import
f. .NET 2.0 based even for xlsx and docx (but it also supports .NET 4.0)
g. Successful use cases all over the world
h. Great amount of basic and to the point samples
i. Professional service support (even 24*7) directly from NPOI team (not free)
My dear friend Tony Qu from China (the guy behind NPOI development) approached me and asked me to help him share NPOI 2.0 news with the English speakers. I’m always glad to help spread the word about this amazing open source project that has served me in many situations.
The most seen and shared post of this humble blog as of now has almost 9000 shares and was published on 7/02/2009 – oh God that’s exactly 4.5 years ago… its title is Creating Excel spreadsheets .XLS and .XLSX in C#. This huge amount of shares shows that a tool that does what NPOI does is highly demanded in the market. No doubt!
You know: when I wrote that post I had no idea it would be so useful to so many people. My intention with this blog is really to share useful things with the world giving back a bit of what I find/learn/improve from the great minds spread throughout this big planet earth. This is a continuous\infinite process for sure.
OK dude: that’s enough of food for thought. Let me show you what’s going on with NPOI. Here you go…
NPOI 2.0 release
The release is planned for this January. We agreed to publish posts discussing major features/enhancements that’s arriving.
Here they are:
1 - WorkbookFactory can help make HSSF and XSSF transparent for users
2 - Excel 2007 and Word 2007 support
3 - Cell, Row, Sheet copying and Workbook merging
4 - Converting Excel XLS documents to HTML format
5 - isRightToLeft and setRightToLeft in XSSF and HSSF
6 - Diagonal line in cells for both Excel 2003 and Excel 2007
7 - Excel 2007 chart support
8 - New excel functions added in formula calculation
9 - NPOI tag added to files generated with NPOI
10 - XSSFWorkbook implements IEnumerator
Keep an eye on this blog for the next posts.
NPOI source code
NPOI NuGet package | http://www.leniel.net/2014/01/npoi-2.0-major-features-enhancements-series-of-posts-scheduled.html | CC-MAIN-2017-43 | refinedweb | 451 | 73.88 |
Developing Libraries with Cross Platform Tools
This article covers how to write libraries for .NET using cross-platform CLI tools. The CLI provides an efficient and low-level experience that works across any supported OS. You can still build libraries with Visual Studio, and if that is your preferred experience refer to the Visual Studio guide.
Prerequisites
You need the .NET Core SDK and CLI installed on your machine.
For the sections of this document dealing with .NET Framework versions, you need the .NET Framework installed on a Windows machine.
Additionally, if you wish to support older .NET Framework targets, you need to install targeting/developer packs for older framework versions from the .NET target platforms page. Refer to this table:
How to target the .NET Standard
If you're not quite familiar with the .NET Standard, refer to the .NET Standard to learn more.
In that article, there is a table which maps .NET Standard versions to various implementations:
1 The versions listed for .NET Framework apply to .NET Core SDK 2.0 and later versions of the tooling. Older versions used a different mapping for .NET Standard 1.5 and higher.
-.
Here's what this table means for the purposes of creating a library:
The version of the .NET Standard you pick will be a tradeoff between access to the newest APIs and the ability to target more .NET implementations and .NET Standard versions. You control the range of targetable platforms and versions by picking a version of
netstandardX.X (Where
X.X is a version number) and adding it to your project file (
.csproj or
.fsproj).
You have three primary options when targeting the .NET Standard, depending on your needs.
You can use the default version of the .NET Standard supplied by templates -
netstandard1.4- which gives you access to most APIs on .NET Standard while still being compatible with UWP, .NET Framework 4.6.1, and the forthcoming .NET Standard 2.0.
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard1.4</TargetFramework> </PropertyGroup> </Project>
You can use a lower or higher version of the .NET Standard by modifying the value in the
TargetFrameworknode of your project file.
.NET Standard versions are backward compatible. That means that
netstandard1.0libraries run on
netstandard1.1platforms and higher. However, there is no forward compatibility - lower .NET Standard platforms cannot reference higher ones. This means that
netstandard1.0libraries cannot reference libraries targeting
netstandard1.1or higher. Select the Standard version that has the right mix of APIs and platform support for your needs. We recommend
netstandard1.4for now.
If you want to target the .NET Framework versions 4.0 or below, or you wish to use an API available in the .NET Framework but not in the .NET Standard (for example,
System.Drawing), read the following sections and learn how to multitarget.
How to target the .NET Framework
Note
These instructions assume you have the .NET Framework installed on your machine. Refer to the Prerequisites to get dependencies installed.
Keep in mind that some of the .NET Framework versions used here are no longer in support. Refer to the .NET Framework Support Lifecycle Policy FAQ about unsupported versions.
If you want to reach the maximum number of developers and projects, use the .NET Framework 4.0 as your baseline target. To target the .NET Framework, you will need to begin by using the correct Target Framework Moniker (TFM) that corresponds to the .NET Framework version you wish to support.
.NET Framework 2.0 --> net20 .NET Framework 3.0 --> net30 .NET Framework 3.5 --> net35 .NET Framework 4.0 --> net40 .NET Framework 4.5 --> net45 .NET Framework 4.5.1 --> net451 .NET Framework 4.5.2 --> net452 .NET Framework 4.6 --> net46 .NET Framework 4.6.1 --> net461 .NET Framework 4.6.2 --> net462 .NET Framework 4.7 --> net47
You then insert this TFM into the
TargetFramework section of your project file. For example, here's how you would write a library which targets the .NET Framework 4.0:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net40</TargetFramework> </PropertyGroup> </Project>
And that's it! Although this compiled only for the .NET Framework 4, you can use the library on newer versions of the .NET Framework.
How to Multitarget
Note
The following instructions assume you have the .NET Framework installed on your machine. Refer to the Prerequisites section to learn which dependencies you need to install and where to download them from.
You may need to target older versions of the .NET Framework when your project supports both the .NET Framework and .NET Core. In this scenario, if you want to use newer APIs and language constructs for the newer targets, use
#if directives in your code. You also might need to add different packages and dependencies for each platform you're targeting to include the different APIs needed for each case.
For example, let's say you have a library that performs networking operations over HTTP. For .NET Standard and the .NET Framework versions 4.5 or higher, you can use the
HttpClient class from the
System.Net.Http namespace. However, earlier versions of the .NET Framework don't have the
HttpClient class, so you could use the
WebClient class from the
System.Net namespace for those instead.
Your project file could look like this:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard1.4;net40;net45</TargetFrameworks> </PropertyGroup> <!-- Need to conditionally bring in references for the .NET Framework 4.0 target --> <ItemGroup Condition="'$(TargetFramework)' == 'net40'"> <Reference Include="System.Net" /> </ItemGroup> <!-- Need to conditionally bring in references for the .NET Framework 4.5 target --> <ItemGroup Condition="'$(TargetFramework)' == 'net45'"> <Reference Include="System.Net.Http" /> <Reference Include="System.Threading.Tasks" /> </ItemGroup> </Project>
You'll notice three major changes here:
- The
TargetFrameworknode has been replaced by
TargetFrameworks, and three TFMs are expressed inside.
- There is an
<ItemGroup>node for the
net40target pulling in one .NET Framework reference.
- There is an
<ItemGroup>node for the
net45target pulling in two .NET Framework references.
The build system is aware of the following preprocessor symbols used in
#if directives:
Here is an example making use of conditional compilation per-target:
using System; using System.Text.RegularExpressions; #if NET40 // This only compiles for the .NET Framework 4 targets using System.Net; #else // This compiles for all other targets using System.Net.Http; using System.Threading.Tasks; #endif namespace MultitargetLib { public class Library { #if NET40 private readonly WebClient _client = new WebClient(); private readonly object _locker = new object(); #else private readonly HttpClient _client = new HttpClient(); #endif #if NET40 // .NET Framework 4.0 does not have async/await public string GetDotNetCount() { string url = ""; var uri = new Uri(url); string result = ""; // Lock here to provide thread-safety. lock(_locker) { result = _client.DownloadString(uri); } int dotNetCount = Regex.Matches(result, ".NET").Count; return $"Dotnet Foundation mentions .NET {dotNetCount} times!"; } #else // .NET 4.5+ can use async/await! public async Task<string> GetDotNetCountAsync() { string url = ""; // HttpClient is thread-safe, so no need to explicitly lock here var result = await _client.GetStringAsync(url); int dotNetCount = Regex.Matches(result, ".NET").Count; return $"dotnetfoundation.org mentions .NET {dotNetCount} times in its HTML!"; } #endif } }
If you build this project with
dotnet build, you'll notice three directories under the
bin/ folder:
net40/ net45/ netstandard1.4/
Each of these contain the
.dll files for each target.
How to test libraries on .NET Core
It's important to be able to test across platforms. You can use either xUnit or MSTest out of the box. Both are perfectly suitable for unit testing your library on .NET Core. How you set up your solution with test projects will depend on the structure of your solution. The following example assumes that the test and source directories live in the same top-level directory.
Note
This uses some .NET Core CLI commands. See dotnet new and dotnet sln for more information.
Set up your solution. You can do so with the following commands:
mkdir SolutionWithSrcAndTest cd SolutionWithSrcAndTest dotnet new sln dotnet new classlib -o MyProject dotnet new xunit -o MyProject.Test dotnet sln add MyProject/MyProject.csproj dotnet sln add MyProject.Test/MyProject.Test.csproj
This will create projects and link them together in a solution. Your directory for
SolutionWithSrcAndTestshould look like this:
/SolutionWithSrcAndTest |__SolutionWithSrcAndTest.sln |__MyProject/ |__MyProject.Test/
Navigate to the test project's directory and add a reference to
MyProject.Testfrom
MyProject.
cd MyProject.Test dotnet add reference ../MyProject/MyProject.csproj
Restore packages and build projects:
dotnet restore dotnet build
Note
Starting with .NET Core 2.0, Visual Studio Team Services or in build systems that need to explicitly control the time at which the restore occurs.
Verify that xUnit runs by executing the
dotnet testcommand. If you chose to use MSTest, then the MSTest console runner should run instead.
And that's it! You can now test your library across all platforms using command line tools. To continue testing now that you have everything set up, testing your library is very simple:
- Make changes to your library.
- Run tests from the command line, in your test directory, with
dotnet testcommand.
Your code will be automatically rebuilt when you invoke
dotnet test command.
How to use multiple projects
A common need for larger libraries is to place functionality in different projects.
Imagine you wished to build a library which could be consumed in idiomatic C# and F#. That would mean that consumers of your library consume them in ways which are natural to C# or F#. For example, in C# you might consume the library like this:
using AwesomeLibrary.CSharp; public Task DoThings(Data data) { var convertResult = await AwesomeLibrary.ConvertAsync(data); var result = AwesomeLibrary.Process(convertResult); // do something with result }
In F#, it might look like this:
open AwesomeLibrary.FSharp let doWork data = async { let! result = AwesomeLibrary.AsyncConvert data // Uses an F# async function rather than C# async method // do something with result }
Consumption scenarios like this mean that the APIs being accessed have to have a different structure for C# and F#. A common approach to accomplishing this is to factor all of the logic of a library into a core project, with C# and F# projects defining the API layers that call into that core project. The rest of the section will use the following names:
- AwesomeLibrary.Core - A core project which contains all logic for the library
- AwesomeLibrary.CSharp - A project with public APIs intended for consumption in C#
- AwesomeLibrary.FSharp - A project with public APIs intended for consumption in F#
You can run the following commands in your terminal to produce the same structure as this guide:
mkdir AwesomeLibrary && cd AwesomeLibrary dotnet new sln mkdir AwesomeLibrary.Core && cd AwesomeLibrary.Core && dotnet new classlib cd .. mkdir AwesomeLibrary.CSharp && cd AwesomeLibrary.CSharp && dotnet new classlib cd .. mkdir AwesomeLibrary.FSharp && cd AwesomeLibrary.FSharp && dotnet new classlib -lang F# cd .. dotnet sln add AwesomeLibrary.Core/AwesomeLibrary.Core.csproj dotnet sln add AwesomeLibrary.CSharp/AwesomeLibrary.CSharp.csproj dotnet sln add AwesomeLibrary.FSharp/AwesomeLibrary.FSharp.fsproj
This will add the three projects above and a solution file which links them together. Creating the solution file and linking projects will allow you to restore and build projects from a top-level.
Project-to-project referencing
The best way to reference a project is to use the .NET Core CLI to add a project reference. From the AwesomeLibrary.CSharp and AwesomeLibrary.FSharp project directories, you can run the following command:
$ dotnet add reference ../AwesomeLibrary.Core/AwesomeLibrary.Core.csproj
The project files for both AwesomeLibrary.CSharp and AwesomeLibrary.FSharp will now reference AwesomeLibrary.Core as a
ProjectReference target. You can verify this by inspecting the project files and seeing the following in them:
<ItemGroup> <ProjectReference Include="..\AwesomeLibrary.Core\AwesomeLibrary.Core.csproj" /> </ItemGroup>
You can add this section to each project file manually if you prefer not to use the .NET Core CLI.
Structuring a solution
Another important aspect of multi-project solutions is establishing a good overall project structure. You can organize code however you like, and as long as you link each project to your solution file with
dotnet sln add, you will be able to run
dotnet restore and
dotnet build at the solution level. | https://docs.microsoft.com/en-us/dotnet/core/tutorials/libraries | CC-MAIN-2018-30 | refinedweb | 2,016 | 62.44 |
translated strings, and normal case for strings that still need translating.
This code is in the public domain.
"""
import re, sys
import polib # from
import HTMLParser
class)
I've done something similar in the past, but translated all input into "Fāķė Ĕńĝĺĩŝħ Ťėxŧ" (using characters from Latin-1 Supplement and Latin Extended-A). It's still fairly readable, but it has the side-effect of testing that Unicode is being handled correctly, and that combining marks above and below aren't being clipped.
Years ago, at Wang Labs, our suggestion to developers was to create a "pig-latin" translation. English is more compact than most other languages, so the extra letters added to each word by the pig latin suffixes give you an idea of whether your UI will still look reasonable in translation.
@Bradley: very nice. I pondered a few other xform ideas, and this is better than all of mine!
Wow, this is really nice!!
Some copyright and license information would be helpful too.
I guess I didn't think it was long enough to need explicit IP statements, but it never hurts, so here goes: this code is copyright 2010 by Ned Batchelder, and is in the public domain.
IANAL but I think copyright and public domain are mutually exclusive. Perhaps you mean "copyright 2010 by Ned Batchelder, may be used for any purpose without restriction." Or better, "This work is licensed under a Creative Commons Attribution 3.0 Unported License."
@Kent, although YANAL, you make a good point. The code is in the public domain.
Although I am not a lawyer and this is not legal advice, I HAVE spent a good deal of time reading up on copyright law. There is a "flaw" in the US copyright law such that it is extremely difficult to put something in the public domain even if you want to. (That is actually one reason why things like the creative commons licenses are useful.) Basically (and I may have the details of this wrong), for good reasons, the law says you can't give up your copyright without a contract, and for good reasons it says a contract isn't valid unless both parties receive something of value. The combination of these two means your contract to give up ownership of the code may not be valid.
Of course, all this is only meaningful in the imaginary world of legal arguments, not in the real world. Clearly you are trying to say anyone can use it, and I would personally feel confident using it without fear that you would sue me later. But in terms of best practices, it's legally better to use a license than say the words "public domain".
Maybe someday Congress will fix the flaws in our legal system. And I have no idea how any of this applies in any other jurisdiction.
There is a tool doing exactly this with support for several translation formats, including Gettext PO files. It also has quite a few more possibilities. It does the extended Latin version that Bradley mentions, does one for boundaries checking, one for testing right-to-left functionality, and can even imitate the Swedish Chef :-)
Have a look at podebug:
@F.Wolff: very nice! The podebug tool indeed does exactly this, but times 20! Thanks for the pointer.
Like Richard, I used pig-latin for testing translation functionality in an application I used to work on. It worked quite well and was probably the only translation I was qualified to write.
Nice! One little problem with the script is that it doesn't poxxify the "msgid_plural" forms, if any, in your PO file. This seems to work, though it could be shortened:
Add a comment: | https://nedbatchelder.com/blog/201012/faked_translations_poxxpy.html | CC-MAIN-2018-51 | refinedweb | 621 | 71.85 |
This series never got finished, instead, I created some courses that are much better.
When you first start learning React, you’ll inevitably ask yourself “Should I learn Flux?”. You’ll then most likely look to Google for the source of that answer and after a bit of researching softly conclude that, yes you should. However, I wish that wasn’t always the answer. Flux is great. Flux does a really good job at what it’s designed to do. I use Flux. A lot of people use Flux. But you don’t have to use Flux with React. In fact, I would suggest that you don’t even look at Flux until you really understand the pain point that it’s trying to solve. Too many people jump into React then jump straight to Flux because they think they have to and are left disappointed with React because Flux is a bit, complex. Don’t let the complexity of Flux ruin the simplicity of React.
So, a better question than “Should I learn Flux?” is “Should I use Flux for this particular project?” and if yes, then learn it. The entire reasoning behind Flux is making data changes in your app easy to reason about. In its most simple form, Flux removes the burden of having a component manage its own state and moves that data to a central location called a Store where multiple components can now share that data. Then, everything in that Store’s purpose is to, in one way or another, assist in the modification or preservation of the data. The benefit of this is that if the data in the Store changes, you know exactly what triggered the change because the Store is the only place in your app with the ability to modify the data.
Notice how Flux revolves around the fact that your application has data and that data needs to be kept up to date in an effective manner. If your app doesn’t have and or care about dynamic data, Flux might not be the best choice. Flux excels in respect to data management, but will feel unnecessary if you don’t have any data to manage.
So now that you’re aware of the necessity of your app to have data in order for Flux to be beneficial, let’s talk about the flow of a Flux app. Because, again, the whole idea of a Flux app is to make your data changes easy to reason about, Flux embraces a one way data flow architecture. So what we’ll do in this tutorial is we’ll walk through every part of the Flux architecture until we have a solid grasp of each concept.
Above is a Flux diagram I made that I wish existed when I was learning Flux. It won’t make a ton of sense now, but as you read through the different parts of the Flux architecture my hope is that you’ll reference this diagram and it will start clicking for you. If you’ve read any of my tutorials before, you know I’m a huge fan of trying to break things down into their most easy to understand form. With Flux, I can honestly say this was a bit difficult. If something doesn’t make sense, keep reading and then re-read and I’m confident it will eventually click.
Let’s start off with our components. Remember, one of the main points of Flux is to take the storage of the data out of the component and put it in a more central location (Store). Because of that, our components will look exactly the same except, as you probably guessed, we’ll be calling out to our Actions to add data and Stores to fetch data.
For the sake of having code snippets that demonstrate the principles I talk about, let’s pretend we’re building a basic Todo List app. I’ll obviously leave a lot of parts out, but I’ll include the parts that demonstrate the specific Flux principle.
The full source code can be found HERE.
var React = require('react');var AddItem = require('./AddItem');var List = require('./List');var todoStore = require('../stores/todoStore');var todoActions = require('../actions/todoActions');var ListContainer = React.createClass({getInitialState: function(){return {list: todoStore.getList()}},componentDidMount: function(){todoStore.addChangeListener(this._onChange);},componentWillUnmount: function(){todoStore.removeChangeListener(this._onChange);},handleAddItem: function(newItem){todoActions.addItem(newItem);},handleRemoveItem: function(index){todoActions.removeItem(index);},_onChange: function(){this.setState({list: todoStore.getList()})},render: function(){return (<div className="col-sm-6 col-md-offset-3"><div className="col-sm-12"><h3 className="text-center"> Todo List </h3><AddItem add={this.handleAddItem}/><List items={this.state.list} remove={this.handleRemoveItem}/></div></div>)}});module.exports = ListContainer;
Let’s break down this component.
First thing you’ll notice is the list property on the object which is being
returned from
getIntiailState doesn’t have a value of an empty array but its
value is instead whatever is being returned from
todoStore.getList. Remember
the reason for this is because we’re taking the data out of the component and
putting it into the Store. We’ll cover more about the Store side of things later
in this tutorial.
Next, you’ll notice the
componentDidMount and
componentWillUnmount methods.
Each of those are calling methods on the
todoStore which seem to be adding and
removing an event listener. Head back up to the diagram for a second and reread
the “Views/Component” section. Because we’re relying on the Store to house our
data, we’ll need to make sure that whenever the data in the Store changes, our
component knows about that and will update its own state. We accomplish this by
passing the store a method (
_onChange) which will refetch the data from the
store and update the components state. Now, whenever the Store changes its data,
it can invoke the callback function we initially passed it when the component
mounted (
_onChange) which will make sure the component keeps its data up to
date with what’s in the store. The
addChangeListener piece is what’s tying the
store back into the component.
The last thing to notice is that every time a user event occurs, whether it’s
adding a new item to the todo list (handleAddItem) or removing an item from the
list (handleRemoveItem), we’re invoking a method on our todoActions rather than
using
setStat. Again, this is because our main source of truth for our data
is the store, and as the diagram points out, we first need go through our
actions in order to eventually update the data in the store.
Let’s now take a look at our actions, or the second phase of our Flux diagram.
var AppDispatcher = require('../dispatcher/AppDispatcher');var appConstants = require('../constants/appConstants');var todoActions = {addItem: function(item){AppDispatcher.handleAction({actionType: appConstants.ADD_ITEM,data: item});},removeItem: function(index){AppDispatcher.handleAction({actionType: appConstants.REMOVE_ITEM,data: index})}};module.exports = todoActions;
Referring back to the diagram, the Dispatcher is what is going to emit a certain event. Notice the way we keep track of these events is through a constants file. Because we need to emit a specific type of event, and also listen for that exact same type of event, a constants object makes perfect sense.
var appConstants = {ADD_ITEM: "ADD_ITEM",REMOVE_ITEM: "REMOVE_ITEM"};module.exports = appConstants;
Notice literally all this constants object is is a mirrored key value pair. Whose keys/values are whatever the specific event is we’re emitting/listening for.
Back to our actions, since our Dispatcher is the one actually emitting an event, our Actions object can be thought of as essentially just prepping an object before it’s dispatched. Notice in our addItem method the actionType is appConstants.addItem and the data is just the specific item we’re adding. These keys/values will eventually make themselves to our store where we can not only listen for that specific event (addItem) but also grab the data off of that payload once it gets to the store.
Now we’ve arrived at the 3rd part of our diagram, the Dispatcher. You can think of the Dispatcher as the hub of your app. Every time you want to change the data that lives in a store, you must go through the Dispatcher.
var Dispatcher = require('flux').Dispatcher;var AppDispatcher = new Dispatcher();AppDispatcher.handleAction = function(action){this.dispatch({source: 'VIEW_ACTION',action: action});};module.exports = AppDispatcher;
You probably noticed there’s really not much going on here. That’s because,
there really doesn’t need to be much going on. The whole point of the dispatcher
again is to dispatch certain events. There are plenty of libraries that do this,
but the recommended one is the one we’re using in the code above. It also
happens to be the one facebook uses as well. We require the
flux module, then
create a new instance of the
Dispatcher on that module, then set a method on it
that we’ll invoke from any
actions in our app. The reason we’re using
VIEW_ACTION as the source of our dispatch is because you could also be using
SERVER_ACTION if that action was coming from the server. The only other thing is
to pass along the action which is passed in when handleAction is invoked (and
contains the
actionType as well as the
data). What’s interesting about our
Dispatcher is that most people don’t really mention that you’ll use the same
dispatcher in all your stores as well in order to register callbacks which will
be invoked when certain Dispatches are dispatched. It’s a little weird at first,
but you can think of the Dispatcher as kind of a bridge. In the main
Dispatcher.js file is where you set up your
handleAction method which will
dispatch the actual event, but you also need to make it so your stores actually
listen to those events. So what’s interesting, and kind of confusing at first,
is inside your store you’ll require the Dispatcher which you exported from your
main Dispatcher file in order to register some callbacks that will be invoked
whenever the Dispatcher dispatches then hears those certain dispatches. We’ll
see that in the next section on Stores. I realize that got super wordy but stick
with me. The paragraph above will make more sense after reading this next
section.
The store is where the magic happens. You can think of a Store as having four parts.
The actual “model” or data store. What’s great about Flux, is your “model” is just a JavaScript data structure like an object or array. Everything else in the Store will be built around manipulating or getting this data.
var _store = {list: []};
Setter methods. Remember, the whole point of Flux is to make your data changes easy to reason about. These setter methods will be the only interface for manipulating the data of our store (which we made in the first step above).
var addItem = function(item){_store.list.push(item);};var removeItem = function(index){_store.list.splice(index, 1);}
The Store itself, which is really just a collection of getter functions in order to access the data in the first step along with a few emitter/change listener helpers. Another idea of Flux that might throw you at first is Getters vs Setters. Remember, we only want to be able to manipulate the data from our setter functions (which we made in the second step above). However, we want to be able to GET the data whenever we like through our Getter functions defined in this step. To accomplish this, we’ll make the setter functions “private” to our Store file while we’ll export the actual Store (this step, or the collection of Getter methods) so that we can require the Store in other files and invoke those getter methods in order to get the data. In other words, this step is going to be global, while the other steps will be “private”.;},});
A few things to note about the actual code above. Notice, as mentioned, we have
our
getList method which just returns us the list. If you remember back to the
component we built earlier, you’ll notice in
getInitialState we’re invoking
todoStore.getList() and setting the result to the list property on our state.
getInitialState: function(){return {list: todoStore.getList()}}
This
getList method in the Store above is the interface for getting the data
out of the store. We also have the
addChangeListener and
removeChangeListener
methods. Again if you remember back to our component we built earlier, when our
component mounted, we passed in
_.onChange which just used
setState to invoke
todoStore.getList in order to refetch the data.
_onChange: function(){this.setState({list: todoStore.getList()})},componentDidMount: function(){todoStore.addChangeListener(this._onChange);},componentWillUnmount: function(){todoStore.removeChangeListener(this._onChange);}
Well, the cb parameter we’re passing to
addChangeListener and
removeChangeListener is that
_.onChange function. So now, whenever a
CHANGE_EVENT (or “CHANGE”) event is emitted, React will invoke
_.onChange
which will update the state of the component.
The last thing to discuss about the
todoStore itself above is the use of
objectAssign with
EventEmitter. All
objectAssign allows you to do is
extend/combine objects together in order to make “super objects” if you will. By
super objects, I mean objects whose keys/values are a collection of keys/values
from different objects. We pass
objectAssign a target, or an empty object
first. This empty object is what the next two parameters are going to add their
properties to. We then pass it
EventEmitter.prototype. Now our empty object will
get all of the properties that are on the EventEmitter’s prototype object. This
will give our store the ability to do things like
.on and
.emit. The last
argument is another object whose properties will be added to the empty object.
So when everything is complete, the object being returned from
objectAssign is
an object which has all of properties of EventEmitter’s prototype as well as
addChangeListener,
removeChangeListener, and
getList.
We need to use our
Dispatcher to listen for certain events and when we hear those events, invoke the setter functions above (in the second step).;}});
Remember, when the handleAction method on our Dispatcher is invoked, it’s going to dispatch an object which will look like this
{source: ‘VIEW_ACTION’,action: {actionType: ‘SOME_CONSTANT’,data: ‘SOME DATA’}}
So on our Switch statement, we’ll be checking the
actionType in order to know
which action was emitted. Based on that
actionType, we’ll know exactly what
setter function (which we created in step 2 above) to invoke in order to modify
the data. Once we invoke our setter function, we will then emit a change event,
then, because in our
addChangeListener method in our todoStore we set up the
.on event handler, whenever it hears the change event, it will invoke the
callback function which was passed to it which is
_onChange from our original
component.
Here’s the full code for the todoStore.js file.
var AppDispatcher = require('../dispatcher/AppDispatcher');var appConstants = require('../constants/appConstants');var objectAssign = require('react/lib/Object.assign');var EventEmitter = require('events').EventEmitter;var CHANGE_EVENT = 'change';var _store = {list: []};var addItem = function(item){_store.list.push(item);};var removeItem = function(index){_store.list.splice(index, 1);;}});module.exports = todoStore;
Let’s walk step by step through the whole process now.
Our
todoStore is created, creating a place where our data lives, some setter
functions, a
todoStore object with a
getList method a
addChangeListener and
removeChangeListener function, and we register our callbacks with the
Dispatcher.
When our component mounts, we pass
_.onChange to
todoStore.
addChangeListener which makes it so whenever the Store hears the “CHANGE” event, it will run
_.onChange which will refetch the data from the store using
todoStore.getList and update its own state with the data returned from
getList.
A user clicks “Submit” wanting to add a new item to their todo list which invokes a method on the component which we’ll call
handleAddItem.
handleAddItem
runs and invokes the
todoActions.addItem method passing it the new item to add.
The
addItem method on our
todoActions object invokes
AppDispatcher.handleAction passing it an object with the actionType of
appConstants.ADD_ITEM and the data of the original todo item.
When
AppDispatcher.handleAction invokes, it emits
appConstants.ADD_ITEM, because of step 1, the callback we passed to
AppDispatcher.register in our Store is invoked, the switch statement catches the
appConstants.ADD_ITEM conditional and then
addIte is invoked which pushes the new item onto our data in the Store.
todoStore
emits a
CHANGE event then because of step 2,
todoStore hears
that event which invokes the callback function which was passed to it which was
originally
_onChange in our component
_onChange
runs which uses
todoStore.getList in order to update its own
internal state and now we’ve gone full circle.
That process in code will look like this.
1. See Code Above2.componentDidMount: function(){todoStore.addChangeListener(this._onChange);}3.handleAddItem: function(newItem){todoActions.addItem(newItem);}4.AppDispatcher.handleAction = function(action){this.dispatch({source: 'VIEW_ACTION',action: action});};5.case appConstants.ADD_ITEM:addItem(action.data);5.5var addItem = function(item){_store.list.push(item);};6.todoStore.emit(CHANGE_EVENT);break;6.5addChangeListener: function(cb){this.on(CHANGE_EVENT, cb);},7._onChange: function(){this.setState({list: todoStore.getList()})}
Now, that might seem like a rather large and unnecessary process to take. That’s a fair judgement. But remember what Flux is designed to do. It’s not meant for small apps with little data but instead meant to be implemented with large apps with complex and ever changing. | https://ui.dev/react-js-tutorial-pt-3-architecting-react-js-apps-with-flux/ | CC-MAIN-2021-43 | refinedweb | 2,951 | 55.84 |
This app uses System.Speech and System.Speech.Synthesize namespaces. There is nothing too special with these as they have been used in a few apps here at CodeProject and a few other sites. The applications that can be thought of using System.Speech are unimaginable. I came up with this idea from a few apps that are here at CodeProject. I ran one of the apps and my grandchildren were amazed at the computer talking. So I added their names to the program and ran it. They were surprised to hear their names. Their attention spans were as short as this >.<. Now they are not.
System.Speech
System.Speech.Synthesize
System.Speech
This app is a (CLC) Child's Learning Center and there is nothing more valuable than a child or grandchild's education. This app targets the 3 to 5 year old pre-schoolers. Some children might start to read at 2 years of age and others might start at 6 years. If your child is a little bored, stop the learning process for a couple of weeks and TRY again. Remember, children learn at their own pace.
The requirements for the app are: Children, Adobe's PDF Reader, Powerpoint viewer, both installed to their default locations, go to, to get all the PDF and Powerpoint Presentation activity sheets and visual learning tools free. This app was tested on Vista Home Basic w/SP2, .NET 3.5, Visual Studio 2008 Pro w/SP1, 1024X768, and my grandchildren.
There are many Child Learning Applications out there, but this one is Free. It works, and my grandchildren's attention spans have increased 10 fold. They interact with the computer by doing, seeing, and hearing what they have just done. Repeating the same steps, 3 times, helps the child remember.
Putting this app together was a learning process for me. I had to think of what I would like to see as a child, different colors, animal pictures, letters, numbers, pretty fruit, and the computer talking. I am by no means, a designer or a teacher, but I am someone who believes that if something works, don't Fix-It. I didn't believe it at first, this actually works.
First was the Parent-Child interactivity mode. I added a TextBox to hold the child's name. I then added a GroupBox to hold five CheckBoxes and a couple of Buttons to display the different activities. Then I added the activity GroupBoxes with alphabet buttons, number buttons, a few pictureBoxes and a label. Putting this all together starts the learning process.
TextBox
GroupBox
CheckBoxes
Buttons
GroupBoxes
I had a problem when clicking on a checkbox and checking it, then clicking on another checkbox, having it checked and the previous checkbox, unchecked, while displaying the correct groupbox for the current checkbox. Confused??? So was I after I wrote that long-winded sentence, but it makes perfectly good sense to me, now. This turned out to be somewhat simple enough without any overflow exceptions being thrown. I then added two more checkboxes to the Numbers GroupBox, using the same method, I was getting overflow exceptions. After a few trial and error attempts, I came up with these two examples:
Private Sub chkPlus_CheckedChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles chkPlus.CheckedChanged
If chkPlus.Checked Then
lblSign.Text = "+"
chkMinus.Checked = False
Else
lblSign.Text = "-"
chkMinus.Checked = True
End If
End Sub
Private Sub chkMinus_CheckedChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles chkMinus.CheckedChanged
If chkMinus.Checked Then
lblSign.Text = "-"
chkPlus.Checked = False
Else
lblSign.Text = "+"
chkPlus.Checked = True
End If
End Sub
Clicking on one checkbox switches from one checkbox to the other, and visa-versa.
My next problem was with the simple addition (1 + 1 = 2). I haven't been programming that long and when I typed 1 in the first textbox and 1 in the next textbox then added them together, I got 'cannot convert string to Integer'. I just forgot to convert the text numbers to integers. After all the fuss, I came up with this:
Private Sub btnPlus_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnPlus.Click
ansPlus = (CInt(txtNum1.Text) + CInt(txtNum2.Text))
End Sub
Private Sub btnMinus_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnMinus.Click
ansMinus = (CInt(txtNum1.Text) - CInt(txtNum2.Text))
End Sub
Private Sub btnEnter_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnEnter.Click
If chkPlus.Checked Then
If CInt(txtAnswer.Text) = ansPlus Then
strSay = CInt(txtNum1.Text) & " plus " & CInt(txtNum2.Text) & _
" equals " & CInt(txtAnswer.Text)
InitializeSpeaker()
speaker.SpeakAsync(strSay)
MessageBox.Show("Correct :) " & txtName.Text)
Else
MessageBox.Show("Try Again :( " & txtName.Text)
End If
Else
If CInt(txtAnswer.Text) = ansMinus Then
strSay = CInt(txtNum1.Text) & " minus " & CInt(txtNum2.Text) & _
" equals " & CInt(txtAnswer.Text)
InitializeSpeaker()
speaker.SpeakAsync(strSay)
MessageBox.Show("Correct :) " & txtName.Text)
Else
MessageBox.Show("Try Again :( " & txtName.Text)
End If
End If
End Sub
Applying the spelling routine was pretty straight forward. I created 'wordlist.txt' file to hold all my 2 and 3 letter words, I then added a ListBox and made it invisible as it is not used for any type of selection. I added two more buttons, btnNext, btnPrevious to navigate the word list in the Listbox. Here is what I came up with that works fairly well:
ListBox
btnNext
btnPrevious
Listbox
Private Sub LoadListWords()
Try
Dim sr As StreamReader = New StreamReader(wordlistPath)
'sr.ReadBlock(
Do While sr.Peek() >= 0
strWord = sr.ReadLine
Me.lstWords.Items.Add(strWord)
Loop
sr.Close()
sr = Nothing
lstWords.SelectedIndex = 0
wordIndex = 0
Catch ex As Exception
MessageBox.Show("Error : " & ex.Message)
End Try
End Sub
Private Sub btnPrevious_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnPrevious.Click
If wordIndex <= 0 Then Exit Sub
lstWords.SetSelected(wordIndex, False)
wordIndex -= 1
lstWords.SetSelected(wordIndex, True)
lblSpell.Text = lstWords.SelectedItem.ToString()
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnNext.Click
If wordIndex >= lstWords.Items.Count - 1 Then Exit Sub
lstWords.SetSelected(wordIndex, False)
wordIndex += 1
lstWords.SetSelected(wordIndex, True)
lblSpell.Text = lstWords.SelectedItem.ToString()
End Sub
Private Sub btnSPClear_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSPClear.Click
strSay = ""
txtSpell.Text = ""
End Sub
Private Sub btnSPSay_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSPSay.Click
InitializeSpeaker()
speaker.SpeakAsync(strSay)
strGood = strCorrect & txtName.Text
If strSay = txtSpell.Text Then
speaker.SpeakAsync(strGood)
Else
' Do Nothing
End If
End Sub
After I put everything together and got it working correctly, then came the testing. I started with my oldest granddaughter, who is 4 years old and pretty much set in her ways already. To my amazement, she took right to it. Now, when she comes over, this is the first thing she wants to do. She already knew how to sing the alphabet song so I started teaching her the letters of the alphabet with the A is For... part of the program. Next is writing the letters. You can download all child activities from. They are free and well worth it.
A is. | http://www.codeproject.com/script/Articles/View.aspx?aid=37945 | CC-MAIN-2015-18 | refinedweb | 1,211 | 62.54 |
Point -> Vector to a point
Hello everyone,
If i have point in 3D
A=point3d((4,3,2),size=10,color='red',opacity=.5)
How to create a vector from the origin to the point. I know i could define the vector. But I would rather have a point, for plotting reasons
And i would like to plot the Point and the Vector, with automatic labeling of the coordinates.
I have managed to do this like:
from sage.plot.plot3d.shapes2 import frame3d F=frame3d([0,0,0],vector([10,10,10]),color='red') A=points((4,3,2),size=10,color='red',opacity=.5) B=point([(4,3,8)],size=10,color='red',opacity=.5) t = var('t') p = vector([4,3,2]) q = vector([0,0,0]) vec=parametric_plot3d(p*t+q, (t,0,1)) #vectB=vector(B.xdata[1],B.ydata[1],B.zdata[1]) e=0.2 eps=vector([4+e,3+e,2+e]) T_A = text3d('A',eps) #T_B = text3d('B',B) F+A+T_A+B+vec
Is there any better, way to do it?
Here is the file:... | https://ask.sagemath.org/question/46034/point-vector-to-a-point/?answer=46038 | CC-MAIN-2019-26 | refinedweb | 184 | 51.65 |
Using AI-based Object Detection For Finding Elements
It has been possible for some time to use AI to find elements in Appium, via the collaboration between Test.ai and the Appium team. We work together to maintain the test-ai-classifier project, and in this edition of Appium Pro we'll take a look at an advanced element finding mode available in v3 of the plugin.
A tale of two modes
The default mode for the plugin is what I call "element lookup" mode. Let's say we're trying to find an icon that looks like a clock on the screen. The way this mode works is that Appium finds every leaf-node element in the view, generates an image of how it appears on screen, and then checks to see whether that image looks like a clock. If so, then the plugin will remember the element that was associated with that image, and return it as the result of the call to
findElement.
This mode works great for finding many icons, and is pretty speedy on top of that. However, it can run into some big problems! Let's say we're working with the Files app on iOS:
Now let's say we want to find and tap on the "Recents" button at the bottom of the screen. There's an icon that looks like a clock, so we might be tempted to try and find the element using that label:
driver.findElement(MobileBy.custom("ai:clock")).click();
This might work depending on the confidence level set, but it will probably fail. Why would it fail? The issue is that, on iOS especially, the clock icon is not its own element! It's grouped together with the accompanying text into one element, like this:
When a screenshot is taken of this element, and it's fed into the classifier model, the arbitrary text that's included as part of the image will potentially confuse the model and lead to a bad result.
Object detection mode
Version 3.0 of the classifier plugin introduced a second element finding mode to deal with this kind of problem. Because there are now two modes, we need a way to tell the plugin which one we want to use. We do that with the
testaiFindMode capability, which can take two values:
element_lookup(the default)
object_detection
What is object detection, and how does it help? Object detection is a feature of many image-based machine learning models, which aims to take an input image and generate as its output a list of regions within that image that count as distinct objects. The image of birds with boxes around them up top is an example of what an object detection algorithm or machine learning model can achieve. Carving up the world into separate objects is something our human brains do quite naturally, but it's a fairly complex thing to figure out how to train a computer to do it!
Once objects have been detected in an image, they can optionally be classified. The object detection mode of the plugin does exactly this: it takes a screenshot of the entire screen, runs this entire screenshot through an object detection model, and then cuts up screen regions based on objects detected by the model. Those cut-up images (hopefully representing meaningful objects) are then sent through the same classifier as in element lookup mode, so we can see if any of them match the type of icon that we're looking for.
The main advantage of object detection mode is that the plugin will look at the screen the way a human would--if you ask it to find a clock, it won't matter if there's a unique 'clock' element all by itself somewhere on the screen or not. This is also the main disadvantage, because when using this mode, we are not finding actual elements. We're just finding locations on the screen where we believe an element to be, i.e., image elements. This is totally fine if we just want to tap something, but if we're trying to find an input box or other type of control to work with using something like
sendKeys, we're out of luck.
Example
By way of example, I've written up a simple test case that attempts to tap on the "Recents" button in the Files app on iOS, using object detection. It's pretty slow (the object detection model takes about 30 seconds to run on my machine), so it's really only useful in situations where absolutely nothing else works at this point! I'm very grateful to Test.ai for contributing the object detection model which is downloaded in v3 of the plugin.
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.Setting;
import io.appium.java_client.ios.IOSDriver;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;.WebDriverWait;
public class Edition092_AI_Object_Detection {
private String BUNDLE_ID = "com.apple.DocumentsApp";
private IOSDriver driver;
private WebDriverWait wait;
private By recents = MobileBy.custom("ai:clock");
private By browse = MobileBy.AccessibilityId("Browse");
private By noRecents = MobileBy.AccessibilityId("No Recents");
public void setUp() throws IOException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("platformName", "iOS");
caps.setCapability("automationName", "XCUITest");
caps.setCapability("platformVersion", "11.4");
caps.setCapability("deviceName", "iPhone 8"););
driver = new IOSDriver<MobileElement>(new URL(""), caps);
wait = new WebDriverWait(driver, 10);
}
public void tearDown() {
try {
driver.quit();
} catch (Exception ign) {}
}
public void testFindElementUsingAI() {
driver.setSetting(Setting.CHECK_IMAGE_ELEMENT_STALENESS, false);
// click the "Browse" button to navigate away from Recents
wait.until(ExpectedConditions.presenceOfElementLocated(browse)).click();
// now find and click the recents button by the fact that it looks like a clock
driver.findElement(recents).click();
// prove that the click was successful by locating the 'No Recents' text
wait.until(ExpectedConditions.presenceOfElementLocated(noRecents));
}
}
(Of course, you can also check out the sample code on GitHub) | https://appiumpro.com/editions/92 | CC-MAIN-2019-47 | refinedweb | 985 | 54.12 |
This is a C Program to find GCD and LCM of given two numbers. GCD is calculated using Euclidean Algorithm.
Here is source code of the C Program to Find the GCD and LCM of n Numbers. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int gcd(int x, int y) {
int r = 0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while (a % b != 0) {
r = a % b;
a = b;
b = r;
}
return r;
}
int lcm(int x, int y) {
int a;
a = (x > y) ? x : y; // a is greater number
while (1) {
if (a % x == 0 && a % y == 0)
return a;
++a;
}
}
int main(int argc, char **argv) {
printf("Enter the two numbers: ");
int x, y;
scanf("%d", &x);
scanf("%d", &y);
printf("The GCD of two numbers is: %d", gcd(x, y));
printf("The LCM of two numbers is: %d", lcm(x, y));
return 0;
}
Output:
$ gcc GCDLCM.c $ ./a.out Enter the two numbers: 12 15 The GCD of two numbers is: 3 The LCM of two numbers is: 60
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms. | https://www.sanfoundry.com/c-program-find-gcd-lcm-n-numbers/ | CC-MAIN-2018-13 | refinedweb | 231 | 81.22 |
You're not restricted to drawing an image at its natural width and
height. The following variation on the
paint() method
let's you specify the width and height with which the image will be
drawn:
public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver io)
Here
width and
height are the width and
height at which the image will be drawn in pixels. All other
arguments are the same as before.
Here's the code that produced it:
import java.awt.*; import java.applet.Applet; public class FillWithImage extends Applet { private Image picture; public void init() { String filename = this.getParameter("imagefile"); if (filename != null) { this.picture = this.getImage(this.getDocumentBase(), filename); } } public void paint (Graphics g) { if (this.picture != null) { g.drawImage(this.picture, 0, 0, this.getSize().height, this.getSize().width, this); } else { g.drawString("Missing imagefile PARAM element in HTML page", 10, 10); } } } | http://www.cafeaulait.org/course/week9/16.html | CC-MAIN-2019-09 | refinedweb | 151 | 50.02 |
Crypto Portfolio Optimization Part 3: Numerical Optimization
In this article, we are going to use numerical optimization methods to perform crypto portfolio optimization. Pareto optimization for crypto portfolio optimization. Therefore, we created a huge amount of different portfolios to find the efficient frontier of non-dominated portfolios. Furthermore, this is an expensive process regarding the computational costs.
In this article, we want to determine the portfolio with the minimum volatility or maximum Sharpe ratio without using Pareto optimization. Here, we are going to use numerical optimization to cut down the computational costs and therefore the demanded time.
Numerical Optimization
Mathematical optimization methods are used to find the “best” results (minimum or maximum) of an objective function within a defined domain. Here we use numerical methods to solve these mathematical problems.
In the following I want to state our optimization problem in mathematical terms. The standard deviation
needs to be minimized by changing the weights
of the assets. Furthermore, we have the constraint, that the sum of the weight is equal to 1 (100 %) and every weight needs to be between 0 and 1 (0 – 100 %).
In Python we are going to use the Scipy library and in detail the optimization routines. Therefore, the Sequential Least Squares Programming (SSLSQP) method is used which is based on the Sequential Quadratic Programming (SQP) method.
Sharpe ratio
This time we are going to use another indicator called the Sharpe ratio. The Sharpe ratio is an indicator that calculates the risk adjusted return. It is calculated from the average return, risk-free return and the standard deviation of the return (volatility). While the Sortino ratio is just considering negative volatility, the Sharpe ratio is considering positive and negative volatility.
Using these indicators, we can try to examine the performance of an investment. Additionally, we can compare different portfolios with different asset allocations relatively to each other.
Here we assume, that the risk free rate is 0 %. This means there is no such thing as a risk free rate in the crypto space.
Assumptions for the Portfolio Simulation
- The simulations are conducted on the 09.09.2018.
- In the following we consider the exchange Binance.
- We consider all prices in BTC.
- The example portfolios consist of: XMR, VET, OMG, NEO. (For details have a look at CMC).
- When using Pareto optimization we simulate 1000000 portfolios.
Python
You can view and download the entire Python code in this Github repository.
Results Pareto optimization
First, let us have a look at the 1000000 portfolios and the pareto frontier (Using the method from this article). This massive amount of samples is taken, to map the parameter space as good as possible. Furthermore, the smoothness of the red line is an indicator for the right amount of samples.
The green circle marks the portfolio with a globally minimal volatility of 24.91 %, return of 7.34 % and Sharpe ratio of 0.295.
While the red circle the one with globally maximum Sharpe ratio of 0.731, return of 26.23 % and a volatility of 35.88 %.
This leads is to the portfolio allocations of all portfolios on the pareto frontier. This means, by mixing in VET the return increases, but the same time the volatility increases. But this can look very different in a different timeframe or in the future.
Results numerical optimization
Now, let us apply mathematical optimization and compare the results to the Pareto simulation.
First, let us have a look at the portfolio with the minimal volatility. It returns a portfolio of XMR: 86.88 %, VET: 0 %, OMG: 13.11 %, NEO: 0 %, which leads to an return of 7.18 % and a volatility of 24.91 %.
Furthermore, the result of the maximum Sharpe ratio. It returns a portfolio of XMR: 52.09 %, VET: 47.91 %, OMG: 0 %, NEO: 0 %, which leads to an return of 25.88 % and a volatility of 35.34 %.
Conclusion
- You can use numerical optimization for crypto portfolio optimization.
- Sometimes you do not want the entire Pareto frontier but just one specific portfolio e. g. min. volatility. Therefore, you can use numerical optimization.
- The magnitude of the Pareto optimization results can be confirmed by numerical optimization methods.
- The difference in numerical- and Pareto optimization can be based on the numerical tolerance of the optimizer. Furthermore, maybe not all possible portfolios are sampled
- The final goal is to maximize return and minimize volatility.
- You can use the Sharpe ratio to compare portfolios relative to each other.
- Be careful, the results depend strongly on the input timeframe.
- Legthening the timeframe lowers usually the volatility.
- Past performance does not indicate future results.
What do you think?
I’d like to hear what you think about this post.
Let me know by leaving a comment below and don’t forget to subscribe to this blog! | https://numex-blog.com/crypto-portfolio-optimization-part-3-numerical-optimization/ | CC-MAIN-2019-13 | refinedweb | 798 | 50.63 |
We conquer technique, its all done sequentially.
Come Java 8, there is a new API introduced for sorting which is Arrays#parallelSort. This is does the sorting in parallel. Interesting right! Lets see how it does…
Arrays#parallelSort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool. This is called eating your own dog food. Fork/Join implements a work stealing algorithm where in a idle thread can steal tasks queued up in another thread.
An overview of Arrays#parallelSort:
The method uses a threshold value and any array of size lesser than the threshold value is sorted using the Arrays#sort() API (i.e sequential sorting). And the threshold is calculated considering the parallelism of the machine, size of the array and is calculated as:
private static final int getSplitThreshold(int n) { int p = ForkJoinPool.getCommonPoolParallelism(); int t = (p > 1) ? (1 + n / (p << 3)) : n; return t < MIN_ARRAY_SORT_GRAN ? MIN_ARRAY_SORT_GRAN : t; }
Once its decided whether to sort the array in parallel or in serial, its now to decide how to divide the array in to multiple parts and then assign each part to a Fork/Join task which will take care of sorting it and then another Fork/Join task which will take care of merging the sorted arrays. The implementation in JDK 8 uses this approach:
– Divide the array into 4 parts.
– Sort the first two parts and then merge them.
– Sort the next two parts and then merge them.
And the above steps are repeated recursively with each part until the size of the part to sort is not lesser than the threshold value calculated above.
Some interesting results:
I tried to compare the time taken by the Arrays#sort and Arrays#parallelSort on a machine with 4 CPUs. The program which I used for this comparison is:
public class ArraysParallelDemo { public static void main(String[] args) throws FileNotFoundException { List<Double> arraySource = new ArrayList<>(); Scanner reader = new Scanner(ClassLoader. getSystemResourceAsStream("java8demo/large_array_input")); while(reader.hasNext()){ String line = reader.nextLine(); String[] strNums = line.split(","); for ( String strN : strNums){ arraySource.add(Double.parseDouble(strN)); } } System.out.println(arraySource.size()); Double [] myArray = new Double[1]; myArray = arraySource.toArray(myArray); long startTime = System.currentTimeMillis(); Arrays.sort(myArray); long endTime = System.currentTimeMillis(); System.out.println("Time take in serial: "+ (endTime-startTime)/1000.0); Double [] myArray2 = new Double[1]; myArray2 = arraySource.toArray(myArray); startTime = System.currentTimeMillis(); Arrays.parallelSort(myArray2); endTime = System.currentTimeMillis(); System.out.println("Time take in parallel: "+ (endTime-startTime)/1000.0); } }
And the time taken by each of the APIs against arrays of double values of different sizes is shown below:
There is a similar implementation for Lists as well and lot of the operations on Lists have a parallel equivalent.
5 thoughts on “Arrays.sort versus Arrays.parallelSort”
Salam Alykom,
I really did a similar test and got (disappointedly) the opposite results.
My data was generated intentionally with opoosite order from it should be ordered.
Please see:
Actually after repeated the test many time and do some code cleans, It seems to me your tests actually same as my own, **EXCEPT**, that when I run an array of size 10,000,000 the parallel version is performs very badly (2x slower).
I guess the extra time may be due to the fact that merging and splitting of objects i.e Employee objects is taking time. Can you try with simple integers? In the post above I used Integers. May be I should try with objects as well and see how it performs. | http://blog.sanaulla.info/2013/04/08/arrays-sort-versus-arrays-parallelsort/ | CC-MAIN-2016-07 | refinedweb | 593 | 57.98 |
jGuru Forums
Posted By:
Miguel_Barral
Posted On:
Friday, February 22, 2008 06:49 AM
Hi!, i'm new in this group, and let's see if some of you could help me, ;)
I'm developing a plugin for eclipse, and i need webbrowser support, the part of launch an external application its done, but i want to improve my internal launcher, the internal launcher that i get is something like this...
but the other day, i opened a .html file, and eclipse open it, in a different internal browser...something like this
and this is what im looking for, this kind of browser, i mean, with the navigation bar integrate, the back, forward and stop button, and not the other internal browser, that dont allow me to change urls...
i use
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
but maybe i have to see in another API, or something, to find how to get a workbench like that, or maybe a dont use the correct methods...i dont know, if someone could tell me how to launch a browser like that, it would be grateful
thanks!!! | http://www.jguru.com/forums/view.jsp?EID=1357017 | CC-MAIN-2015-06 | refinedweb | 191 | 68.4 |
Preparing Program Sources
For the programmer, changes to source code fall into two categories. First, you have to make the localization functions known to all modules needing message translation. Second, you should identify, adjust and mark all constant strings in your program needing translation.
Importing
At the top of modules that have strings to be translated, have the following import:
from SCons.i18n import _
Preparing Strings
Before strings can be marked for translations, they sometimes need to be adjusted. Usually preparing a string for translation is done right before marking it, during the marking phase which is described in the next sections. What you have to keep in mind while doing that is the following.
- Decent English style.
- Entire sentences.
- Split at paragraphs.
- Use format strings instead of string concatenation.
- Avoid unusual markup and unusual control characters..
rw = "write" if rw else "read" print "File %s is %s protected" % (filename, rw)
Most translators will not look at the source and will thus only see the string "File %s is %s protected", which is unintelligible. Change this to
if rw: print "File %s is write protected" % filename else: print
print "Locale charset \"%s\" is different from\n" % lcharset print ):
print "Locale charset \"%s\" is different from\n\ input file charset \"%s\".\n" % (lcharset, fcharset)
You may now ask: how about two or more adjacent sentences? Like in this case:
file.write("Apollo 13 scenario: Stack overflow handling failed.") file.write( py.
Hardcoded string concatenation is sometimes used to construct English strings:
msg = "Replace " + object1 + " with " + object2 + "?"
In order to present to the translator only entire sentences, and also because in some languages the translator might want to swap the order of object1 and object2, it is necessary to change this to use a format string:
print "Replace %{object1}s with %{objects2}s?" % {"object1":object1, "object.
Mark Keywords
All strings requiring translation should be marked in the source code. Marking is done in such a way that each translatable string appears to be the sole argument of some function. There are only a few such possible functions meant for translation, and their names are said to be marking keywords. The marking is attached to strings themselves, rather than to what we do with them. pygettext at properly extracting all translatable strings when it scans a set of program sources and produces PO file templates.
The canonical keyword for marking translatable strings is ‘_’. Use ‘_’ (a simple underline) as a keyword, and write ‘_(, This isn't offered officially.
The marking keywords ‘_’ take the translatable string as sole argument.
Note also that long strings can be split across lines, into multiple adjacent string tokens. Automatic string concatenation is performed at compile time; py.
Marking
String expansion and translations
_ method wraps the Python module gettext.gettext.
You can use it like this:
title = _("Title")
In cases where there is more than one variable, this allows translators to reorder the variables.
Also, pass the expansion dict into gettext call. If there's a variable expansion error, then module will fall back to the English string. This prevents bad translations from preventing users from using SCons.
BAD:
title = _("Delete file %(filename)s?" % {"filename": self.filename}) title = _("Delete %(count)s file %(filename)s?" % {"count": count, "filename": self.filename})
BAD because it expands the variables before calling gettext:
GOOD:
title = _("Delete file %(filename)s?") % {"filename": self.filename}
--
BAD:
title = _("Delete file %s?") % self.filename
BAD because it uses %s instead of something like %(filename)s and it doesn't pass in the expansion dict into gettext.
Long strings and translations
Long strings (description of things, ...) should be formatted like this:
description = _( "This is a really long string that is formatted using explicit " "whitespace and explicit string delimiters. It avoids whitespace " "problems that can't be seen (extra spaces, carriage returns, ... " "without causing parsing problems.\n" "\n" "You can do multiple paragraphs as well." )
If you need to expand variables in the long string, use the Python string formatting syntax and a dict like this:
description = _( "This is a long string that you find in %(shortappname)s that " "is translated. Using Python string formatting syntax like this " "makes it easier for translators to understand what values are " "substituted in. This paragraph has %(count)d two values.") % {"count": 2, "shortappname": "Miro"}
Special way you can handle this situation:
animals = [N_('mollusk'), N_('albatross'), N_('rat'), N_('penguin'), N_('python'), ] # ... for a in animals: print _(a)
References | http://www.scons.org/wiki/i18n/DeveloperGuide | CC-MAIN-2014-49 | refinedweb | 748 | 65.22 |
The MainWindow Class
The MainWindow class is responsible for displaying the main window and also functions as the controller. In a larger system I would probably split it into multiple files and maybe use some application framework, but in such a small utility I felt okay with just managing everything in a single class. The UI is defined declaratively using XAML in MainWindow.xaml and the controller code is in the code-behind class MainWindow.xaml.cs.
Let's start with the UI. The root element is naturally the <Window>. It contains the usual XML namespaces for XAML and the local namespace for the MP3DurationCalculator. It also contains the title of the window and its initial dimensions. There is also a <Window.Resources> sub-element that contains resources that can be shared by all elements in the window. In this case it's the DurationConverter class. I'll talk more about it later. Here is the XAML for <Window> element:
<Window x: <Window.Resources> <local:DurationConverter x:</local:DurationConverter> </Window.Resources> ... </Window>
The Window element corresponds to the WPF Window class, which is a content container. That means it can hold just one item. That sounds pretty limited, but in practice this single item can be a layout container that itself can hold many items. This is how WPF layout works. You nest containers within containers to get the exact desired layout. The most common and flexible layout container is the grid. WPF Layout is a big topic that warrants its own article (or more). In this article, I try to get away with the minimal amount of explanations necessary to understand the layout of the MP3 Duration Converter. The grid element contains two elements: a media element and a dock panel. The media element is not displayed actually because we use it only to play audio. The dock panel contains the rest of the UI. Here is a collapsed view of the grid:
<Grid> <MediaElement Height="0" Width="0" Name="mediaElement" LoadedBehavior="Manual" /> <DockPanel LastChildFill="True"> ... </DockPanel> </Grid>
The dock panel is another layout container, which contains three stripes arranged vertically. The top stripe contains a browse button for selecting a folder and a text box to display the selected folder name (see Figure 3).
The middle stripe contains a list view that displays the MP3 files in the selected folder (see Figure 4).
The bottom stripe contains a couple of buttons for selecting all or none of the files and a text box to display the total duration of the selected songs (see Figure 5).
The top stripe is a dock panel that has several attributes. The DockPanel.Dock attribute is actually an attached attribute and it applies to outer dock panel (the one that contains all three stripes). It has the value Top, which means that the top strip will be docked to the top part of outer dock panel. The height is defined to be 30 and the vertical alignment is set to Stretch, which means that the top stripe will stretch to fit the entire width of the outer dock panel. The LastChildFill attribute is set to True, which means that that last child laid out will fill the remaining area. The top stripe contains two controls a button and a text box. Both has attached DockPanel.Dock properties that apply to the top stripe itself. The button is docked to the left and the text box is docked to the right. In addition, since the top stripe has a LastChildFill ="True" the text box will stretch to fill the remaining area of the top stripe after the button is laid out. The margin attribute of the button and text box ensures that there will be some spacing between them, so they are not squished together. The button has an event handler called Click that calls the btnSelectDir_Click method when the button is clicked. This method is defined in the code-behind class. Here is XAML for the top stripe:
<DockPanel DockPanel. <Button DockPanel.Browse...</Button> <TextBox Height="22" Name="tbTargetFolder" MinWidth="258" Margin="3" TextChanged="tbTargetFolder_TextChanged"></TextBox> </DockPanel>
The second stripe is actually the bottom stripe and not the middle stripe. The reason for this supposed inconsistency is that I want the middle stripe to fill the remaining area of the outer stripe after the top and bottom have been laid out (according to the LastChildFill attribute), so it must be laid out last. I actually find it a little disorienting. I would prefer if you could simply set one of the DockPanel.Dock of one of the children to Fill instead of making sure it appears last in the XAML file. Anyway, that's the the choice the WPF designers made, so the second stripe is the bottom stripe. It is very similar to the top stripe. It contains two buttons for selecting all files or unseelcting all files and two text boxes. The total text box contains the total duration of all the selected files and the status text box shows various status messages. Named elements like total and status can be accessed using their name in the code-behind class. The text of the "total" text box is data bound to the total.Text property of the MainWindow object. More on that later. Here is the XAML for the bottom stripe:
<DockPanel DockPanel. <Button DockPanel.Select All</Button> <Button DockPanel.Unselect All</Button> <TextBox DockPanel.</TextBox> <TextBox Height="22" Name="status" MinWidth="100" Margin="3" /> </DockPanel>
The middle stripe is a list view. It has no DockPanel.Dock attached property because it is the last child and thus just fills the area left between the top stripe and the bottom stripe. When the Window is resized the top and bottom stripe keep their fixed height and the list view is resize to accommodate the new height of the window. The list view has a name ("files") because it is accessed programmatically from the MainWindow class. It also has an event handler for the SelectionChanged event. The list view also has a view property, which is a grid view in this case (the list view supports several view types including custom views). The grid view has two columns, which are bound to the Name and Duration properties of its item object. The items that populate the list must be object that have a Name and Duration properties. The Duration property is converted using the DurationConverter to a more display-friendly format. Here is the XAML for the list view:
<ListView MinHeight="223" Name="files" MinWidth="355" Background="White" SelectionChanged="files_SelectionChanged"> <ListView.View> <GridView> <GridView.Columns> <GridViewColumn Header="Filename" DisplayMemberBinding="{Binding Path=Name}" Width="Auto" /> <GridViewColumn Header="Duration" DisplayMemberBinding="{Binding Path=Duration, Converter={StaticResource DurationConverter}}" Width="Auto" /> </GridView.Columns> </GridView> </ListView.View> </ListView>
Let's move on to the MainWindow code-behind class. This class oversees the following actions: browse for a new folder that contains MP3 files, collect track info about every MP3 file, select files from the current folder, calculate and display the total duration of all the selected files.
The state the class works with the following member variables:
_folderBrowserDialog . This is a System.Windows.Forms component used to display a dialog for browsing the file system and selecting a folder. WPF doesn't have its own component, but using the Windows.Forms component is just as easy.
_trackDurations. This is an instance of our very own TrackDurations class described earlier
_results. This is an observable collection of TrackInfo objects received from the TrackDurations class whenever the selection of MP3 files is changed.
_fileCount. Just an integer that says how many files are in the current selected directory.
_maxLength. Just an integer that measures the length of the longest track name. It is used to properly resize the list view columns to make sure track names are not truncated.
FolderBrowserDialog _folderBrowserDialog; TrackDurations _trackDurations; ObservableCollection<TrackInfo> _results; int _fileCount = 0; double _maxLength = 0;
In addition to these member variables defined in code the MainWindow class also has additional member variables, which are all the named elements in the XAMNL file like the files list view, the total and status text boxes.
The constructor calls the mandatory InitializeComponent() method that reads the XAML and builds all the UI and then instantiates the folder browser dialog and initializes its properties so it starts browsing from the Downloads directory (folder) under the current user's desktop directory. It also instantiates _results to an empty collection of TrackInfo objects. The most important action is binding the 'files' list view to _results object by assigning _results to files.ItemsSource. This ensures that the files list view will always display the contents of the _results object.
public MainWindow() { InitializeComponent(); _folderBrowserDialog = new FolderBrowserDialog(); _folderBrowserDialog.Description = "Select the directory that containd the MP3 files."; // Do not allow the user to create new files via the FolderBrowserDialog. _folderBrowserDialog.ShowNewFolderButton = false; _folderBrowserDialog.RootFolder = Environment.SpecialFolder.DesktopDirectory; var dt = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); var start = System.IO.Path.Combine(dt, "Downloads"); _folderBrowserDialog.SelectedPath = start; _results = new ObservableCollection<TrackInfo>(); files.ItemsSource = _results; }
The action is usually triggered by selecting a folder to browse. When you click the 'Browse...' button the BrowseFolderDialog pops up and lets you select a target directory. If the user selected a folder and clicked 'OK' the text of the tbTargetFolder text box is set to the selected path. If the user clicked 'Cancel' nothing happens.
void btnSelectDir_Click(object sender, RoutedEventArgs e) { DialogResult r = _folderBrowserDialog.ShowDialog(); if (r == System.Windows.Forms.DialogResult.OK) { tbTargetFolder.Text = this._folderBrowserDialog.SelectedPath; } }
Another way to initiate the action is to directly type a folder path into the tbTargetFolder text box. In both cases the TextChanged event of the text box will fire and corresponding event handler will be called. It will check if the text constitutes a valid folder path and if so calls the collectTrackInfo() method.
private void tbTargetFolder_TextChanged(object sender, TextChangedEventArgs e) { if (Directory.Exists(tbTargetFolder.Text)) collectTrackInfo(tbTargetFolder.Text); }
The collectTrackInfo() method is pretty central so I'll explain it in detail. First of all, it disables the browse button and the target folder text box to ensure that the user doesn't try to go to a different folder while the collection is in progress. This prevents a whole class of race condition and synchronization issues.
void collectTrackInfo(string targetFolder) { btnSelectDir.IsEnabled = false; tbTargetFolder.IsEnabled = false;
The next part is getting all the MP3 files in the target folder. I used a LINQ expression that reads almost like English: "From the files in the target folder select all the files whose extension is ".mp3":
var mp3_files = from f in Directory.GetFiles(targetFolder) where System.IO.Path.GetExtension(f) == ".mp3" select f;
The collection of mp3 files is returned in the reverse order for some reason, so I reverse them back.
mp3_files = mp3_files.Reverse();
Now, the _fileCount member variable is updated and the _results collection is cleared:
_fileCount = mp3_files.Count(); _results.Clear();
If _fileCount is 0 it means no mp3 files were found and there is no need to collect any track information. The status text box is updated and the browse button and the target folder text box are enabled.
if (_fileCount == 0) { status.Text = "No MP3 files in this folder."; btnSelectDir.IsEnabled = true; tbTargetFolder.IsEnabled = true; }
If _fileCount is greater than 0, then a new instance of _trackDurations is created and receives the media element, the collection of mp3 files in the target folder and the onTrackInfo() callback.
else _trackDurations = new TrackDurations(mediaElement, mp3_files, onTrackInfo);
The onTrackInfo() callback is called by TrackDurations every time the information about one of the tracks is collected and once more in the end (with a null TrackInfo). If ti (the TrackInfo object) is null it means we are done with the current directory. The _maxLength variable is reset to 0, the _trackDurations object is disposed of, the status text box displays "Ready." and the selection controls are enabled again.
void onTrackInfo(TrackInfo ti) { if (ti == null) { _maxLength = 0; _trackDurations.Dispose(); status.Text = "Ready."; btnSelectDir.IsEnabled = true; tbTargetFolder.IsEnabled = true; }
If ti is not null it means a new TrackInfo object was received asynchronously. First of all the TrackInfo object is added to the _results collection. As you recall (or not) the _results collection is data-bound to the list view, so just adding it to _results make the new track info show up in the list view.
else { _results.Add(ti);
The next step is to make sure the new filename fits in the first list view column. This is a little cumbersome and involves first creating a FormattedText object with the proper font of the list view and then checking if the size of this formatted text object is greater than the current _maxWidth. If it is greater than it becomes the new _maxWidth and the width of first column of the list view is set to the new _maxWidth.
// Make sure the new filename fits in the column var ft = new FormattedText( ti.Name, CultureInfo.GetCultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight, new Typeface(files.FontFamily, files.FontStyle, files.FontWeight, files.FontStretch), files.FontSize, Brushes.Black); if (ft.Width > _maxLength) { _maxLength = ft.Width; var gv = (GridView)files.View; var gvc = gv.Columns[0]; var curWidth = gvc.Width; // Reset to a specific width before auto-sizing gvc.Width = _maxLength; // This causes auto-sizing gvc.Width = Double.NaN; }
The last part of the onTrackInfo() method is updating the status line with current count of track info object out of the total number of MP3 files.
// Update the status line var st = String.Format("Collecting track info {0}/{1} ...", _results.Count, _fileCount); status.Text = st; } }
After all the information has been collected the user may select files in the list view using the standard Windows selection conventions (click/space to select, ctrl+click/space to toggle selection and shift+click/space to extend selection). Whenever the selected files change the SelectionChanged event is fired and the event handler calculates the total duration of all the currently selected files and update 'total' text box.
private void files_SelectionChanged(object sender, SelectionChangedEventArgs e) { var tp = new TimeSpan(); foreach (var f in files.SelectedItems) { tp += ((TrackInfo)f).Duration; } var d = new DateTime(tp.Ticks); string format = "mm:ss"; if (tp.Hours > 0) format = "hh:mm:ss"; total.Text = d.ToString(format); }
There are two buttons called 'Select All' and 'Unselect All' that are hooked to corresponding event handlers and simply select or unselect all the files in list view when clicked. This results of course in a SelectionChanged event handled by the files _SelectionChanged event handler described above.
private void SelectAll_Click(object sender, RoutedEventArgs e) { files.SelectAll(); } private void UnselectAll_Click(object sender, RoutedEventArgs e) { files.UnselectAll(); } | http://www.drdobbs.com/architecture-and-design/your-own-mp3-duration-calculator/222500141?pgno=4 | CC-MAIN-2015-14 | refinedweb | 2,449 | 57.37 |
State is used for properties on a component that will change, versus static properties that are passed in. This lesson will introduce you to taking input within your React components.
Can you explain why the need to use this.update.bind(this) in the onChange attribute?
Previously with
React.createClass you would get autobinding. When you use es6 classes, this is no longer the case, so you need to explicitly bind the
this scope of event handler functions. People will also do this in the constructor or through a more "es7" style property binding.
constructor(props) { super(props); this.update = this.update.bind(this); }
MyComponent extends React.Component { update = () => this. update(); render() { // ...
I had some trouble with this because the code in the video does not match the code under Code. I was able to resolve it by adding:
import ReactDOM from 'react-dom';
and
changing:
export default App
to
ReactDOM.render(<App />, document.getElementById('app'));
The JSBin HTML file has script links to fb.me for react and react-dom, so that it does work there, but that is not part of the course lesson.
In further investigation, I found on the github repo for lesson 4 that main.js had been returned to its original state. In one of the earlier lessons, he deletes several lines, but never indicates in subsequent lessons that he put them back. | https://egghead.io/forums/lesson-discussion/topics/106-react-state-basics | CC-MAIN-2017-04 | refinedweb | 229 | 68.06 |
19253/cant-install-python-module-python3-use-jsonrpc-for-altcoin
Hi I want to install a module on python 3.6 on Ubuntu I want to install this because you can you altcoins with it and i cant find a way to use altcoins only btc any help.
python3 setup.py install
Traceback (most recent call last):
File "setup.py", line 32, in <module>
version=os.environ['VERSION'],
File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'VERSION'
Try this
VERSION=0.1 python3 setup.py install
and there's also a Makefile:
make all
sudo dpkg -i deb_dist/python-pifkoin_$(VERSION)-1_all.deb
module - don't think so. Because module ...READ MORE
The bluemix service was using an older ...READ MORE
This should work:
#!/usr/bin/env python
import getpass
import json
import requests ...READ MORE
This is related to a pybitcointools bug where
Try compiling and migrating the contract:
$ truffle ...READ MORE
I tried the following code and it ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/19253/cant-install-python-module-python3-use-jsonrpc-for-altcoin | CC-MAIN-2019-47 | refinedweb | 179 | 70.09 |
Win a copy of Barcodes with iOS this week in the iOS forum or Core Java for the Impatient in the Java 8 forum!
Shamsudeen Akanbi wrote:Hey, what I'm saying is that: I key in a string and I get characters in an array. You see, something like this. Split the word "SAMSON" into individual characters. So in my array I get 'S' 'A' 'M' 'S' 'O' 'N' .
I tried string.split() and the delimiter was a "\\s"
. So what I mean in short is that, instead of spacing SAMSON at the command line,
isn't there any REGULAR EXPRESSION i can use.
Shamsudeen Akanbi wrote:Please I'm trying to split a string into characters to, be stored in an array. But I don't know which delimiter I'm to use. I've been trying including spaces so that \\s splits it, but that's not exactly what I want.
import java.util.*;
class MyClass {
public static void main(String[] args) {
String[] token = args[0].split("\\s");
String a = token[0] + token[1] + token[2];
System.out.print (a);
}
}
Thanks in advance.
Chetan Sarnad wrote:
I guess you are trying to split the command line argument i.e the string at each occurrence of spaces,
So I guess this should be good enough if the string is like "My name is Shamsudeen Akanbi"
String[] token = args[0].split(" ");
Jeff Verdegan wrote:
He's actually stated quite explicitly that that's NOT what he wants.
String [] p=args[0].split("");
Oscar G. Rodriguez wrote:Another one that thinks you have to use toCharArray(), but if you don't want to, you can try with
String [] p=args[0].split("");
You'll obtain the String[], but the first element will be "".
Oscar G. Rodriguez wrote:Well, I don't know if I wrote what I want to said, my English isn't very good.
I think that he ought to use toCharArray(), another one was me because I understood that you said the same.
Sorry for the misunderstanding. | http://www.coderanch.com/t/566392/java/java/Regex | CC-MAIN-2015-11 | refinedweb | 340 | 75 |
On 5/6/09 6:56 AM, "Marcus Gnaß" <gona...@gmx.de> wrote: > Tom Worster wrote: >> there's a control structure i wish php had: a simple block that you can >> break out of, e.g. > > As Maarten pointed out you could use a function. Another alternative is > to use Exceptions which might be the most proper way to do it.
in a thread off-list i commented on the use of a function. here's what i said: yes, it's just like that. i could wrap a function around the logic. and sometimes i use that trick. the downside to that is access to globals. for many of my scripts there's a common pattern: 1 get set up. 2 process inputs, checking and preparing data for use 3 and 4 or aborting to an error handler at the end of this section (which is what the breaks all jump to) if there's a problem with the input. 3 do some work 4 prepare an output page in this scheme, it's convenient if 2, 3 and 4 all have access to the same namespace, so i don't usually use the function approach. -- PHP General Mailing List () To unsubscribe, visit: | https://www.mail-archive.com/php-general@lists.php.net/msg246025.html | CC-MAIN-2018-17 | refinedweb | 204 | 82.04 |
Beginner: Web Scraping in Mostly Pure Python
KurzGedanke
Updated on
・6 min read
I love web scraping, especially in the beginning of learning how to code. It is fairly easy, you can learn a lot about how to handle data and you get immediate results!
But I see a lot of tutorials which get overly complicated and focuses mainly on a framework called Beautiful Soup. It is a fantastic and mighty framework but most of the time - and especially for a beginner - it is completely over the top. Let's be honest, we don't want to index a complete website, most of the times we just want to download images or ask for a few values.
This can be done a lot of easier with one magic word,
Regular Expressions.
Okay, okay, I hear you "whaaat? Regular expressions and easy? WTF?"
Yeah, you are not wrong, RegEx aren't that easy. Personally I found it much easier to learn RegEx than an arbitrary framework which has only one use case.
What are regular expressions?
The concept of regular expressions occurred in the 1950s. In theoretical computer science it is a sequence of characters that define a search pattern. (Wikipedia)
So, what does a regular expression looks like?
Imagine we have a string:
Hi, I'm KurzGedanke and is my website.
Now we want to get the website with the specific domain. We can assume that every input looks like.
One solution to match this with regular expressions might be looking like this:
www\.(.*)\.([a-zA-Z]*)\s
wwwas you might suspect, this matches exactly
www
\.matches the
.after the
www. Because the dot has a function in RegEx we need to escape it with the
\.
(.*)the
.matches any single characters. Is it the
aor a tab, it will match it. Besides of newlines. With the asterisc we match zero or more characters of the expression before it. In this case zero or more of any single character. The parentheses
()puts the match in a group which can be accessed easily.
\.this dot matches the dot before the top level domain.
([a-zA-Z]*)here we have the top level domain, which is put in a group again with the
().
[]are used to match a single character. In this case a character between the lower
ato the lower
zor the capital
Ato the capital
Z. To get more than a single character the
*is used.[This is funny and a classic mistake. I didn’t thought it through completely. A URL can of course contain a dash
-and I missed it.]
\smatches white space. In this case it is used to end the regular expression.
To be honest, I think there are smarter ways to do this, but I find this way easy to see what’s going on and not to get overwhelmed by a 50 character long RegEx string.
To learn regular expressions I used an interactive tutorial like this: regexone.com. This is not the only one out there and you can look if you find one that suites you.
Another great tip are sites like regex101.com. You can paste text in it and write directly your regex while you can see in realtime which parts are matched.. I use it everytime when I write some regex.
Lets write some python
We can use this knowledge to scrap websites. And... to be honest... I will rely on a module called Requests: HTTP for Humas. But this module is so easy to handle and pythonic - sometimes I have the feeling it is more pythonic than python itself.
Our goal is to scrap my website and get every article title of my landing page, as well as the link to it.
A simplified version of the HTML looks like this:
<div class="post-list"> <article class="post-preview"> <div class="post-preview-heading"> <h2><a href="">Headless ssh and Wifi on RaspberryPi</a></h2> </div> <hr> </article> <article class="post-preview"> <div class="post-preview-heading"> <h2><a href="">How to Encrypt Files with AES</a></h2> </div> <hr> </article> <article class="post-preview"> <div class="post-preview-heading"> <h2><a href="">Problems with Flask and PyCharm</a></h2> </div> <hr> </article> <article class="post-preview"> <div class="post-preview-heading"> <h2><a href="">Decentraland | How to Mine on a Mac</a></h2> </div> <hr> </article> <article class="post-preview"> <div class="post-preview-heading"> <h2><a href="">Welcome</a></h2> </div> <hr> </article> </div>
So, what are we looking for in this HTML? Let's see, we want the titles and the url of all posts. We have a few articles with the class
post-preview. And down below we have a
h2 heading inside a
div called
post-preview-heading. The
h2 contains a
a href which assembles a link. Might be good to go! Every
h2 has the same structure and, we are lucky, this is the only
h2 with this structure on this whole side. So we can assume, like above, that every input looks exactly like this:
<h2><a href="linkToPostTitle">postTitle</a></h2>
On other websites the
h2 or the
a href would have a dedicated class or id like
<h2 class="post-preview-title-header"></h2>
this is even better because we would have a persistent pattern which could be used to match against.
Now let us write our RegEx to search for.
<h2><a href=\"https:\/\/kurzgedanke\.de\/post\/
This simply represents the
<h2><a href=" string. Again the backslashes as well as the
double quotes have to be escaped.
Note: You can leave the escaping of the double quotes out when you use single quotes in your python code. But escaped double quotes are always the safe option.
Now the rest:
<h2><a href="https:\/\/kurzgedanke\.de\/post\/(.*)\/">(.*)<\/a><\/h2>
(.*)selects everything after the
post/till the
/">and puts it in a group.
- 2.
(.*)matches the post title
<\/a><\/h2>closes of the
</a>tag and the
</h2>tag.
Now that we've written the regular expression let's take a look at the python code.
import re import requests r = requests.get('') regex = r'<h2><a href="https:\/\/kurzgedanke\.de\/post\/(.*)\/">(.*)<\/a><\/h2>' titleURL = re.findall(regex, r.text) for urlAndTitle in titleURL: print(f'Title:\t {urlAndTitle[1]}') print(f'URL:\t{urlAndTitle[0]}/') print('-------------------------------')
import reimports the regular expression module from the standard library
import requestsimport the requests module from Kenneth Reitz.
r = requests.get('')makes an HTTP request to kurzgedanke.de and safes the data in a requests object.
regex = r'...'declares a variable with the regular expression as a value.
r'...'tells python that this string is a regular expression.
titleURL = re.findall(regex, r.text)we use the regex module to find all matches with the use of our regex variables and
r.textwhich contains the html of our http request. After everything is found it will be a list with all matches assigned to
titleURL.
for urlAndTitle in titleURL:we can easily iterate over the list and access the different matches with an array notation because we grouped them up in our regular expression with the
().
When you run the script it should look like this:
Title: Headless ssh and Wifi on RaspberryPi URL: ------------------------------- Title: How to Encrypt Files with AES URL: ------------------------------- Title: Problems with Flask and PyCharm URL: ------------------------------- Title: Decentraland | How to Mine on a Mac URL: ------------------------------- Title: Welcome URL: -------------------------------
I hope you found this little write up useful and learned a bit.
If you have any question or remarks, please leave a comment, contact me on twitter or write a mail.
You can read this post as well on kurzgedanke.de.
If I don't use React, am I still a developer?
A self-taught developer, more confident in his abilities than ever, feels he's just a hack because he doesn't understand anything anymore
Chapter 1 - Programming for the Puzzled
Takahiro Kudo -
Get rid of chrome restore bubble popup when automate GUI test using Selenium
cuongld2 -
Using Multiple Linear regression to solve banknote authentication problem
penthaapatel -
Once you get the basics of web scraping, most problems you are likely to stumble upon when going further are already solved by scrapy, a wonderful web scraping open source library I enjoy using.
Check it out! scrapy.org/
I take it you've not read this warning; stackoverflow.com/questions/173234...
Regexex might work just fine if you're just interested in titles, headers and links, but otherwise you should consider using an XML-parser, like Beautifulsoup with the lxml library for backend.
Though it's worth noting that you won't be able to scrape elements which are rendered with javascript, since there's no javascript engine in a pure python scraper.
If you're after performance, you can use some async-stuff or just threading... I think they do approximately the same under the hood.
Or use grequests in lieu of requests, which handles the async-stuff for you, while mostly retaining the same API (it's now a generator, but otherwise I think it's the same). And it's by the same author as the requests library.
Happy scraping! | https://practicaldev-herokuapp-com.global.ssl.fastly.net/kurzgedanke/beginner-web-scraping-in-mostly-pure-python-6d0 | CC-MAIN-2019-43 | refinedweb | 1,532 | 64.3 |
*OWFTUJHBUPSĴT3FQPSUUPUIF1SVEFOUJBM"VUIPSJUZ
VOLUME 1
I have, for the past five months, investigated the sorry affairs of
R2 billion. And they certainly did not put in anything like the
INTRODUCTION ...........................................................................................3
The audited financial statements for the year ended 31 March 2017 ....... 75
APPENDICES
Appendix D: Exhibits
1 Against the backdrop of, inter alia, a severe liquidity crisis that prevailed at
VBS Mutual Bank ("VBS"), the Minister of Finance placed VBS under
Services was appointed, in terms of section 81 of the Mutual Banks Act 124
of 1993 ("the Mutual Banks Act"), as the curator to VBS. The curator is
2 On 13 April 2018, and consequent upon the initial findings of the curator
which revealed massive losses in VBS, the Deputy Governor of the South
African Reserve Bank, in his capacity as the Chief Executive Officer of the
appointed me as an investigator in terms of section 134 of the FSR Act for the
or not:
3.1 any of the business of VBS was conducted with the intent to defraud
purpose;
they have also acted as evidence leaders during the formal interviews that took
to the investigation. They have played essential roles in the investigation. They
are:
5.1 Basileus Consilium Professional Services (Pty) Ltd ("BCPS"), who are
the interviews that have taken place in terms of section 136 of the FSR
Act.
5.2 FACTS Consulting (Pty) Ltd ("FACTS"), who are cyber-forensic and data
also took control of and mirror imaged the data stored on the computers
to the investigation.
5.3 Crowe Forensics SA (Pty) Ltd ("Crowe"), who are specialist chartered
are implicated in the frauds and thefts that have taken place at VBS.
the sometimes complex technical issues that arose in the enquiry into
6.1 flow of funds between VBS and the various municipalities which
6.2 the flow of funds through VBS’ banking system, named EMID, in respect
investigation.
report. I shall, in due course, make reference to various aspects of their report.
8 The investigation has been conducted in accordance with the provisions of the
investigation.
10 Many of the persons that were interviewed invoked the immunity provided by
section 140(1) of the FSR Act, which constitutes a use immunity. As such, the
immunity in the manner prescribed by section 140(1). It does not prevent the
protected evidence from being used against that person in any other
does the immunity prevent a prosecution being instituted against that person
is acquired.
conducted in terms of the provisions of section 137 of the FSR Act at VBS’
head office at Makhado on Tuesday, 17 April 2018. The investigation team had
been informed by the curator’s representatives that VBS records were mainly
of VBS required to be urgently searched and the scope of the search and
seizure operation was expanded to include VBS’ offices in Sandton and its
Thohoyandou branch.
warrant in terms of section 138 of the FSR Act to enter and search the
issued by a High Court Judge on 2 May 2018 and on Monday, 7 May 2018, a
search and seizure operation, as contemplated in section 137 of the FSR Act,
in VBS.
13 The search and seizure operations that were conducted formed the principal
source of the vast depository of data that the investigation team has had
FORMAL INTERVIEWS
14 A series of formal interviews was held with various persons that were identified
auditors and other players. As the investigation unfolded some witnesses were
Appendix B to this report. The full transcripts of their evidence, together with
the exhibits referred to in the course of their testimony, accompany this report
electronic format.
16 I shall set out in this report the findings I have made arising from the
those findings. The report does not deal with every aspect of the evidence that
17 I shall also set out my recommendations relating to both criminal and civil
18 The evidence that has been gathered traverses what I have found to be two
VBS.
18.1 The one pillar constitutes the methods used by those who had captured
VBS which enabled them to embark upon widescale looting and pillaging
of the monies placed on deposit at VBS. I found that there were three
18.1.1 Payment of very large sums of money was made to the various
directors and other related parties in order to buy their silence and
to look the other way while the looting was going on.
18.2 The other pillar is the way in which, by fraudulent means, the looting of
VBS was hidden from view and was allowed to continue and, indeed,
its liabilities exceeded its assets by about R180 million and it was, thus,
hopelessly insolvent as at 31 March 2017. By the time that the bank was
worse. Had the truth been told the Registrar would have been able to act
far more expeditiously and the looting could have been stopped much
earlier.
19.1 first introduce each person that was interviewed in the course of the
19.2 second set out my detailed factual findings in regard to the collapse of
19.3 third set out, in summary, the extent of the looting of VBS that emerges
to:
19.4.1 the preferring of charges against those who have been involved in
instituted.
20 For convenience, I have divided the dramatis personae into three categories –
the insiders, the outsiders and the auditors. At times, as will be seen, these
21 The "insiders" comprise directors and employees of VBS. The following persons
were interviewed:
21.2 Philip Nicolaas Truter ("Truter"), an Executive Director and the Chief
receiving a large reward from Vele’s banking account for his complicity in
the scheme.
of evidence to the contrary, has steadfastly denied that he was in any way
issued shares in VBS. Magula, who previously held the post of Executive
in order to buy his silence. Nesane resigned from his post at the PIC two
as its Chief Financial Officer. As was the case with Magula and Nesane,
The price for his complicity seems, however, to have been significantly
PIC. She also testified about the creation of fictitious contract finance
21.9 Yolanda Deale ("Deale"), who was, until February 2017, an accountant
in the employ of VBS. After her departure from VBS the looting of the
that title, a director of VBS. Maposa testified about the use of numerous
structures of VBS, some of these persons played crucial and central roles.
VBS and the municipalities. Matsepe’s role in the affairs of both VBS)
22.4 Takalani Veronica Mmbi ("Mmbi"), Matodzi’s faithful assistant. Mmbi set
to launder some of the funds stolen from VBS. When VBS was put into
her efforts.
was the former Chief Operating Officer of VBS and later COO and then
derived very large rewards, much of which was in the form of undeclared
income.
22.6 Yvonne Page ("Page"), the former acting Group CFO of PRASA who told
PRASA from depositing that sum into what she described as "a Ponzi
scheme".
22.7 Mariette Venter ("Venter"), a chartered accountant and the acting CFO of
and managed to force VBS to return the municipality’s funds to it. She
was unfairly suspended from her post as a result and pilloried as a racist
23 The auditors comprise the various members of the KPMG audit team which
conducted the statutory and regulatory audits of VBS for the financial year
23.1 Zondi Nduli ("Nduli"), a third year clerk on the 2017 VBS audit. He
was the audit manager on the 2017 VBS audit. She was the person in
23.3 Luan Niewoudt ("Niewoudt"), a first year clerk who was initially deployed
23.4 Tersia Monare ("Monare"), a second year clerk who took over the cash
23.5 Cindy-Lee Williams ("Williams"), another second year clerk, who was
23.6 David Broom ("Broom"), a chartered accountant who was the engagement
23.7 Cezanne Krieg ("Krieg"), a member of the regulatory audit team who
with the provisions of the Mutual Banks Act and its regulations.
was the engagement partner on the 2017 VBS audit. Malaba
conduct of VBS’ business. He, his companies, and his associates have been
25 During July 2018, the curator of VBS brought applications to sequestrate the
the curator as being central participants in, and beneficiaries of, the looting
of VBS. Matodzi did not oppose the application for his provisional
sought in his affidavit to lay the blame squarely and solely on Ramavhunga,
pandered the preposterous tale that Vele had intended to borrow R1.5 billion
in due course.
THE FINDINGS
27 As already alluded to, the investigation has revealed that the business of VBS
his associates.
28 The evidence that has been gathered shows that until 2014 VBS was a modest,
clients against the security of the deposits they had made with the bank.
29 Originally VBS’ shareholders were largely its depositors who had chosen to
invest by way of paid-up shares. The PIC, which had succeeded to the pension
VBS. During 2013 Matodzi approached the Venda king, Toni Mphephu
Promafco (Pty) Ltd ("Promafco") owned by David Mabilu ("Mabilu") and the
held 51% of the shares in Dyambeu with Brilliantel and Promafco each
VBS. In his first chairman’s report, dated 22 June 2016, Matodzi stated that
"I have however been involved with the bank strategy and turnaround since the
and Ramavhunga had known each other at university. They are both qualified
December 2013 and, with effect from 1 August 2014, he was appointed to the
There were two main parts to the turnaround strategy. First, VBS’ traditional
reliance on small retail depositors to fill the bank’s coffers was abandoned and
VBS now set its sights on obtaining very large, but short term, deposits from
money to. VBS entered into numerous high-value fuel financing and contract
financing deals with a variety of clients. The evidence reveals that many of
34 The ostensible impact of the turn-around strategy can be discerned from the
34.1 In the year ended 31 March 2014 VBS reported a loss of R1 871 982. It
had made loans and advances in a total amount of R210 364 202, less
loans. It held R285 218 985 of depositors’ funds. Cash and cash
overdrafts (2.1% of the book) and vehicle finance (3.4% of the book). It
held depositors’ funds amounting to R352 301 042. Cash and cash
34.3 In the year ended 31 March 2016 VBS’ reported profit had risen to
R4 888 819. Its loan book had jumped to a reported R697 508 746, less
stood at 11% and 12% respectively. VBS had extended its lending
term personal loans now made up a mere 0.3% of the loan book.
Depositors’ funds stood at R621 781 540. Cash and cash equivalents
34.4 The audited annual financial statements for 31 March 2017 report a
vastly changed position. The still modest reported profit, before tax, was
R5 689 010. However, the loans and advances book now stood at
at 12.9% and vehicle finance constituted 17.4%. Asset finance and short
term personal loans stood at 0.8% and 0.4% of the book respectively. VBS
Cash and cash equivalents were reported as being R802 427 245.
34.5 As will be shown in due course, the 2017 audited financial statements
35 Mukhodobwane testified that during April and May 2017 Matodzi paid him a
so-called "bonus" totalling R500 000. Payments were made from Vele’s
account. R350 000 was paid on 13 April 2017 and R150 000 was paid on
the amount of R10 million. This payment was made into an account operated
front for him. He testified that during December 2017 yet another "bonus" in
37 Truter stated in his testimony that he had been promised R5 million but that
38 Ramavhunga admitted that he, through Dambale, had received the sum of
R15 million from Vele’s banking account on 5 October 2017. He also admitted
series of monthly payments of R300 000 from the bank accounts of Vele
Petroport (Pty) Ltd ("Vele Petroport") and Vele over the period July 2016 until
strenuously denied that any of these payments were untoward. He stated that
the R15 million was paid to Dambale in respect of a fee earned by him for
He stated further that the monthly payments of R300 000 and the R1 000 000
payment were earned as management fees for work that he had done in
respect of a joint venture between two of VBS’ fuel finance customers, Belton
39.1 His employment contract with VBS precluded him from carrying out the
sort of activities that he contended were the causa for the fees supposedly
39.2 As demonstrated more fully below, the agreement between Vele and the
vendor of the shares in Mvunonala had already been finalised prior to the
parties.
39.3 The monthly payments of R300 000 all took place on the same date each
Makhavhu, who is the advisor to the Venda king. Each of Magula, Nesane
and Makhavhu admitted that there was no lawful cause whatsoever for
these payments. Magula and Nesane admitted that the payments were
receiving substantial rewards for their participation in the looting of VBS has,
41 His credibility was damaged beyond repair by his mendacious insistence that
the R15 million that he had received on 5 October 2017 had been earned by
42 He previously explained that he had earned the R15 million payment for
shares in Mvunonala.
adamant that he had earned a fee for bringing about the agreement on
45 Ramavhunga then shifted his ground and stated that Mhlanga "is actually the
Gasela Family Trust" and that Tshepo Mathopo, the trustee of Gasela, merely
"by way of introduction" around 4, 5 and 6 August 2017 and went to Zimbabwe
and WhatsApp communications relating to the deal and the fees agreed upon.
nonsensical.
Mmampilo together and earning a very substantial fee for doing so,
Ramavhunga utilised the bank’s confidential information. Any fees that were
47 Ramavhunga would have me believe that, despite the fact that he was the CEO
of VBS for the better part of four years, he was blissfully unaware of what was
abundantly clear that Ramavhunga was a central and active participant in the
unlawful conduct of VBS’ affairs, who was very well rewarded for his
complicity.
Ramikosi, all confessed that they had been rewarded in an improper manner.
49 Magula, after first giving a great deal of false evidence in this regard, eventually
found himself constrained to retract his prior evidence and to seek immunity
front companies which were his vehicles for receiving payments from Vele
49.2 in return for those payments, Matodzi was "buying silence from those that
and had given him support and guidance out of the goodness of his heart.
52 Shortly after the termination of the interview, Nesane returned and stated that
hearing at 19:00 at which point Nesane invoked his right to object in terms of
the provisions of section 140 of the FSR Act. His objection was overruled, and
he thus acquired the use immunity provided for in section 140(1)(c) in respect
52.4 The only reason for the payment of that sum was to buy his silence and
to ensure that he did not properly comply with his fiduciary duties as a
stated that he was not aware of the full extent and detail of their irregular
conduct.
of VBS. This was also the case with the appointment of Madzonga as the
52.7 He was well aware that there was a disconnect between the rosy financial
52.8 It had come to the attention of the board that very large loans had been
which was initially R100 million and later increased to R250 million, as
52.9 It is his view that the Chairman of the Audit Committee, Ramikosi, must
Management simply ignored the board’s decision and no steps were taken
Ramikosi totalling R99 400 over the period August 2017 to March 2018. He
stated that these supposed loans were personal, not in writing and intended
54 He was also asked about payments totalling R96 618.16 made by Zanoware
August 2017. He testified that he was not "privy to that arrangement" and,
since they have been divorced since 2014, he did not know what the purpose use immunity in terms of section 140 of the FSR Act in respect of the
56.1 Ramikosi admitted that Zanoware was in fact, and contrary to his
56.2 He testified that initially Zanoware was set up to be used for opportunities
that may come up in the trucking business. It was set up with a nominee
conflict of interest. He explained that the first payment of R250 000 was
Zanoware did some catering work for Vele but that no services were
56.2.1 the payment of R250 000 on 13 March 2017 was not received as a
56.2.2 a small part of the payment of R200 000 on 26 July 2017 was received
Zanoware but that the bulk of the payment was not earned at all; and
56.2.3 the payment of R300 000 on 29 October 2017 was entirely for
for his benefit and that there were no "loans" to him by Manye as he had
testified the previous day. He admitted that all payments made through
56.5.1 he knew that, as the chairman of the audit and risk committee, he
56.5.2 he could plainly not receive monies on the side, and he knew that he
56.5.3 he knew that it would be wrong to exploit his relationship with VBS
56.7 After further probing Ramikosi eventually conceded that the intention to
disguise his involvement was, in fact, present right from the outset and
Zanoware.
notwithstanding the fact that he was receiving money from VBS’ majority
"could still create a distinction between what needed to be done. I had kept
a separate view of the transaction and the work I needed to do for the
bank".
became the COO of Vele. In September 2017 he became the CEO of Ve
60.1 R3 000 847 was paid from the VBS Corporate bank account;
60.3 R11 471 580 was paid from the Vele account;
60.4 R1 750 000 was paid from the Vele Petroport account;
60.5 R15 000 000 was paid from the Vele Financial Services account;
60.7 R700 000 was paid from the Black Label Telecoms account;
60.9 R115 000 was paid from the Allcare Administrators account;
60.10 R10 000 was paid from the Uhuru Studios account; and
62 He said he received a signing on bonus of R5 million, again net after tax, when
that. The amount of R4.5 million was paid by Vele into Madzonga’s home loan
account at VBS.
when Madzonga was applying to First National Bank for a home loan,
certifying that Madzonga "receives a monthly gross salary of R400 000.00 plus
R100 000.00 travel allowance". Madzonga admitted that the home loan
"services rendered".
65 Madzonga was required by me to produce his income tax returns. The returns
for 2017 and 2018 reveal that none of the money received by Madzonga,
described in paragraph 60, has been declared by him as taxable income in the
66 Madzonga attempted to explain the payment of the sum of R15 million that he
19 February 2018 when VBS had put itself in a position where it had
points rather to Mathopo having paid an amount from his trust account that
was due to Vele arising from the cancellation of an agreement that a company
named Intsika Women Powered Solutions (Pty) Ltd ("Intsika") had entered into
67 Ramavhunga was happy to take credit for the "turn-around strategy" at VBS,
1 This is the same person who features as a trustee of the Gasela Trust in the Mvunonala acquisition. Time constraints on the investigation prevented these issues being explored further with Mathopo.
suggested that all banks do that. He strenuously denied, however, that he had
any knowledge that bribes were being paid to municipal officials to persuade
roll-over the funds when they became due for repayment. I find his denials to
be disingenuous.
solicit the deposit. In some cases, there were agreements in place that set the
Mukhodobwane stated that invoices for these fees were kept within his own
department at the bank and in the finance department. Some were contained
69 Mukhodobwane stated that initially there was no direct contact between VBS
and the municipalities and all payments were made by VBS to the so called
received "a can of Coke" for his efforts while the "consultant" had received
Nemabubuni, who is the General Manager of Sales at VBS. VBS was, however,
unable to cut out the "consultants", who "in most instances had political ties to
either (sic) very powerful people within the ANC structures within that particular
region".
time to time to bribe municipal officials and funds would then be drawn in
72 During the course of further questioning on this topic, on 22 May 2018, and
extremely reluctant to reveal that name and he expressed fear about his
to Msiza.
monies on deposit at VBS as, in her view, the regulations under the Municipal
who was the acting Chief Financial Officer of Capricorn at the time, that she
75.1 the MFMA regulations required that a municipality had to invest funds
by way of deposits with banks registered in terms of the Banks Act, which
made with institutions with a BBB or higher rating investment grade rated,
77 Venter’s intervention came at some personal cost to her. She was put under
later and Capricorn refrained from making any further deposits with VBS,
making it one of the few municipalities in Limpopo that did not find itself in
persuaded him that the "white lady" was incorrect in her interpretation of the
the bank. This involved Matsepe introducing municipalities to VBS and if "the.
virtue of those initial introductions, which took place at an event held at the
funds already deposited were rolled-over after the term of the deposit had
expired.
at the Ranch. He stated that he met Matsepe at the event. Matsepe was
talking". Matsepe, on the other hand, has denied that Msiza played any
numerous occasions when his political influence was required. I have little
been sourced through Msiza. He stated that Msiza had become involved at a
stage as a result of a complaint made by Matsepe that he had not been paid
let me know if the R50 million from Makhado doesn’t come through. Will take
82 Ramavhunga initially denied that any bribes were ever paid to municipal
officials to place municipal funds into VBS. He then invoked the use immunity
conferred by section 140 of the FSR Act and said, in a hedged manner, that:
MR RAMAVHUNGA: Yes."
84.2 VBS, from the Robvet account, made payment directly to front companies
85 I take the view that the very fact that such payments were made from the
his knowledge, received bribes. The detail of this evidence is set out in
Appendix B.
87 During the course of the investigation Matsepe was ordered in terms of section
136 of the FSR Act, to produce his cellphone and to permit a mirror image to
between Matsepe’s attorneys and me, then ensued which separated the
messages into those that Matsepe conceded were relevant to the affairs of VBS
are discussed. There are many other conversations that cast light on
conversations are set out in Appendix B. The full conversations are to be found
that:
"The Mayor of Vhembe is crying she says we must give her and the speaker a Christmas because they are the ones who are making sure we
90 Matodzi agreed to that, but on 16 January 2018 Matsepe reported that Msiza
27 January 2015 until the advent of the curatorship, with reference to EMID
accounts, VBS received over R3.4 billion from municipalities. In turn, it made
93 As appears from the report, at 30 April 2018 the amount remaining in VBS on
account of municipal deposits was R1 229 840 197. This balance, which
from municipalities and the bank set its sights on the vast sums under the
R1.5 million was paid to a group of union officials from SATAWU who had
claimed the ability to "facilitate" such a deposit from PRASA. VBS paid that
being made.
December 2017.
Cromet Molepo, the Acting Group CEO of PRASA, was found amongst the
records of VBS taken by the investigation team during its search and seizure
after reading the letter, that he had not seen it before and that he doubted
that Ramavhunga was the author and speculated that Matodzi had written it.
months. He viewed 9.25% as a high interest rate, but VBS was desperate for
the funds. He stated that the cost to VBS of obtaining the deposit would,
however, be far greater than the amount of the interest that would accrue on
obtain the deposit. He confirmed that the deposit was ultimately not made by
PRASA and he said that the multi-million Rand bribe was not paid by VBS.
deposit from PRASA. He was asked if he was aware that R1.5 million had been
soliciting a deposit from PRASA. His answer was "It could have been. I know
the donation was probably around December". He then stated that "I know for
a fact that we were asked to put money into the Dudu Myeni Foundation".
101 I understand that there is no entity known as the Dudu Myeni Foundation.
102 Ramavhunga stated that he could not recall who told him that VBS needed to
Ramavhunga stated that the request for a donation to the "Dudu Myeni
103 The former acting Group Chief Financial Officer of PRASA, Yvonne Page
funds in accordance with its investment policy and Treasury regulations. Page
stated that VBS’ representatives had approached the then acting CEO of
to R1 billion with VBS. Zide subsequently told Page to follow up with VBS.
109 Page stated that on 15 January 2018 she was summoned to attend a meeting
in Molepo’s office. Upon her arrival, Manyanga of VBS was already with
Molepo. This suggested to her that Manyanga had easy access to the acting
110 She said that on 16 January 2018, Manyanga addressed an email to various
officials at PRASA "confirming" that the investment will be made "as agreed"
and that PRASA should forward the necessary FICA documents in order.
that after a "fruitful and constructive" meeting between Molepo and Matodzi,
VBS had now approved an increased interest rate of 9.25%. Molepo then, on
the same day, gave a directive by email to Page saying "Because of the strategic
for approval by the nominee of the BOC". The email was copied to the then
her that VBS was nothing more than a Ponzi scheme as the big banks would
116 Page’s steadfast and principled refusal to bend the rules saved PRASA from
making what would have proved to be a very bad "investment". I have not been
117 Ramavhunga later testified that the PRASA deposit was "awarded" in terms of
the Zide letter dated 6 November 2017, and also in a second letter from Molepo
that "I think this Prasa is important more especially that we can get the funds
uncomfortable about many people being involved", "He has R13bn investments
with all the banks" and "So he will give us 1bn and if we do it right he gives us
another 2 after a month". Ramavhunga persisted with his denial of who "the
testimony that a multimillion rand bribe was going to be paid to highly placed
PRASA officials in order to secure the R1 billion deposit is most probably true.
about this very transaction. It is most strange that he would then deny any
knowledge of who "the guy" at PRASA was unless he was very much aware
that there was something untoward about the transaction and feared that he
discussion. If the proposed transaction was above board there would have
MR RAMAVHUNGA: Yes.
MR RAMAVHUNGA: Yes."
might have been paid. He testified there was an ongoing attempt by VBS to
obtain a facility of R2 billion from the PIC. He testified that on 8 April 2017 he
the money was for and Matodzi responded that the money was required to be
paid to "Dr Dan" to obtain his cooperation in facilitating the funding of VBS’
indeed paid to "Dr Dan" by Matodzi as the R2 billion line of funding was not
have lied to him about the purpose of the R5 million in cash and that Matodzi
may have required and used the cash for his own purposes. I cannot, in these
circumstances, make any definitive finding, but I certainly regard the matter
124 Truter testified that significant amounts were lent to various parties by VBS,
financing was a prime location of the looting of funds from VBS. Astonishingly,
the contract finance book, which eventually became the single largest asset of
VBS, was not recorded in the bank’s operating system, known as EMID, but
with ease.
125 A number of witnesses were probed about the failure to bring the contract
finance book onto EMID. I was told that the EMID system would have to be
one was able to give any sensible explanation of what makes the recording of
VBS. During 2017 Vele purported to take up a 53% shareholding in VBS. This
was purportedly in terms of a rights issue. Vele, which was not an existing
shareholder at the time of the rights issue, was therefore not entitled to take
by a blatant fraud.
128 By late 2016 Vele had embarked on a trail of major acquisitions. The first
("Insure"). Insure was a very attractive target, for both Vele and VBS. It
each month and it earns interest from banking the monies collected by it for
Insure charges a fee to its clients for the treasury function it performs.
129 For some time Insure had wished to obtain capital to expand its business into
nominated by Vele.
fund the "deposit" of R250 million which was to be made available to Insure.
was specifically created to facilitate the making available of the R250 million
133 He explained the whereabouts of the corresponding entry in the bank’s books
as follows:
134 Once the R250 million fraudulent deposit was created in a 32 day notice
over the following months. Insure, in turn, deposited R18 million into the
to serve as supposed evidence that VBS had received payment of the amount.
this fraudulent scheme and had, in due course, erroneously permitted the
138 In as much as the R80 million did not in fact exist, this also contributed to
Vele, which followed a similar modus operandi to the Insure acquisition, were
created;
139.2 Anglo African Finance, where a fictitious deposit of R80 million was
140 Vele was, either directly or indirectly, the beneficiary of these fraudulent
transactions. The net effect was to systematically steal funds which had been
funds held on deposit by the bank that gave rise to what, on the face of it,
merely that there was a mismatch between short-term deposits and long-
term lendings by VBS. This, of course, was not the actual reason for the
141 On 19 March 2017 Matodzi met with Mukhodobwane and Truter at the
scheme to further impoverish VBS for the benefit of Matdozi and a large
number of his associates. This time Matodzi’s instructions were very detailed
and were put in writing by him in the form of an Excel spreadsheet, which he
was to:
142.1 wipe out the overdrawn balances on some 34 accounts held at VBS in the
142.2 create new and, in most cases, increased overdraft facilities on these
34 accounts;
142.3 create fictitious "investments" in the names of Matodzi and five other
142.4 cause shares in VBS to be issued to Matodzi and various of the related
144 The beneficiaries of the first and second instructions were as follows:
144.3 Mmampilo received a further R3.5 million deposit and a R3 million facility
144.5 Venmont Built Environment (Pty) Ltd received a R5 million deposit and a
R3 million facility;
144.6 Tiisang Risk and Assurance Consulting received a R7 million deposit and
144.8 Belton Park Trading 134 received a R3.5 million deposit and a R3 million
facility;
144.10 Mafanzwaini received a R500 000 deposit and a R460 000 facility;
144.11 Dzata Trust received a R9 million deposit and an R8.5 million facility;
144.14 MML Food Services (Pty) Ltd received a R19 million deposit and a.20 Vele received a R16 million deposit and a R15 million facility on one of its
accounts;
144.21 Vele received a R3 million deposit and a R1.5 million facility on another
of its accounts;
R4 million facility;
144.24 Vantpix (Pty) Ltd received a R4.2 million deposit and a R4 million facility;
144.26 Zanocube (Pty) Ltd received a R8.2 million deposit and a R7 994 573
144.27 Vantifusion (Pty) Ltd received a R6.7 million deposit and a R6 492 806
144.28 Bonulog (Pty) Ltd received a R5.5 million deposit and a R5 261 388
144.29 Bonusec (Pty) Ltd received a R5.15 million deposit and a R4 927 347
144.30 Bonuset (Pty) Ltd received a R8 million deposit and a R7 543 394 facility;
144.31 Bonuspace (Pty) Ltd received a R4 million deposit and a R4 927 347
144.32 Viridesol (Pty) Ltd received a R4 million deposit and a R3 017 298 facility;
144.33 Wegezi Power Holdings (Pty) Ltd received a R15 million deposit and a
144.34 Shimba La Ndou Family Trust received a R7.5 million deposit and a
R5 million facility.
145 Makuya, Mafanzwaini, Dzata Trust and Vhavenda Heritage Trust were:
148 Plainly, these unlawful transactions, which were all taken account of in the
financial statements for the year ending 31 March 2017, had a very significant
149 I earlier alluded to the contract finance book at VBS. The 2017 annual
allowance of just over R3.5 million. Truter testified, however, that in his view
150 Because the contract finance book was kept on an Excel spreadsheet rather
than on the EMID system, there were no automatic reports generated when
records. Mcwazzer, who by her own admission was engaged in various forms
the Reserve Bank. In reality, however, the credit committee was almost never
convened, and exceptionally large loans were made on the sole authority of
not only exceeded the levels that would have required Reserve Bank approval
153 A significant case in point relates to the contract finance facilities granted to
company with no balance sheet to speak of, was granted a facility of R100
million. This facility was granted on the sole authority of Ramavhunga. At the
Leratadima would service the facility by the receipt of monies earned by it from
a lucrative contract that it had entered into with the Universal Service and
Access Agency of South Africa ("USAASA"). It appears that at some stage the
to VBS was about R138 million. By that stage Leratadima had become
embroiled in a dispute with USAASA and any flow of funds from that source
of R24 million and Belton Park with an exposure of R36.5 million. These
was involved with Belton Park and Mmampilo. Ramavhunga granted a facility.
156.1 the objective of "Black Ops" was to generate fictitious profits that would
156.2 the scheme was hatched at a meeting held at the Eagle Canyon Club
House during July 2017. This coincided with the finalisation of the 2017
audit, by which time it was clear that there was a massive, but hidden,
156.3 Matodzi, Truter and Ramavhunga were "all in the know"; and
and VBS.
158 A list of names of these companies and corporations, together with CIPC
the Eagle Canyon spreadsheet. Not only was Tiisang’s existing overdraft
had received Mcwazzer’s wording and had then completed the fictitious
presence and also that Ramavhunga well knew that they were false.
163 She identified the other participants in the group as being Truter,
transcript. Later, however, in her evidence, Mcwazzer stated that the initial
meeting only included Matodzi and Busa and that Matodzi had told her to
Ramavhunga was not present at any meetings relating to Black Ops, nor was
had signed the contracts he never saw any credit committee recommendations
or approvals.
168 Ramavhunga was informed by us that Mcwazzer had testified that each and
every one of these contracts was fictitious and that they had been created in
"my question is how would she know because she was on maternity leave?".
170 Mcwazzer objected, in terms of the provisions of section 140(1)(a) of the FSR
Ltd ("Imbani"). Previously Truter had testified that this was an example of a
fraudulent document that had been created in order to mislead the PIC into
permitting further drawdowns on the facility that it had granted to VBS. The
matter and she accordingly obtained the use immunity conferred by section
circumstances.
171 Mcwazzer confirmed that the purported addendum did not arise from a
request from Imbani but rather that the document was created pursuant to
that the document had not been signed by anyone authorised on behalf of
clients whose names were similarly used to defraud the PIC. She stated that
Belton Park and Seraj may also have been used in this way. She testified that
in the case of the Thlokaina addendum, she had personally copied and pasted
172 She stated that she was personally aware of the direct participation of herself,
creation of the addendums. She stated that Truter had told her that this was
drawdowns on the PIC facility were used to improve VBS’ liquidity position.
173.1 The information disclosed in the 2017 annual financial statements was
taken by Truter from VBS’ financial records, and in particular the trial
KPMG’s third year audit trainee, Truter employed the services of a firm
named A4B to prepare the statements. But that firm did no more than
provided by Truter.
means of the "suspense accounts" which Vele and its associates had the
advantage of.
173.4 He testified that although much of what was disclosed in the accounts
the trial balance and the actual balance in the SAMOS account amounted
R245 788 840.06 reflected in the trial balance as the amount in the VBS
173.5 Truter testified that the audit clerks from KPMG could not obtain
and could have also easily obtained such a statement without the
173.6 Truter dealt with Nduli, the KPMG third year audit clerk, during the 2017
audit. He confirmed that Nduli was pressing for audit information that
Malaba’s version and denied Malaba’s assertion that all that was
conclude the audit but Truter did not provide it to her and, in fact, he
173.12 Truter attended the audit committee meeting on 30 June 2017 when the
mentioned.
and its financial performance and cash flows for the year then ended in
them to complete the cash audit. They were even unable to identify the
actual bank accounts that were recorded in the general ledger by their
difference between the general ledger amount and the bank statement
amount. He testified that his first iteration of the working paper in that
175.5 Nduli was then questioned on the fact that the amount reflected in the
R413 965 858.59, was not remotely in line with the balance on the
Manager of VBS but he had not been provided with a copy. However, on
saw the statement in the file and noted the "massive" difference.
175.6 Once he had established that there was a very substantial difference he
175.9.1 The working paper, in the form that appears in the audit file, was
175.9.2 He had moved the differences over to the statement column having
cash".
175.9.3 The fact that "the partner was comfortable that there was no difference
informed me that my working paper was not correct in its prior iteration
175.10 Upon the resumption of his interview on 25 June 2018, Nduli stated that
after Munalula had reported to him that Malaba said he was comfortable
"As a result of that I then changed this working paper, on the basis that: the audit has been signed, there are no differences on cash, and let me just make sure I document this thing in terms, first
had left it some weeks earlier. It was at that stage that he moved the
inserted the notes N1 and N2. Note N1 reads "Specific procedures were
performed by the Partner and CEO respectively", which note relates inter
175.12 He then testified that during August 2017 the KPMG regulatory audit
team, which was auditing VBS’ DI returns for 31 March 2017, had
around the cash – the same issues I had picked up around the cash". He
stated that this gave rise to a telephonic discussion between Krieg of the
Krieg that "he was going to sort it out or it was going to be sorted out".
175.13 He testified that he was most concerned at this stage and he raised his
he added the words "by the Partner and CEO respectively". He stated that
it would be best to obtain his laptop from KPMG to see precisely how and
had to close out this file and I also recall then also making sure that I
covered myself".
176.1 She is a qualified chartered accountant and was the Audit Manager for
the VBS audit on 2017. She has been on secondment with KPMG South
there was a clear and evident discrepancy between the available bank
statements and the amounts set out in the general ledger. She said that,
176.4 She made the original version of her draft report to the audit committee
changes to her draft, and in particular she pointed out that on page 5
176.5 She testified further that on 17 July 2017 she had addressed an sms to
"Hi Sipho
Are you okay for the VBS opinion to be signed in light of the EMID report still outstanding and also if you’re happy that cash is fine? They want to print today."
176.7 She testified that she had asked Malaba if he was happy to sign off the
176.8 She stated that she had instructed Nduli to make a reference in his audit
working paper to "say where the partner had audited". She testified that
would be dealing with cash. She explained that this was not required:
176.12 She explained that she had used the words "not all bank reconciliations
have been received" in her draft report to the audit committee rather than
had specifically told her that "it was no longer outstanding" and "it had
been resolved".
"He said: Okay, you can give it to her. Then I said: But, remember, you said you were doing this work. Then he said: Oh yes, I did, hey. Okay, I’ll give her a call, I’ll talk to her about it".
177.1 He was a first-year audit clerk in the employ of KPMG during the 2017
audit of VBS. It was his first bank audit. He was involved in several
but by the time he left the audit engagement he had not yet received the
177.3 He explained that the "testing procedure" for the cash audit entails a letter
being sent to the external bank requesting that bank to state the balance
177.4 When he was initially assigned to cash and bank, he was to test the
balance of cash and bank as at 31 March 2017. The starting point is."
various banks and the South African Reserve Bank and that the SAMOS
account can be accessed by the relevant bank. He said "from there you
can request a statement from any date. That can be generated at the
statement.
relevant institutions.
end from the relevant banks. He confirmed that these letters are the
177.6.4 He also explained that the letters that were provided followed
which had the account name and account number on, so "that when
I actually receive the balance from the client I can populate that further
sought in the first place and which would constitute proper audit
date he was no longer on the audit and was, in fact, on leave. The e-
that he would not rely on them as audit evidence. He was asked what
step he would have taken, had he been given this document during
that:
177.7 He was asked what he would have done if he had seen the divergence
between the amount in the SAMOS statement and the amount stated
178.1 She was previously employed by KPMG and was a second year audit clerk
in the 2017 VBS audit. She was involved in various aspects of the
obtain all the bank statements, record the amounts recorded by the client
against the amounts in the statements and assess the difference, if any.
auditors. She stated that usually the auditors draft these letters and
then request the client to put it on the client’s letterhead and sign it.
The auditors will then send the letters to the banks or log a request
178.2.2 It is essential that these confirmations are received directly from the
VBS in "dribs and drabs" and was not complete. She stated that she
Niewoudt, from Standard Bank and that the statements that she had
when she was working on cash and bank were internal and were not
178.2.4 She agreed that the statements by ABSA and Standard Bank,.
and she stated that she had never seen this statement before. She
178.2.8 She confirmed that, had she seen the SAMOS statement, she would
She also stated that a difference of such magnitude should have been
178.2.9 When Monare rolled off the audit she handed over her "workings" to
Nduli. At that stage she had very few bank statements and no external
178.2.10 In addition, the working paper that is in the e-audit file is very
different from the working paper that she left when she rolled off
("the EQCR partner"). He had been involved in the VBS audit for a
number of years prior to 2017. He testified that the role of the EQCR
partner is "to review and then see that the quality of the work is
conducted his role solely in the KPMG offices and has never met any of
179.2 He said he had no involvement in reviewing the cash section of the audit
file and that it had not been identified in the audit planning as a
significant risk area. Accordingly, he did not look at any of the relevant
"However, when I did look at the screen and saw the comment there, I was shattered. There didn’t appear to be audit evidence supporting the cash and bank".
179.3 He stated that auditing cash and bank is a simple process and
big balances, the team would have called for bank certificates from the
external banks.
179.4 After his retirement in February 2018 he had no access to any KPMG
files, but that KPMG had granted him access to the e-audit file for
179.5 He was then taken through the cash and bank working paper. In this
179.5.1 The 2017 working paper differs substantially from the 2016 working
paper.
179.5.4 He stated that he "was shattered" when he saw that note. When asked
"if the engagement partner is having difficulties with it, and it becomes an
179.7 He was given the gist of the evidence given by Nduli, Munalula and
Malaba and the disputes were pointed out to him. He was told how
179.11 He was then asked about issues concerning VBS’ equity position. He
stated that this was not included in his EQCR review. He agreed that the
179.12 Broom was referred to the 2017 annual financial statements and taken
contract finance book was not kept on the EMID system but in Excel and
he stated that he was not aware of that but that it would have been a
179.13 He was "very surprised" to hear that VBS had been placed under
the KPMG Risk Management Partner, who told him about the lack of
audit evidence and "the R800 million". They agreed to meet at KPMG’s
offices the following week. He then contacted Malaba, who suggested that
loans with VBS at that meeting. He stated that Malaba told him they were
discussed "some of the issues" and he then learned "from the firm" that
their wives’ companies) totalled some R28 million. He then realised that".
that they audit, unless such banks are security exchange clients,
provided that such loans or facilities are "in the ordinary course of
special terms and not be funded, or special interest rates or anything like
that". He testified that if such loans are not in the normal course of
had declared that he was independent and that "no violations or special
dispensations exist".
his articles at KPMG. After stints at various other firms after he qualified,
partner for the VBS audit about five or six years ago.
being Truter. At the outset he stated that he recalled that there was an
180.3 He said that he thought that his discussion with Truter was the last that
he had heard from either the manager or from Truter in this regard. It is
point when he last discussed the matter with Truter and that it related
stated:
180.5 Malaba testified about the draft report to the audit committee that
2 It is important to note that Malaba knew that the bank needed to do the reconciliation.
been received" was to be deleted and that this deletion was required by
him before the report went to the audit committee. When asked why that
180.9 The version given by Truter to in the course of his evidence about their
180.10 Malaba testified that he had comfort in signing off the 2017 annual
Munalula and Broom and that neither of them raised a red flag on any
issue.
the outstanding reconciliation item in the draft audit report and at the
time that he signed off the annual financial statements, the reconciliation
that he told Truter to do had in fact not been done. But for his removal
contact person and a signatory for several of the accounts. Thus, when
180.14 Malaba testified that Ihaawu Lesizwe is a company owned by his wife,
account with VBS. Malaba and his wife are signatories on all these
180.15 Malaba stated that his wife and his cousin are the shareholders and
financed in terms of the same type of contract as the Evoque had been
Benz and that, while debit orders were continuously reversed, no steps
were taken by VBS. He simply testified that he did not know why VBS did
not take any steps to exercise its rights in the event of default.
R7 322 484.30 and that he made payment in respect thereof from his.
of R250 000 into Ihaawu Lesizwe’s mortgage bond account, which then
brought that account up to date. He, however, testified that he has "not
a clue" who Khavho Enterprises is and that he did not notice that the
disguised payments on behalf of VBS and Vele. This was put to him, but
and from Robvet, in the sum of R90 000. As previously stated, Robvet
has been clearly identified as a slush fund. Once again, Malaba said he
never noticed these payments coming into the mortgage bond account.
money stolen from VBS found its way into an account held and used for
180.23 He confirmed that Ihaawu Lesizwe obtained an overdraft facility with VBS
and that the use of that facility was for his personal benefit. The facility
was initially granted in the amount of R2 million. He stated that the limit
R8 million and finally to R11 million. By the date of the curatorship the
excess of R11.5 million. From the date of the opening of that account,
being 27 January 2016, not one single cent has ever been paid into the
same day he paid R1 465 186 to Oxford University as tuition fees for a
"went for university fees again, and I had to pay for air tickets, school fees
180.25 He was asked how, when he was so "over-stretched" that he was unable
bond, he was able to obtain ever increasing overdraft facilities which were
the facility was "more flexible". He was also asked why VBS took no
recovery steps when the facility was used up to the hilt while no payments
were being made into it to service it. He answered that "it was in its
permitted to do.
180.26 He steadfastly denied, despite all of this, that the facilities granted to him
through Ihaawu Lesizwe were "soft" facilities and that the absence of any
steps being taken against him was solely due to his very close
180.27 He stated that when requesting the increases in the facility he did so by
Matodzi. He stated that they would then presumably send the requests
did not, however, produce these applications when they were demanded.
His evidence later shifted and he stated that, when the increases were
granted, he did not provide any supporting documents and his credit
180.28 He also stated that in November 2017 the facility was again increased by
a further R3 million, despite the fact that he was already in breach of the
communications did not find their way into VBS’ records. He was unable
obvious to me that this was part of the scheme to hide his involvement
as much as possible.
record of what the facility is, on what basis a credit lending decision is
made and there is no facility letter. There is, in fact, nothing more than a
that this e-mail stands in stark conflict with the evidence that he
facility.
his wife and the wife of Dumi Tshuma ("Tshuma"), his colleague at KPMG.
of the commencement of the curatorship. Once again, until that date not
a single cent had been paid into the Betanologix account to service it.
180.32 I note from the Betanologix bank statement that there was a single
payment of R200 000 out of that account to Tshuma, whereas there are
180.33 Malaba insisted that, because VBS embraced "black business" and
wanted to empower black people to start their own companies, VBS would
ensued:
MR MALABA: Yes.
overdraft facility and was not servicing the very substantial interest
some properties and that he may have been able to pay the facilities from
180.35 Malaba steadfastly denied that any of this was unusual. Eventually, after
the following was put to him, he conceded that he unduly benefited from
180.36 He confirmed that he did not disclose at the start of the 2017 VBS audit
that he had these facilities with VBS because "technically" he was not a
which the facilities were granted to him and the fact that no steps were
taken against him despite the massive arrears meant that these were not
loans made by the audit client bank "under normal lending procedures,
threshold for disclosure set by KPMG and imposed on its audit staff when
180.37 He conceded that a letter written, at his request, by the chief risk officer
180.38 Malaba was asked about a report, signed by him, relating to large
Ihaawu Lesizwe’s exposure by then was about R11 million, and thus to
reported on, this exposure was not included in the report simply because
it did not form part of the "data dump" provided by VBS management. I
serving.
180.39 Malaba’s counsel requested, and was given, the opportunity to re-
reverted to his earlier denial that he was provided with ever increasing
been able to repay R30 million worth of debt to VBS from his salary and
bonuses. Aside from Malaba laying all the blame for the failed cash and
181 During the course of the investigation it was submitted on behalf of Malaba
committed fraud.
185 I have come to the conclusion, based on a careful consideration of all of the
evidence that has been received, that Malaba was indeed complicit in the
185.1 I am mindful of the fact that Truter’s evidence must be approached with
regulatory audit and he thought that she was on the verge of discovering
audit, yet she did not take up those opportunities. However, I certainly
found her to be a far more honest and reliable witness than Malaba.
185.4 In the final analysis I find that the weight of all of the evidence, both by
deliberately disguised the fact that he was the beneficiary of the various
facilities. At the most basic level, had he been honest he would have
applied for facilities in his own name and not sought to hide them. The
Malaba well knew what his disclosure duties, aimed at warranting his
informed KPMG that he had done so, when he had not. All these things
knowing that the reconciliation that was solely intended to address the
massive cash shortfall that was escalated to him, had not been received
185.7 Munalula also sent him an SMS asking if he was happy to which he
185.8 The probabilities are heavily stark against Malaba. His version is simply.
for their active participation in the unlawfulness that engulfed VBS and
signing the audit opinion for the 2017 annual financial statements of
VBS, well knowing that the amounts reported in the financial statements
misstated.
185.10 I not only do not believe his version, but I reject it as well.
186 In all the circumstances, I find that Malaba approved and signed off on VBS’
financial statements for the year ended 31 March 2017, knowing of the
187 Before dealing with the evidence that has been obtained relating to the DI
returns that were made by VBS and the regulatory audit of those returns, it
(2) …
("the Regulations").
190 The reference to "the Registrar" in the Mutual Banks Act and in the
Act on 1 April 2018 the office of the Registrar was abolished and the functions
191 Regulation 6(1) requires that the auditor of a mutual bank shall annually
report on the mutual bank’s financial position and the result of its operations
Banks Act, referred to in Regulation 6(5) that had been submitted to the
Registrar as at the end of the financial year end of the reporting mutual bank.
192 Regulation 6(2) requires the auditor to report whether in his opinion the
accounting and other records at the reporting date has been extracted
extracted from, the accounting and other records at the reporting date;
and
192.4 was prepared using the same accounting policies as those contained in
193 Regulation 6(5) requires that the audit report contemplated in Regulation 6(1)
from time to time by the South African Institute of Chartered Accountants and
600, DI 700, DI 701, DI 702 and DI 704 submitted in respect of the reporting
bank’s operations.
194 VBS submitted the returns required in terms of section 53 of the Mutual
Banks Act, read with the Regulations, in respect of the month ending
195 Truter testified that there were many errors in the DI reporting due to the fact
that Deale had left VBS’ employ and there was simply not enough and
from PWC and KMPG trainees. In the course of the regulatory audit KPMG
the management report that it required to be reported in the same way it had
from a further enquiry into what might be inside those accounts if they were
196 One of the returns that was submitted was the Form DI 100 return ("the
DI 100 return"), which requires a setting out of VBS’ monthly balance sheet
197 The evidence discloses that at the time of the submission of the DI 100 return
for the month ended 31 March 2017, Truter and Mukhodobwane were aware
that the DI 100 return was false in at least the following respects:
198 The remaining amount of approximately R700 000 000 represented monies
aware that, in truth, there was no more than R4 300 000 in such accounts
which ought to have been recorded in line 74, column 1, of the DI 100 return
3 Regulation 17(2) provides that "amounts shall be shown to the nearest thousand units of currency, for example, R4 107 498 and R4 107 540 shall be reported as R4 107 and R4 108, respectively".
in addition to the amount "70,413" recorded in that line of the DI 100 return.
that:
207 She referred to the DI 100 return containing the balance sheet and explained
that R702 million of the R770 million reported there as "assets" in the form of
was not about whether the R702 million actually existed and finding audit
evidence in support of its existence, but rather about the manner in which its
208 Later, when she was again referred to this issue, Krieg testified that settlement
was then provided to Truter for his comments which were then simply
recorded.
215 Krieg confirmed that it assists in seeing the match between assets and
liabilities and that there is a liquidity issue, for example, when the bank has
lent out a lot of money long term and brought in a lot of money by way of
with the reporting obligations. She said that she did not know who submitted
Ntokozo, Ronewa", were responsible for completing the returns. She testified
that Mukhodobwane was responsible for the liquidity risk returns, that
Ronewa was the contact person for the "700 series" and that Truter was the:
220 Krieg was taken through Nduli’s working paper, the ultimate changes he made
and his evidence in that regard. She testified that she had never seen Nduli’s
226 Malaba testified that VBS’ submitting erroneous DI returns was "nothing new"
and they had been "struggling for years" with the DI returns. He stated that
this was due to Truter struggling with the DI returns and that Truter required
227 He confirmed that the reporting of the VBS Settlement Control Account and
the SAMOS account in the DI 100 return as "interbank" was incorrect and they
228 Malaba agreed that the reporting, in the DI 300 return, of R770 866 000 as
"deposits held" was incorrect as it included the R702 866 000 which ought to
have been reported as "other assets" and thus should not have been included
229 He also agreed that the proposition that the reporting of the settlement
accounts in the manner that VBS reported them obfuscated the fact that
230 Malaba confirmed that he wanted to give the regulatory audit report a "soft
landing" in the sense that he wanted to meet with the Reserve Bank first
231 He recalled that at the Tri-lateral meeting Matodzi was "flippant about the
232 Truter and Mukhodobwane were at the center of the fraudulent manipulation
difficult for the Registrar to obtain a clear picture of VBS’ actual risk profile.
The misdescription in the DI 100 return of the SAMOS account and the VBS
contends that he did not know the precise amount of the misstatement.
234.4 Thus, when Malaba was required to sign the regulatory audit reports that
the errors and irregularities that had been referred to in the reports and
234.5 I accordingly find that Malaba committed fraud by approving and signing
the report in terms of Regulation 6(1) in respect of the DI 100 return for
235 It was not possible, in the course of the interviews, to obtain a clear picture of
the precise amount that has been looted from VBS by its captors. Indeed, that
ascertain, with precision, the amounts that every participant in the looting
236 The forensic accountants have, however, set out in their report a detailed
analysis of cash flows which gives a far clearer and more accurate picture of
237 It emerges from the forensic accountants’ report that the amount of
R1 894 923 674 was gratuitously received from VBS by some fifty three
persons of interest, both natural and juristic, over the period 1 March 2015 to
238 Amongst the biggest recipients, directly and indirectly, of these gratuitous
payments are:
THE RECOMMENDATIONS
239 The investigation has revealed a wide range of criminality in the conduct of
the affairs of VBS. That is also so in regard to Vele. Indeed, it emerges very
clearly that VBS and Vele have been operated as a single criminal enterprise,
240 It is imperative that those who have been identified as participating and
charges against those that have been identified as being responsible for
financial statements for the year ended 31 March 2017, the submission
of the fraudulent DI returns for the month ended 31 March 2017 and the
Those frauds were perpetrated directly on the Registrar of Banks and the
241.2 The Prudential Authority, whether alone or together with the curator,
241.2.1 those that have been identified as being the perpetrators of the
241.2.2 those who benefitted from the receipt of funds through theft or fraud;
and
242 I recommend that the entirety of this report, including its appendices, be made
the perpetrators.
243 I further recommend that the Prudential Authority inform the South African
investigation to enable SARS to pursue both criminal charges and tax recovery
244 I recommend that the Prudential Authority disclose to the curator such parts
244.1 seek the grant of final orders of sequestration against those who have
and winding-up proceedings, against those who have benefitted from the
244.3 seek the intervention of the Asset Forfeiture Unit to preserve and
confiscate the proceeds of the crimes that have been committed; and
Prudential Authority, the curator and National Treasury against KPMG for
246 I also recommend that urgent steps be taken to wind-up VBS. It seems clear
core. Indeed, there is hardly a person in its employ in any position of authority | https://www.scribd.com/document/390564628/VBS-Mutual-Bank-The-Great-Bank-Heist | CC-MAIN-2019-39 | refinedweb | 11,126 | 65.96 |
Write Aura Components
Syntax Highlighting
The Aura Components Extension offers syntax highlighting for Aura markup, HTML, CSS, and JavaScript on .cmp, .component, .app files and more. This example shows syntax highlighting for JavaScript.
Code Completion
Invoke code completion with Ctrl+Space when you’re working with Aura markup. View additional information about tag names and attributes directly in the editor.
- Note: If you have any Lightning Web Components in your workspace, those components will also appear in the list of suggested completions. The Lightning Web Component suggestions will be displayed with the proper Aura syntax.
Attributes
View Component Documentation on Hover
Hovering over a component name or attribute shows component documentation in the editor, as well as links to the Component Library. You can see reference documentation for Aura components and Lightning web components nested within Aura components.
Here’s reference documentation for the
lightning:card component.
View or Jump to Definitions
You can preview, view, or go to definitions of:
- Aura Tags
- LWC Tags
- JavaScript
- Methods
- Variables.
Outline view
Outline view allows you to see the outline of your component—i.e. its HTML tags and JavaScript properties. Invoke it with Ctrl+Shift+O on Windows and Linux and Cmd+Shift+O on Mac.
Lightning Explorer (Beta)
As a beta feature, Lightning Explorer View. Lightning Explorer. The use of this feature is governed by the Salesforce.com Program Agreement. If you encounter any problems, or want to request an enhancement, open a Github issue.
Lightning Explorer lets you view reference documentation for both Aura components and Lightning web components. To enable it, go to Preferences > Settings. Enter
lightning explorer in the search bar. Then, click the checkbox next to salesforcedx-vscode-lightning:Show Lightning Explorer.
To use Lightning Explorer, click the lightning bolt icon on the left hand side of the screen. Click a namespace to see all of the available components. Lightning web components and Aura have different lightning icons.
Under the c namespace, we’ve selected the Lightning web component
c-wire-get-object-info. When you click on the name of the component, its corresponding file shows up in the main code panel.
Here’s the Aura component
force:inputField. The blue icon to the right of the component name opens your browser to the component reference in the Component Library.
Your custom Aura components and documentation are also available in the Aura Components extension. To learn more about writing documentation for your Aura components, see the Lightning Aura Components Developer Guide. | https://developer.salesforce.com/tools/vscode/articles/aura/writing | CC-MAIN-2019-39 | refinedweb | 416 | 50.12 |
Driving Adoption of a Design System
Design systems are emerging as a vital tool for product design at scale. These systems are collections of components, styles, and processes to help teams design and build consistent user experiences. It seems like everyone is building one, but there is no playbook on how to take it from the first button to a production-ready system adopted across an organization. Much of the advice and examples out there are for teams that seem to have already figured it out.
Today I want to share my experience in bootstrapping a design system and driving adoption within our organization, Segment. I will share how we got started by creating something small and useful first. Then I will share how I hijacked a project to build out that small thing into our full blown design system known as Evergreen. Finally, I will share how we continue to drive and track adoption of our design system.
What is a Design System?
A design system is a collection of components, styles and processes to help teams design and build consistent user experiences — faster and better. Design systems often contain components such as buttons, popovers and checkboxes, and foundational styles such as typography and colors. Teams that use the design system can focus on what’s unique to their product instead of reinventing common UI components.
What’s in our Design System
Before I share my experience bootstrapping our design system called Evergreen. I want to set some context first, and explain what is in our design system.
Design Resources
Sketch UI Kit
Design Guidelines
Code Resources
React UI Framework
Developer Documentation
Operational Resources
Roadmap documents
On-boarding process
Our design system didn’t start out with all of those resources. In fact, I built something small and useful first. In the next sections I will share the lessons I learned in bootstrapping a design system and driving adoption within our organization.
How We Got Started
About 2 years ago, I joined Segment as a product designer. I worked as a front-end developer in the past and I wanted to use my skillset to create interactive prototypes. To give you a bit of context, the Segment application allows our customers to collect data from your website or app, synthesize that data and integrate with over 200 integrations for marketing and analytics.
The prototypes I wanted to develop would live outside of our Segment application and would have no access to the application codebase..
Build something small and useful
One of the first challenges you run into when creating a component library is how to deal with styling and CSS. There are a few different ways to deal with this:
Traditional CSS: Verbose to write, hard to maintain at scale. Often relies on conventions.
CSS Preprocessor such as Sass or Less: Easier way to write CSS, chance of naming collisions. Often relies on conventions.
CSS-in-JS solutions: Write CSS in JavaScript. Powerful ways to abstract into components.
I wanted a solution that didn’t require any extra build steps or extra imports when using the component library. CSS-in-JS made this very easy. You can import a component in your code and it works out of the box.
I wanted to avoid having to create a ton of utility class names to override simple CSS properties on components such as dimensions, position and spacing. It turns out there is a way to achieve this in an elegant way — enter the React UI primitive.
Choosing React
There are many choices of frameworks for your component library. When I started building a component library, we were already using React, so it was the obvious choice.
React UI Primitive
After doing research, I found the concept of UI primitives. Instead of dealing with CSS directly, you deal with the properties on a React component. I bounced ideas off my coworkers and got excited about what this would mean. In the end we built UI-BOX.
UI-BOX
UI-BOX exports a single
Box component that allows you to use React props for CSS properties. Instead of creating a class name, you pass the property to the
Box component directly:
import Box from 'ui-box export default () => ( <Box height={240} Hello Box </Box> )
Why is this Box component useful?
The Box component is useful because it helps with 3 common use cases
Create layouts without helper classes.
Define components without worrying about CSS.
Override single properties when using components.
Create layouts without helper classes.
<Box display="flex" padding={16}> <Box flex={1} <Heading size={600}> Items </Heading> </Box> <Box> <Button appearance="primary" onClick={this.newItem}> New Item </Button> </Box> </Box>
Define components without worrying about CSS
import React from 'react' import Box from 'ui-box' export default function Button(props) { return ( <Box is="button" className="button-reset button-state" fontSize={14} paddingX={12} paddingY={8} {...props} ) }
Override single properties when using components
import React from 'react' import Box from 'ui-box' import Button from './Button' function ButtonExamples() { return ( <Box margin={40}> <Button marginRight={16}>Default</Button> <Button disabled marginRight={16}>Disabled</Button> <Button display="block" width="100%">Full Width</Button> </Box> ) }
Flexibility and composability
The
Box component makes it easy to start writing new components that allows setting margin properties directly to the component. For example, quickly space out two buttons by adding
marginRight={10} to the left button. Also, you can override CSS properties without adding new distinct properties to the component. For example, this is useful when full-width button is needed, or want to remove the border-radius on one side of a button. Furthermore, layouts can be created instantly by using the Box component directly.
Still a place for CSS
It is important to note that UI-BOX only solves some of the problems. A class is still needed to control the appearance of a component. For example, a button can add dimensions and spacing with UI-BOX, but a class defines the appearance: background color, box shadows, color as well as the hover, active and focus states. In our design system called Evergreen a CSS-in-JS library called Glamor is used to create appearance classes.
Why it drove adoption of Evergreen
A design system can start with something small and useful. In our case it was using a UI primitive that abstracted away dealing with CSS directly. Roland, one of our lead engineers said the following about UI-BOX.
UI-BOX really drove adoption of Evergreen…
…there is no need to consider every configuration when defining a new component. And no need to wrap components in divs for spacing.
— Roland Warmerdam, Lead Software Engineer, Segment
The lesson learned here is that it’s possible to start with something small and slowly grow that out to a full fledged design system. Don’t think you have time for that? Read the next section for some ideas.
How we started driving adoption
Up until now, I had built a tool for myself in my spare time, but it was still very much a side project. Smaller startups often can’t prioritize a design system as it doesn’t always directly align with business value. I will share how I hijacked a project, scaled out the system, and finally drove adoption across teams at Segment — and how you can do the same.
Hijack a project
About a year ago I switched teams within Segment. I joined a small team called Personas, which was almost like a small startup within Segment. With Personas we were building user profiles and audience capabilities on top of the Segment platform. It turned out to be a perfect opportunity to build out more of the design system.
Deadline in sight — our first user conference
The company wanted to announce the Personas product at our first ever user conference, with only 3 months of lead time to prepare. The idea was that our CEO and Head of Product would demo it on stage. However, there was no way we could finish a fully-baked consumer-facing product in time. We were pivoting too often based on customer feedback.
The company wanted to announce this product at our first ever user conference, with only 3 months of lead time to prepare.
Seize the opportunity
It seemed like an impossible deadline. Then it hit me: We could build a standalone prototype to power the on-stage demo. This prototype would be powered by fake data and only support just the functionality that was part of the demo.
This prototype would live outside of the confines of our application. This would allow us to build things quickly, but the downside is that there is no access to the code and components that live in our application codebase. Every component we want to use in the prototype needs to be built — a perfect opportunity to build out more of the design system. We decided it would be the lowest risk, highest reward option for us to pursue.
While we worked on the demo script for the on-stage demo, I was crunching away on the prototype and Evergreen. Having the prototype available and easily shareable made it easier for the team to practice and fine-tune the script. It was a great time at Segment; I could see the team and company growing closer while readying for launch.
Huge Success
The interactive prototype was a huge success. It helped us show the vision of what our product and Personas could be. It drove considerable interest to our newest product, Personas. I was happy, because not only did we have a interactive prototype, we also have the first parts of our design system.
Focus on the developer experience
So far, we built something small and useful and hijacked a project that allowed us to build out a big chunk of our design system, Evergreen. The prototype also proved to be a great way to drive adoption of Evergreen in our application. Our developers simply took code from the prototype and ported it over in our application.
At that point, Evergreen components were adopted in over 200 source code files. Our team was happy about the components, but there were some pain points with the way Evergreen was structured. When we started building Evergreen, we copied some of the architecture decisions of bigger design systems. That turned out to be a mistake. It slowed us down.
Too early for a mono-repo
When I started building Evergreen I took a lot of inspiration from Atlassian’s AtlasKit. It is one of the most mature and comprehensive enterprise design systems out there. We used the same mono-repo architecture for Evergreen, but it turns out there is quite a lot of overhead to when using a mono-repo.
Our developers were not happy with the large number of different imports in each file. There were over 20 different package dependencies. Maintaining these dependencies was painful. Besides unhappy developers, it was time-consuming to add new components.
A single dependency is better for us (for now)
I wanted to remove as much friction for our developers using Evergreen as possible, which is why I wanted to migrate away from the mono-repo. Instead, a single package would export all of our components as a single dependency.
Migrate our codebase in a single command
When we decided to migrate to a single package, it required updating the imports in all the places Evergreen was used in our application. At this point Evergreen was used in over 200 source code files in the Segment application. It seemed like a pretty daunting challenge, not something anyone got excited about doing manually. We started exploring our options and ways to automate the process, and to our surprise it was easier than we thought.
Babel parser to the rescue
We created a command line tool for our application that could migrate the hundreds of files of source code using Evergreen with one command. The syntax was transformed using a tool called b. Now it’s a much better experience for our developers in the application. In the end, our developers were happy.
Lesson Learned, Face the challenge
A big change like this can feel intimidating, and give you second doubts. Although I wish I started Evergreen with the architecture it has right now — sometimes the right choice isn’t clear up front. The most important thing is to learn and move forward.
Driving adoption of a design system is very challenging. It is hard to understand progress. We came up with a quite nifty way to visualize the adoption in our application — and in turn make data-driven decisions about the future of Evergreen.
How to get to 100% adoption
Within our company, teams operate on key metrics to get resources and show they are being successful to the rest of the company. One of the key metrics for Evergreen is 100% adoption in our application. What does 100% even mean? And how can we report on this progress?
What does 100% adoption even mean?
100% adoption at Segment means building any new products with Evergreen and deprecating our legacy UI components in favor of Evergreen components. The first part is the easiest as most teams are already using Evergreen to build new products. The second part is harder. How do we migrate all of our legacy UI components to Evergreen components?
What legacy UI components are in our app?
Active code bases will accrue a large number of components over time. In our case this comes in the form of legacy component libraries that live in the application codebase.
In our case it comes in the following two legacy libraries:
React UI Library, precursor to Evergreen.
Legacy UI folder, literally a folder called
uiin our codebase that holds some very old components.
Evergreen versions
In addition to the legacy libraries, the application is able to leverage multiple versions of Evergreen. This allows gradual migration from one version to another.
Evergreen v4, the latest and greatest version of Evergreen. We want 100% of this.
Evergreen v3, previous version of Evergreen. We are actively working on migrating this over to
v4.
How can we report on the progress of adoption?
The solution we came up with to report on the adoption of Evergreen is an adoption dashboard. At any single point in time the dashboard shows the following metrics:
Global Adoption, the current global state of adoption
Adoption Week Over Week, the usage of Evergreen (and other libraries) week over week
Component Usage, a treemap of each component sorted by framework. Each square is sized by how many times the component is imported in our codebase.
The Component Usage Treemap
Besides the aggregates, we know exactly which files import a component. To visualize this, a Treemap chart on the dashboard shows each component with the size of the square representing how many times it imported in our application.
Understand exactly where you are using a component
Clicking on one of the squares in the treemap shows a side sheet with a list of all the files which import that component. This information allows us to confidently deprecate components.
Filter down a list of low hanging fruit to deprecate
The adoption dashboard also helps to prioritize the adoption roadmap. For example, legacy components that are only imported once or twice are easy to deprecate.
How it works
Earlier I shared how we used babel-parser to migrate to the new import structure. Being true to our roots, we realized the same technique could be used to collect analytics for our design system! To get to the final adoption dashboard there are a few steps involved.
Step 1. Create a report by analyzing the codebase
We wrote a command line utility that returns a report by analyzing the import statements at the top of each file in our codebase. An index is built that maps these files to their dependencies. Then the index can be queried by package and optionally the export. Here is an example:
Command
$ dependency-report './client/**/*.js' --packages=evergreen-ui --exports=SideSheet
Output
[ [ { "name": "SideSheet", "files": 4, "filepaths": [ "./client/components/Destinations/ErrorSheet.js", "./client/components/Navigation/UserDropdown.js", "./client/components/Customers/DestinationSettings.js", "./client/components/WorkspaceSettings/RegulationSheet.js", ] } ] ]
We open-sourced this tool if you are interested in learning more or want to build out your own adoption dashboard see
Step 2. Create and save a report on every app deploy
Every time we deploy our application, the codebase is analyzed and a JSON report is generated using the
dependency-reporttool.
Once the report is generated, it is persisted to object storage (S3).
After persisting the report, a webhook triggers the rebuild of our dashboard via the Gatsby static site generator.
Step 3. Build the dashboard and load the data
To reduce the number of reports on the dashboard, the generator only retrieves the most current report as well as a sample report from each previous week. The latest report is used to show the current state. The reports of the previous weeks are used to calculate an aggregate for the week over week adoption chart.
How the adoption dashboard is pushing Evergreen forward
The adoption dashboard was the final piece in making Evergreen a success as it helped us migrate over old parts of our app systematically and with full confidence. It was easy to identify usage of legacy components in the codebase and know when it was safe to deprecate them. Our developers were also excited to see a visual representation of the progress. These days it helps us make data-driven decisions about the future of Evergreen and prioritize our roadmap. And honestly, it is pretty cool.
Conclusion
To those of you who are considering setting out on this journey, I’ll leave you with a few closing thoughts:
Start small. It’s important to show the value of a potential design system by solving a small problem first.
Find a real place to start. A design system doesn’t have value by itself. It only works when applied to a real problem.
Drive adoption and measure your progress. The real work starts once the adoption begins. Don’t forget that the real value is in adoption. Design systems are only valuable once they are fully integrated into the team’s workflow.
This is only the start of our journey. There are still many challenges ahead. Remember, building a design system is not about reaching a single point in time. It’s an ongoing process of learning, building, evangelizing and driving adoption in your organization. | https://segment.com/blog/driving-adoption-of-a-design-system/ | CC-MAIN-2019-18 | refinedweb | 3,102 | 55.03 |
while.
Putting the
BindableAttribute on a C++ ref class makes the class available for databinding. Unfortunately, if you add a very simple ref class and then mark it as
[Bindable], you’ll get some weird compiler error messages. Example – consider this simple bindable class defined in Restaurant.h.
namespace ViewModels { [Windows::UI::Xaml::Data::Bindable] public ref class Restaurant sealed { public: }; }
Assume there’s a Restaurant.cpp that includes this file. You’ll get these compiler errors (or something close to it).
Error 1 error C3083: 'ViewModels': the symbol to the left of a '::' must be a type ...\xamltypeinfo.g.cpp Error 2 error C2039: 'Restaurant' : is not a member of 'ViewModels' ...\xamltypeinfo.g.cpp Error 3 error C2061: syntax error : identifier 'Restaurant' ...\xamltypeinfo.g.cpp
The not so obvious fix for these errors is to include Restaurant.h in any of your xxx.xaml.h files (right after the include to the xxx.g.h file would be a good place). This seems to be due to how the XAML compiler ties into the whole build process. Not a major hassle, but more something to be aware of. | https://voidnish.wordpress.com/2013/03/15/compiler-errors-when-using-the-bindable-attribute/ | CC-MAIN-2016-40 | refinedweb | 189 | 68.47 |
Ian Lance Taylor
Robert Griesemer
March 19, 2021
This is the design for adding generic programming using type parameters to the Go language. This design has been proposed and accepted as a future language change. We currently expect that this change will be available in the Go 1.18 release in early 2022.
We suggest extending the Go language to add optional type parameters to type and function declarations. Type parameters are constrained by interface types. Interface types, when used as type constraints, permit listing the set of types that may be assigned to them. Type inference via a unification algorithm permits omitting type arguments from function calls in many cases. The design is fully backward compatible with Go 1.
This document is long. Here is some guidance on how to read it.
This section explains the changes suggested by the design very briefly. This section is intended for people who are already familiar with how generics would work in a language like Go. These concepts will be explained in detail in the following sections.
func F[T any](p T) { ... }.
type M[T any] []T.
func F[T Constraint](p T) { ... }.
anyis a type constraint that permits any type.
In the following sections we work through each of these language changes in great detail. You may prefer to skip ahead to the examples to see what generic code written to this design will look like in practice.
There have been many requests to add additional support for generic programming in Go. There has been extensive discussion on the issue tracker and on a living document.
This design suggests extending the Go language to add a form of parametric polymorphism, where the type parameters are bounded not by a declared subtyping relationship (as in some object oriented languages) but by explicitly defined structural constraints.
This version of the design has many similarities to a design draft presented on July 31, 2019, but contracts have been removed and replaced by interface types, and the syntax has changed.
There have been several proposals for adding type parameters, which can be found through the links above. Many of the ideas presented here have appeared before. The main new features described here are the syntax and the careful examination of interface types as constraints. simple examples.
Generic code is written using abstract data types that we call type parameters. When running the generic code, the type parameters are replaced by type arguments.
Here is a function that prints out each element of a slice, where the element type of the slice, here called
T, is unknown. This is a trivial example of the kind of function we want to permit in order to support generic programming. (Later we'll also discuss generic types).
// type parameter list appears before the regular parameters. To distinguish the type parameter list from the regular parameter list, the type parameter list uses square brackets rather than parentheses. Just as regular parameters have types, type parameters have meta-types, also known as constraints. We will discuss the details of constraints later; for now, we will just note that
any is a valid constraint, meaning that any type is permitted.
// Print prints the elements of any slice. // Print has a type parameter T and has a single (non-type) // parameter s which is a slice of that type parameter. func Print[T any](s []T) { // same as above }
This says that within the function
T is a type parameter, a type that is currently unknown but that will be known when the function is called. The
any means that
T can be any type at all. As seen above, the type parameter may be used as a type when describing the types of the ordinary non-type parameters. It may also be used as a type within the body of the function.
Unlike regular parameter lists, in type parameter lists names are required for the type parameters. This avoids a syntactic ambiguity, and, as it happens, there is no reason to ever omit the type parameter names.
Let‘s make our example slightly more complicated. Let’s turn it into a function that converts a slice of any type into a
[]string by calling a
String method on each element.
// This function is INVALID. func Stringify[T any](s []T) (ret []string) { for _, v := range s { ret = append(ret, v.String()) // INVALID } return ret }
This might seem OK at first glance, but in this example
v has type
T, and
T can be any type. This means that
T need not argument that does not have a
String method, the error is reported when compiling the call to
v.String with that type argument. These errors can be lengthy, as there may be several layers of generic function calls before the error occurs, all of which must be reported to understand what went wrong. expects the type arguments to meet certain requirements. We refer to these requirements as constraints (other languages have similar ideas known as type bounds or trait bounds or concepts). In this case, the constraint is pretty obvious: the type has to have a
String() string method. In other cases it may be much less obvious.
We don‘t want to derive the constraints from whatever
Stringify happens to do (in this case, call the
String method). If we did, a minor change to
Stringify might change the constraints. That would mean that a minor change could cause code far away, that calls the function, to unexpectedly break. It’s fine for
Stringify to deliberately change its constraints, and force callers to change. What we want to avoid is
Stringify changing its constraints accidentally.
This means that the constraints must set limits on both the type arguments passed by the caller and the code in the generic function. The caller may only pass type arguments that satisfy the constraints. The generic function may only use those values in ways that are permitted by the constraints. This is an important rule that we believe should apply to any attempt to define generic programming in Go: generic code can only use operations that its type arguments are known to implement.
Before we discuss constraints further, let's briefly note what happens when the constraint is
any. If a generic function uses the
any constraint for a type parameter, as is the case for the
v whose type is the type parameter
T, and it passes that variable to a function.
The operations permitted for any type are:
interface{}
Tto type
T(permitted but useless)
new
It's possible that future language changes will add other such operations, though none are currently anticipated.
Go already has a construct that is close to what we need for a constraint: an interface type. An interface type is a set of methods. The only values that can be assigned to a variable of interface type are those whose types implement the same methods. The only operations that can be done with a value of interface type, other than operations permitted for any type, are to call the methods.
Calling a generic function with a type argument is similar to assigning to a variable of interface type: the type argument must implement the constraints of the type parameter. Writing a generic function is like using values of interface type: the generic code can only use the operations permitted by the constraint (or operations that are permitted for any type).
Therefore, in this design, constraints are simply interface types. Implementing a constraint means implementing the interface type. (Later we'll see how to define constraints for operations other than method calls, such as binary operators).
For the
Stringify example, we need an interface type with a
String method that takes no arguments and returns a value of type
string.
// Stringer is a type constraint that requires the type argument to have // a String method and permits the generic function to call String. // The String method should return a string representation of the value. type Stringer interface { String() string }
(It doesn‘t matter for this discussion, but this defines the same interface as the standard library’s
fmt.Stringer type, and real code would likely simply use
fmt.Stringer.)
anyconstraint
Now that we know that constraints are simply interface types, we can explain what
any means as a constraint. As shown above, the
any constraint permits any type as a type argument and only permits the function to use the operations permitted for any type. The interface type for that is the empty interface:
interface{}. So we could write the
// Print prints the elements of any slice. // Print has a type parameter T and has a single (non-type) // parameter s which is a slice of that type parameter. func Print[T interface{}](s []T) { // same as above }
However, it‘s tedious to have to write
interface{} every time you write a generic function that doesn’t impose constraints on its type parameters. So in this design we suggest a type constraint
any that is equivalent to
interface{}. This will be a predeclared name, implicitly declared in the universe block. It will not be valid to use
any as anything other than a type constraint.
(Note: clearly we could make
any generally available as an alias for
interface{}, or as a new defined type defined as
interface{}. However, we don't want this design, which is about generics, to lead to a possibly significant change to non-generic code. Adding
any as a general purpose name for
interface{} can and should be discussed separately).
For a generic function, a constraint can be thought of as the type of the type argument: a meta-type. As shown above, constraints appear in the type parameter list as the meta-type of a type parameter.
// Stringify calls the String method on each element of s, // and returns the results. func Stringify[T Stringer](s []T) (ret []string) { for _, v := range s { ret = append(ret, v.String()) } return ret }
The single type parameter
T is followed by the constraint that applies to
T, in this case
Stringer.
Although the
Stringify example uses only a single type parameter, functions may have multiple type parameters.
// Print2 has two type parameters and two non-type parameters. func Print2[T1, T2 any](s1 []T1, s2 []T2) { ... }
Compare this to
// Print2Same has one type parameter and two non-type parameters. func Print2Same[T any](s1 []T, s2 []T) { ... }
In
Print2
s1 and
s2 may be slices of different types. In
Print2Same
s1 and
s2 must be slices of the same element type.
Just as each ordinary parameter may have its own type, each type parameter may have its own constraint.
// Stringer is a type constraint that requires a String method. // The String method should return a string representation of the value. type Stringer interface { String() string } // Plusser is a type constraint that requires a Plus method. // The Plus method is expected to add the argument to an internal // string and return the result. type Plusser interface { Plus(string) string } // ConcatTo takes a slice of elements with a String method and a slice // of elements with a Plus method. The slices should have the same // number of elements. This will convert each element of s to a string, // pass it to the Plus method of the corresponding element of p, // and return a slice of the resulting strings. func ConcatTo[S Stringer, P Plusser](s []S, p []P) []string { r := make([]string, len(s)) for i, v := range s { r[i] = p[i].Plus(v.String()) } return r }
A single constraint can be used for multiple type parameters, just as a single type can be used for multiple non-type function parameters. The constraint applies to each type parameter separately.
// Stringify2 converts two slices of different types to strings, // and returns the concatenation of all the strings. func Stringify2[T1, T2 Stringer](s1 []T1, s2 []T2) string { r := "" for _, v1 := range s1 { r += v1.String() } for _, v2 := range s2 { r += v2.String() } return r }
We want more than just generic functions: we also want generic types. We suggest that types be extended to take type parameters.
// Vector is a name for a slice of any element type. type Vector[T any] []T
A type‘s type parameters are just like a function’s type parameters.
Within the type definition, the type parameters may be used like any other type.
To use a generic type, you must supply type arguments. This is called instantiation. The type arguments appear in square brackets, as usual. When we instantiate a type by supplying type arguments for the type parameters, we produce a type in which each use of a type parameter in the type definition is replaced by the corresponding type argument.
// v is a Vector of int values. // // This is similar to pretending that "Vector[int]" is a valid identifier, // and writing // type "Vector[int]" []int // var v "Vector[int]" // All uses of Vector[int] will refer to the same "Vector[int]" type. // var v Vector[int]
Generic types can have methods. The receiver type of a method must declare the same number of type parameters as are declared in the receiver type's definition. They are declared without any constraint.
// Push adds a value to the end of a vector. func (v *Vector[T]) Push(x T) { *v = append(*v, x) }
The type parameters listed in a method declaration need not have the same names as the type parameters in the type declaration. In particular, if they are not used by the method, they can be
_.
A generic type can refer to itself in cases where a type can ordinarily refer to itself, but when it does so the type arguments must be the type parameters, listed in the same order. This restriction prevents infinite recursion of type instantiation.
// List is a linked list of values of type T. type List[T any] struct { next *List[T] // this reference to List[T] is OK val T } // This type is INVALID. type P[T1, T2 any] struct { F *P[T2, T1] // INVALID; must be [T1, T2] }
This restriction applies to both direct and indirect references.
// ListHead is the head of a linked list. type ListHead[T any] struct { head *ListElement[T] } // ListElement is an element in a linked list with a head. // Each element points back to the head. type ListElement[T any] struct { next *ListElement[T] val T // Using ListHead[T] here is OK. // ListHead[T] refers to ListElement[T] refers to ListHead[T]. // Using ListHead[int] would not be OK, as ListHead[T] // would have an indirect reference to ListHead[int]. head *ListHead[T] }
(Note: with more understanding of how people want to write code, it may be possible to relax this rule to permit some cases that use different type arguments.)
The type parameter of a generic type may have constraints other than
any.
// StringableVector is a slice of some type, where the type // must have a String method. type StringableVector[T Stringer] []T func (s StringableVector[T]) String() string { var sb strings.Builder for i, v := range s { if i > 0 { sb.WriteString(", ") } // It's OK to call v.String here because v is of type T // and T's constraint is Stringer. sb.WriteString(v.String()) } return sb.String() }
Although methods of a generic type may use the type's parameters, methods may not themselves have additional type parameters. Where it would be useful to add type arguments to a method, people will have to write a suitably parameterized top-level function.
There is more discussion of this in the issues section.
As we‘ve seen, we are using interface types as constraints. Interface types provide a set of methods, and nothing else. This means that with what we’ve seen so far, the only thing that generic functions can do with values of type parameters, other than operations that are permitted for any type, is call methods.
However, method calls are not sufficient for everything we want to express. Consider this simple function that returns the smallest element of a slice of values, where the slice is assumed to be non-empty.
// This function is INVALID. func Smallest[T any](s []T) T { r := s[0] // panic if slice is empty for _, v := range s[1:] { if v < r { // INVALID r = v } } return r }
Any reasonable generics implementation should let you write this function. The problem is the expression
v < r. This assumes that
T supports the
< operator, but the constraint on
T is simply
any. With the
any constraint the function
Smallest can only use operations that are available for all types, but not all Go types support
<. Unfortunately, since
< is not a method, there is no obvious way to write a constraint—an interface type—that permits
<.
We need a way to write a constraint a composite type or with an arbitrary defined type.
This means that rather than try to write a constraint for
<, we can approach this the other way around: instead of saying which operators a constraint should support, we can say which (underlying) types a constraint should accept.
An interface type used as a constraint may list explicit types that may be used as type arguments. This is done using the
type keyword followed by a comma-separated list of types.
For example:
// SignedInteger is a type constraint that permits any // signed integer type. type SignedInteger interface { type int, int8, int16, int32, int64 }
The
SignedInteger constraint specifies that the type argument must be one of the listed types. More precisely, either the type argument or the underlying type of the type argument must be identical to one of the types in the type list. This means that
SignedInteger will accept the listed integer types, and will also accept any type that is defined as one of those types.
When a generic function uses a type parameter with one of these constraints, it may use it in any way that is permitted by all of the listed types. This could mean operators like
<,
<-, or use in a
range loop, or in general any language construct. If the function can be compiled successfully using each type listed in the constraint, then the use is permitted.
A constraint may only have one type list.
For the
Smallest example shown earlier, we could use a constraint like this:
package constraints // Ordered is a type constraint that matches any ordered type. // An ordered type is one that supports the <, <=, >, and >= operators. type Ordered interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64, string }
In practice this constraint would likely be defined and exported in a new standard library package,
constraints, so that it could be used by function and type definitions.
Given that constraint, we can write this function, now valid:
// Smallest returns the smallest element in a slice. // It panics if the slice is empty. func Smallest[T constraints.Ordered](s []T) T { r := s[0] // panics if slice is empty for _, v := range s[1:] { if v < r { r = v } } return constraint that accepts any comparable type.
To do this we introduce a new predeclared type constraint:
comparable. A type parameter with the
comparable constraint accepts as a type argument any comparable type. It permits the use of
== and
!= with values of that type parameter.
For example, this function may be instantiated with any comparable type:
// Index returns the index of x in s, or -1 if not found. func Index[T comparable](s []T, x T) int { for i, v := range s { // v and x are type T, which has the comparable // constraint, so we can use == here. if v == x { return i } } return -1 }
Since
comparable, like all constraints, is an interface type, it can be embedded in another interface type used as a constraint:
// ComparableHasher is a type constraint that matches all // comparable types with a Hash method. type ComparableHasher interface { comparable Hash() uintptr }
The constraint
ComparableHasher is implemented by any type that is comparable and also has a
Hash() uintptr method. A generic function that uses
ComparableHasher as a constraint can compare values of that type and can call the
Hash method.
It's possible to use
comparable to produce a constraint that can not be satisfied by any type.
// ImpossibleConstraint is a type constraint that no type can satisfy, // because slice types are not comparable. type ImpossibleConstraint interface { comparable type []int }
This is not in itself an error, but of course there is no way to instantiate a type parameter that uses such a constraint.
Interface types with type lists may only be used as constraints on type parameters. They may not be used as ordinary interface types. The same is true of the predeclared interface type
comparable.
This restriction may be lifted in future language versions. An interface type with a type list may be useful as a form of sum type, albeit one that can have the value
nil.
A type argument satisfies a type constraint with a type list if the type argument or its underlying type is present in that type list. If in some future language version we permit interface types with type lists outside of type constraints, this rule will make them usable both as type constraints and as sum types. Using a list of defined types would mean that only those exact types would implement the interface, which is to say that only those exact types could be assigned to the sum type. Using a list of predeclared types and/or type literals would mean that any type defined as one of those types would implement the interface or be assignable to the sum type. There would be no way to write a sum type to accept only a predeclared type or type literal and reject types defined as those types. That restriction is likely acceptable for the cases where people want to use sum types.
Within a single type parameter list, constraints may refer to any of the other type parameters, even ones that are declared later in the same list. (The scope of a type parameter starts at the beginning of the type parameter list and extends to the end of the enclosing function or type declaration.) // NodeConstraint is the type constraint for graph nodes: // they must have an Edges method that returns the Edge's // that connect to this Node. type NodeConstraint[Edge any] interface { Edges() []Edge } // EdgeConstraint is the type constraint for graph edges: // they must have a Nodes method that returns the two Nodes // that this edge connects. type EdgeConstraint[Node any] interface { Nodes() (from, to Node) } // Graph is a graph composed of nodes and edges. type Graph[Node NodeConstraint[Edge], Edge EdgeConstraint[Node]] struct { ... } // New returns a new graph given a list of nodes. func New[Node NodeConstraint[Edge], Edge EdgeConstraint[Node]] (nodes []Node) *Graph[Node, Edge] { ... } // ShortestPath returns the shortest path between two nodes, // as a list of edges. func (g *Graph[Node, Edge]) ShortestPath(from, to Node) []Edge { ... }
There are a lot of type arguments and instantiations here. In the constraint on
Node in
Graph, the
Edge being passed to the type constraint
NodeConstraint is the second type parameter of
Graph. This instantiates
NodeConstraint with the type parameter
Edge, so we see that
Node must have a method
Edges that returns a slice of
Edge, which is what we want. The same applies to the constraint on
Edge, and the same type parameters and constraints are repeated for the function
New. We aren't claiming that this is simple, but we are claiming that it is possible.
It‘s worth noting that. In particular, the methods do not return interface types.
For example, consider these type definitions in some other package:
// Vertex is a node in a graph. type Vertex struct { ... } // Edges returns the edges connected to v. func (v *Vertex) Edges() []*FromTo { ... } // FromTo is an edge in a graph. type FromTo struct { ... } // Nodes returns the nodes that ft connects. constraints of
graph.Graph. Note that we couldn't pass plain
Vertex or
FromTo to
graph.New, since
Vertex and
FromTo do not implement the constraints. The
Edges and
Nodes methods are defined on the pointer types
*Vertex and
*FromTo; the types
Vertex and
FromTo do not have any methods.
When we use a generic interface type as a constraint, we first instantiate the type with the type argument(s) supplied in the type parameter list, and then compare the corresponding type argument against the instantiated constraint. In this example, the
Node type argument to
graph.New has a constraint
NodeConstraint[Edge]. When we call
graph.New with a
Node type argument of
*Vertex and an
Edge type argument of
*FromTo, in order to check the constraint on
Node the compiler instantiates
NodeConstraint with the type argument
*FromTo. That produces an instantiated constraint, in this case a requirement that
Node have a method
Edges() []*FromTo, and the compiler verifies that
*Vertex satisfies that constraint. type constraints..
In many cases we can use type inference to avoid having to explicitly write out some or all of the type arguments. We can use function argument type inference for a function call to deduce type arguments from the types of the non-type arguments. We can use constraint type inference to deduce unknown type arguments from known type arguments.
In the examples above, when instantiating a generic function or type, we always specified type arguments for all the type parameters. We also permit specifying just some of the type arguments, or omitting the type arguments entirely, when the missing type arguments can be inferred. When only some type arguments are passed, they are the arguments for the first type parameters in the list.
For example, a function like this:
func Map[F, T any](s []F, f func(F) T) []T { ... }
can be called in these ways. (We'll explain below how type inference works in detail; this example is to show how an incomplete list of type arguments is handled.)
var s []int f := func(i int) int64 { return int64(i) } var r []int64 // Specify both type arguments explicitly. r = Map[int, int64](s, f) // Specify just the first type argument, for F, // and let T be inferred. r = Map[int](s, f) // Don't specify any type arguments, and let both be inferred. r = Map(s, f)
If a generic function or type is used without specifying all the type arguments, it is an error if any of the unspecified type arguments cannot be inferred.
produces more readable code.)
Type inference is based on type unification. Type unification applies to two types, either or both of which may be or contain type parameters.
Type unification works by comparing the structure of the types. Their structure disregarding type parameters must be identical, and types other than type parameters must be equivalent. A type parameter in one type may match any complete subtype in the other type. If the structure differs, or types other than type parameters are not equivalent, then type unification fails. A successful type unification provides a list of associations of type parameters with other types (which may themselves be or contain type parameters).
For type unification, two types that don‘t contain any type parameters are equivalent if they are identical, or if they are channel types that are identical ignoring channel direction, or if their underlying types are equivalent. It’s OK to permit types to not be identical during type inference, because we will still check the constraints if inference succeeds, and we will still check that the function arguments are assignable to the inferred types.
For example, if
T1 and
T2 are type parameters,
[]map[int]bool can be unified with any of the following:
[]map[int]bool
T1(
T1matches
[]map[int]bool)
[]T1(
T1matches
map[int]bool)
[]map[T1]T2(
T1matches
int,
T2matches
bool)
(This is not an exclusive list, there are other possible successful unifications.)
On the other hand,
[]map[int]bool cannot be unified with any of
int
struct{}
[]struct{}
[]map[T1]string
(This list is of course also not exclusive; there are an infinite number of types that cannot be successfully unified.)
In general we can also have type parameters on both sides, so in some cases we might associate
T1 with, for example,
T2, or
[]T2.
Function argument type inference is used with a function call to infer type arguments from non-type arguments. Function argument type inference is not used when a type is instantiated, and it is not used when a function is instantiated but not called.
To see how it works, let's go back to the example of a call to the simple
Print[int]([]int{1, 2, 3})
The type argument
int in this function call can be inferred from the type of the non-type argument.
The only type arguments that can be inferred are those that are used for the types of the function‘s (non-type) input parameters. If there are some type parameters that are used only for the function’s result parameter types, or only in the body of the function, then those type arguments cannot be inferred using function argument type inference.
To infer function type arguments, we unify the types of the function call arguments with the types of the function‘s non-type parameters. On the caller side we have the list of types of the actual (non-type) arguments, which for the
[]int. On the function side is the list of the types of the function’s non-type parameters, which for
[]T. In the lists, we discard respective arguments for which the function side does not use a type parameter. We must then apply type unification to the remaining argument types.
Function argument type inference is a two-pass algorithm. In the first pass, we ignore untyped constants on the caller side and their corresponding types in the function definition. We use two passes so that in some cases later arguments can determine the type of an untyped constant.
We unify corresponding types in the lists. This will give us an association of type parameters on the function side to types on the caller side. If the same type parameter appears more than once on the function side, it will match multiple argument types on the caller side. If those caller types are not equivalent, unify the remaining types
// Map calls the function f on every element of the slice s, // returning a new slice of the results. func Map[F, T any](s []F, f func(F) T) []T { r := make([]T, len(s)) for i, v := range s { r[i] = f(v) } return r }
The two type parameters
F and
T are both used for input parameters, so function argument type inference is possible. In the call
strs := Map([]int{1, 2, 3}, strconv.Itoa)
we unify
[]int with
[]F, matching
F with
int. We unify the type of
strconv.Itoa, which is
func(int) string, with
func(F) T, matching
F with
int and
T with
string. The type parameter
F is matched twice, both times with
int. Unification succeeds, so the call written as
Map is a call of
Map[int, string].
To see the untyped constant rule in effect, consider:
// NewPair returns a pair of values of the same type. func NewPair[F any](f1, f2 F) *Pair[F] { ... }
In the call
NewPair
F with
int, so the final call is
NewPair[int](1, 2).
In the call
NewPair(1, int64(2)) the first argument is an untyped constant, so we ignore it in the first pass. We then unify
int64 with
F. At this point the type parameter corresponding to the untyped constant is fully determined, so the final call is
NewPair[int64](1, int64(2)).
In the call
NewPair(1, 2.5) both arguments are untyped constants, so we move on the second pass. This time we set the first constant to
int and the second to
float64. We then try to unify
F with both
int and
float64, so unification fails, and we report a compilation error.
As mentioned earlier, function argument type inference is done without regard to constraints. First we use function argument type inference to determine type arguments to use for the function, and then, if that succeeds, we check whether those type arguments implement the constraints (if any).
Note that after successful function argument type inference, the compiler must still check that the arguments can be assigned to the parameters, as for any function call.
Constraint type inference permits inferring a type argument from another type argument, based on type parameter constraints. Constraint type inference is useful when a function wants to have a type name for an element of some other type parameter, or when a function wants to apply a constraint to a type that is based on some other type parameter.
Constraint type inference can only infer types if some type parameter has a constraint that has a type list with exactly one type in it. We call such a constraint a structural constraint, as the type list describes the structure of the type parameter. A structural constraint may also have methods in addition to the type list, but the methods are ignored by constraint type inference. For constraint type inference to be useful, the constraint type will normally refer to one or more type parameters.
Constraint type inference is applied after function argument type inference. It is only tried if there is at least one type parameter whose type argument is not yet known.
While the algorithm we describe here may seem complex, for typical concrete examples it is straightforward to see what constraint type inference will deduce. The description of the algorithm is followed by a couple of examples.
We start by creating a mapping from type parameters to type arguments. We initialize the mapping with all type parameters whose type arguments are already known, if any.
For each type parameter with a structural constraint, we unify the type parameter with the single type in the constraint's type list. This will have the effect of associating the type parameter with its constraint. We add the result into the mapping we are maintaining. If unification finds any associations of type parameters, we add those to the mapping as well. When we find multiple associations of any one type parameter, we unify each such association to produce a single mapping entry. If a type parameter is associated directly with another type parameter, meaning that they must both be matched with the same type, we unify the associations of each parameter together. If any of these various unifications fail, then constraint type inference fails.
After merging all type parameters with structural constraints, we have a mapping of various type parameters to types (which may be or contain other type parameters). We continue by looking for a type parameter
T that is mapped to a fully known type argument
A, one that does not contain any type parameters. Anywhere that
T appears in a type argument in the mapping, we replace
T with
A. We repeat this process until we have replaced every type parameter.
For an example of where constraint type inference is useful, let's consider a function that takes a defined type that is a slice of numbers, and returns an instance of that same defined type in which each number is doubled.
Using type lists, it's easy to write a function similar to this if we ignore the defined type requirement.
// Double returns a new slice that contains all the elements of s, doubled. func Double[E constraints.Number](s []E) []E { r := make([]E, len(s)) for i, v := range s { r[i] = v + v } return r }
However, with that definition, if we call the function with a defined slice type, the result will not be that defined type.
// MySlice is a slice of ints. type MySlice []int // The type of V1 will be []int, not MySlice. // Here we are using function argument type inference, // but not constraint type inference. var V1 = Double(MySlice{1})
We can do what we want by introducing a new type parameter.
// SC constraints a type to be a slice of some type E. type SC[E any] interface { type []E } // DoubleDefined returns a new slice that contains the elements of s, // doubled, and also has the same type as s. func DoubleDefined[S SC[E], E constraints.Number](s S) S { // Note that here we pass S to make, where above we passed []E. r := make(S, len(s)) for i, v := range s { r[i] = v + v } return r }
Now if we use explicit type arguments, we can get the right type.
// The type of V2 will be MySlice. var V2 = DoubleDefined[MySlice, int](MySlice{1})
Function argument type inference by itself is not enough to infer the type arguments here, because the type parameter E is not used for any input parameter. But a combination of function argument type inference and constraint type inference works.
// The type of V3 will be MySlice. var V3 = DoubleDefined(MySlice{1})
First we apply function argument type inference. We see that the type of the argument is
MySlice. Function argument type inference matches the type parameter
S with
MySlice.
We then move on to constraint type inference. We know one type argument,
S. We see that the type argument
S has a structural type constraint.
We create a mapping of known type arguments:
{S -> MySlice}
We then unify each type parameter with a structural constraint with the single type listed by that constraint. In this case the structural constraint is
SC[E] which has the single type
[]E, so we unify
S with
[]E. Since we already have a mapping for
S, we then unify
[]E with
MySlice. As
MySlice is defined as
[]int, that associates
E with
int. We now have:
{S -> MySlice, E -> int}
We then substitute
E with
int, which changes nothing, and we are done. The type arguments for this call to
DoubleDefined are
[MySlice, int].
This example shows how we can use constraint type inference to set a type name for an element of some other type parameter. In this case we can name the element type of
S as
E, and we can then apply further constraints to
E, in this case requiring that it be a number.
Consider this example of a function that expects a type
T that has a
Set(string) method that initializes a value based on a string.
// Setter is a type constraint that requires that the type // implement a Set method that sets the value from a string. type Setter interface { Set(string) } // FromStrings takes a slice of strings and returns a slice of T, // calling the Set method to set each returned value. // // Note that because T is only used for a result parameter, // function argument type inference does not work when calling // this function. func FromStrings[T Setter](s []string) []T { result := make([]T, len(s)) for i, v := range s { result[i].Set(v) } return result }
Now let's see some calling code (this example is invalid).
// Settable is an integer type that can be set from a string. type Settable int // Set sets the value of *p from a string. func (p *Settable) Set(s string) { i, _ := strconv.Atoi(s) // real code should not ignore the error *p = Settable(i) } func F() { // INVALID nums := FromStrings[Settable]([]string{"1", "2"}) // Here we want nums to be []Settable{1, 2}. ... }
The goal is to use
FromStrings to get a slice of type
[]Settable. Unfortunately, this example is not valid and will not compile.
The problem is that
FromStrings requires a type that has a
Set(string) method. The function
F is trying to instantiate
FromStrings with
Settable, but
Settable does not have a
Set method. The type that has a
Set method is
*Settable.
So let's rewrite
F to use
*Settable instead.
func F() { // Compiles but does not work as desired. // This will panic at run time when calling the Set method. nums := FromStrings[*Settable]([]string{"1", "2"}) ... }
This compiles but unfortunately it will panic at run time. The problem is that
FromStrings creates a slice of type
[]T. When instantiated with
*Settable, that means a slice of type
[]*Settable. When
FromStrings calls
result[i].Set(v), that invokes the
Set method on the pointer stored in
result[i]. That pointer is
nil. The
Settable.Set method will be invoked with a
nil receiver, and will raise a panic due to a
nil dereference error.
The pointer type
*Settable implements the constraint, but the code really wants to use the non-pointer type
Settable. What we need is a way to write
FromStrings such that it can take the type
Settable as an argument but invoke a pointer method. To repeat, we can‘t use
Settable because it doesn’t have a
Set method, and we can‘t use
*Settable because then we can’t create a slice of type
Settable.
What we can do is pass both types.
// Setter2 is a type constraint that requires that the type // implement a Set method that sets the value from a string, // and also requires that the type be a pointer to its type parameter. type Setter2[B any] interface { Set(string) type *B } // FromStrings2 takes a slice of strings and returns a slice of T, // calling the Set method to set each returned value. // // We use two different type parameters so that we can return // a slice of type T but call methods on *T aka PT. // The Setter2 constraint ensures that PT is a pointer to T. func FromStrings2[T any, PT Setter2[T]](s []string) []T { result := make([]T, len(s)) for i, v := range s { // The type of &result[i] is *T which is in the type list // of Setter2, so we can convert it to PT. p := PT(&result[i]) // PT has a Set method. p.Set(v) } return result }
We can then call
FromStrings2 like this:
func F2() { // FromStrings2 takes two type parameters. // The second parameter must be a pointer to the first. // Settable is as above. nums := FromStrings2[Settable, *Settable]([]string{"1", "2"}) // Now nums is []Settable{1, 2}. ... }
This approach works as expected, but it is awkward to have to repeat
Settable in the type arguments. Fortunately, constraint type inference makes it less awkward. Using constraint type inference we can write
func F3() { // Here we just pass one type argument. nums := FromStrings2[Settable]([]string{"1", "2"}) // Now nums is []Settable{1, 2}. ... }
There is no way to avoid passing the type argument
Settable. But given that type argument, constraint type inference can infer the type argument
*Settable for the type parameter
PT.
As before, we create a mapping of known type arguments:
{T -> Settable}
We then unify each type parameter with a structural constraint. In this case, we unify
PT with the single type of
Setter2[T], which is
*T. The mapping is now
{T -> Settable, PT -> *T}
We then replace
T with
Settable throughout, giving us:
{T -> Settable, PT -> *Settable}
After this nothing changes, and we are done. Both type arguments are known.
This example shows how we can use constraint type inference to apply a constraint to a type that is based on some other type parameter. In this case we are saying that
PT, which is
*T, must have a
Set method. We can do this without requiring the caller to explicitly mention
*T.
Even when constraint type inference is used to infer type arguments based on constraints, we must still check the constraints after the type arguments are determined.
In the
FromStrings2 example above, we were able to deduce the type argument for
PT based on the
Setter2 constraint. But in doing so we only looked at the type list, we didn't look at the methods. We still have to verify that the method is there, satisfying the constraint, even if constraint type inference succeeds.
For example, consider this invalid code:
// Unsettable is a type that does not have a Set method. type Unsettable int func F4() { // This call is INVALID. nums := FromString2[Unsettable]([]string{"1", "2"}) ... }
When this call is made, we will apply constraint type inference just as before. It will succeed, just as before, and infer that the type arguments are
[Unsettable, *Unsettable]. Only after constraint type inference is complete will we check whether
*Unsettable implements the constraint
Setter2[Unsettable]. Since
*Unsettable does not have a
Set method, constraint checking will fail, and this code will not compile.
It can be useful for a generic function to require a type argument with a method whose argument is the type itself. For example, this arises naturally in comparison methods. (Note that we are talking about methods here, not operators.) Suppose we want to write an
Index method that uses an
Equal method to check whether it has found the desired value. We would like to write that like this:
// Index returns the index of e in s, or -1 if not found. func Index[T Equaler](s []T, e T) int { for i, v := range s { if e.Equal(v) { return i } } return -1 }
In order to write the
Equaler constraint, we have to write a constraint that can refer to the type argument being passed in. The easiest way to do this is to take advantage of the fact that a constraint does not have to be a defined type, it can simply be an interface type literal. This interface type literal can then refer to the type parameter.
// Index returns the index of e in s, or -1 if not found. func Index[T interface { Equal(T) bool }](s []T, e T) int { // same as above }
This version of
Index would be used with a type like
equalInt defined here:
// equalInt is a version of int that implements Equaler. type equalInt int // The Equal method lets equalInt implement the Equaler constraint. func (a equalInt) Equal(b equalInt) bool { return a == b } // indexEqualInts returns the index of e in s, or -1 if not found. func indexEqualInt(s []equalInt, e equalInt) int { // The type argument equalInt is shown here for clarity. // Function argument type inference would permit omitting it. return Index[equalInt](s, e) }
In this example, when we pass
equalInt to
Index, we check whether
equalInt implements the constraint
interface { Equal(T) bool }. The constraint has a type parameter, so we replace the type parameter with the type argument, which is
equalInt itself. That gives us
interface { Equal(equalInt) bool }. The
equalInt type has an
Equal method with that signature, so all is well, and the compilation succeeds. look back at our earlier example of
FromStrings2. When it is instantiated with type
Settable, it returns a value of type
[]Settable. For example, we can write
// Settable is an integer type that can be set from a string. type Settable int // Set sets the value of *p from a string. func (p *Settable) Set(s string) { // same as above } func F() { // The type of nums is []Settable. nums := FromStrings2[Settable]([]string{"1", "2"}) // Settable can be converted directly to int. // This will set first to 1. first := int(nums[0]) ... }
When we call
FromStrings2 instantiated with the type
Settable we get back a
[]Settable. The elements of that slice will be
Settable values, which is to say, they will be integers. They will not be boxed, even though they were created and set by a generic function.
Similarly, when a generic type is instantiated it will have the expected types as components.
type Pair[F1, F2 any] struct { first F1 second F2 }
When this is instantiated, the fields will not be boxed, and no unexpected memory allocations will occur. The type
Pair[int, string] is convertible to
struct { first int; second string }.
Let's return now to type lists to cover some less important details that are still worth noting. These are not additional rules or concepts, but are consequences of how type lists work.
As seen earlier for
Setter2, a constraint may use both type lists and methods.
// StringableSignedInteger is a type constraint that matches any // type that is both 1) defined as a signed integer type; // 2) has a String method. type StringableSignedInteger interface { type int, int8, int16, int32, int64 String() string }
This constraint permits any type whose underlying type is one of the listed types, provided it also has a
String() string method. It's worth noting that although the
StringableSignedInteger constraint explicitly lists
int, the type
int will not itself be permitted as a type argument, since
int does not have a
String method. An example of a type argument that would be permitted is
MyInt, defined as:
// MyInt is a stringable int. type MyInt int // The String method returns a string representation of mi. func (mi MyInt) String() string { return fmt.Sprintf("MyInt(%d)", mi) }
Using a type list permits a generic function to use an operation that is permitted by all the types in the type list. However, that does not apply to methods. Even if every type in the type list supports the same method with the same signature, the generic function may not call that method. It may only call methods that are explicitly listed in the constraint, as explained in the previous section.
Here is an example of types with the same method. This example is invalid. Even though both
MyInt and
MyFloat have a
String method, the
ToString function is not permitted to call that method.
// MyInt has a String method. type MyInt int func (i MyInt) String() string { return strconv.Itoa(int(i)) } // MyFloat also has a String method. type MyFloat float64 func (f MyFloat) String() string { return strconv.FormatFloat(float64(f), 'g', -1, 64) } // MyIntOrFloat is a type constraint that accepts MyInt or MyFloat. type MyIntOrFloat interface { type MyInt, MyFloat } // ToString converts a value to a string. // This function is INVALID. func ToString[T MyIntOrFloat](v T) string { return v.String() // INVALID }
To permit the
String method to be called, it must be explicitly listed in the constraint.
// MyIntOrFloatStringer accepts MyInt or MyFloat, and defines a String // method. Note that both MyInt and MyFloat have a String method. // If either did not have a String method, they would not satisfy the // constraint even though the type list lists them. To satisfy a // constraint a type must both match the type list (if any) and // implement all the methods (if any). type MyIntOrFloatStringer interface { type MyInt, MyFloat String() string } // ToString2 convers a value to a string. func ToString2[T MyIntOrFloatStringer](v T) string { return v.String() }
The reason for this rule is to simplify complex cases involving embedded type parameters in which it may not be immediately clear whether the type has a particular method or not.
A type in a constraint may be a type literal.
type byteseq interface { type string, []byte }
The usual rules apply: the type argument for this constraint may be
string or
[]byte or a type defined as one of those types; a generic function with this constraint may use any operation permitted by both
string and
[]byte.
The
byteseq constraint permits writing generic functions that work for either
string or
[]byte types.
// Join concatenates the elements of its first argument to create a // single value. sep is placed between elements in the result. // Join works for string and []byte types. func Join[T byteseq](a []T, sep T) (ret T) { if len(a) == 0 { // Use the result parameter as a zero value; // see discussion of zero value in the Issues section. return ret } if len(a) == 1 { // We know that a[0] is either a string or a []byte. // We can append either a string or a []byte to a []byte, // producing a []byte. We can convert that []byte to // either a []byte (a no-op conversion) or a string. return T(append([]byte(nil), a[0]...)) } // We can call len on sep because we can call len // on both string and []byte. n := len(sep) * (len(a) - 1) for _, v := range a { // Another case where we call len on string or []byte. n += len(v) } b := make([]byte, n) // We can call copy to a []byte with an argument of // either string or []byte. bp := copy(b, a[0]) for _, s := range a[1:] { bp += copy(b[bp:], sep) bp += copy(b[bp:], s) } // As above, we can convert b to either []byte or string. return T(b) }
For composite types (string, pointer, array, slice, struct, function, map, channel) we impose an additional restriction: an operation may only be used if the operator accepts identical input types (if any) and produces identical result types for all of the types listed in the type list. To be clear, this additional restriction is only imposed when a composite type appears in a type list. It does not apply when a composite type is formed from a type parameter outside of a type list, as in
var v []T for some type parameter
T.
// structField is a type constraint with a list of structs that all // have a field named x. type structField interface { type struct { a int; x int }, struct { b int; x float64 }, struct { c int; x uint64 } } // This function is INVALID. func IncrementX[T structField](p *T) { v := p.x // INVALID: type of p.x is not the same for all types in list v++ p.x = v } // sliceOrMap is a type constraint for a slice or a map. type sliceOrMap interface { type []int, map[int]int } // Entry returns the i'th entry in a slice or the value of a map // at key i. This is valid as the result of the operator is always int. func Entry[T sliceOrMap](c T, i int) int { // This is either a slice index operation or a map key lookup. // Either way, the index and result types are type int. return c[i] } // sliceOrFloatMap is a type constraint for a slice or a map. type sliceOrFloatMap interface { type []int, map[float64]int } // This function is INVALID. // In this example the input type of the index operation is either // int (for a slice) or float64 (for a map), so the operation is // not permitted. func FloatEntry[T sliceOrFloatMap](c T) int { return c[1.0] // INVALID: input type is either int or float64. }
Imposing this restriction makes it easier to reason about the type of some operation in a generic function. It avoids introducing the notion of a value whose type is the union of a set of types found by applying some operation to each element of a type list.
(Note: with more understanding of how people want to write code, it may be possible to relax this restriction in the future.)
A type literal in a constraint can refer to type parameters of the constraint. In this example, the generic function
Map takes two type parameters. The first type parameter is required to have an underlying type that is a slice of the second type parameter. There are no constraints on the second slice parameter.
// SliceConstraint is a type constraint that matches a slice of // the type parameter. type SliceConstraint[T any] interface { type []T } // Map takes a slice of some element type and a transformation function, // and returns a slice of the function applied to each element. // Map returns a slice that is the same type as its slice argument, // even if that is a defined type. func Map[S SliceConstraint[E], E any](s S, f func(E) E) S { r := make(S, len(s)) for i, v := range s { r[i] = f(v) } return r } // MySlice is a simple defined type. type MySlice []int // DoubleMySlice takes a value of type MySlice and returns a new // MySlice value with each element doubled in value. func DoubleMySlice(s MySlice) MySlice { // The type arguments listed explicitly here could be inferred. v := Map[MySlice, int](s, func(e int) int { return 2 * e }) // Here v has type MySlice, not type []int. return v }
We showed other examples of this earlier in the discussion of constraint type inference.
In a function with two type parameters
From and
To, a value of type
From may be converted to a value of type
To if all the types accepted by
From's constraint can be converted to all the types accepted by
To's constraint. If either type parameter does not have a type list, type conversions are not permitted.
This is a consequence of the general rule that a generic function may use any operation that is permitted by all types listed in the type list.
For example:
type integer interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr } func Convert[To, From integer] a type parameter if it is permitted with every type accepted by the type parameter's constraint.
As with type conversions, this is a consequence of the general rule that a generic function may use any operation that is permitted by all types listed in the type list.
type integer interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr } func Add10[T integer](s []T) { for i, v := range s { s[i] = v + 10 // OK: 10 can convert to any integer type } } // This function is INVALID. func Add1024[T integer](s []T) { for i, v := range s { s[i] = v + 1024 // INVALID: 1024 not permitted by int8/uint8 } }
When a constraint embeds another constraint, the type list of the final constraint is the intersection of all the type lists involved. If there are multiple embedded types, intersection preserves the property that any type argument must satisfy the requirements of all embedded types.
// Addable is types that support the + operator. type Addable interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64, complex64, complex128, string } // Byteseq is a byte sequence: either string or []byte. type Byteseq interface { type string, []byte } // AddableByteseq is a byte sequence that supports +. // This is every type is that is both Addable and Byteseq. // In other words, just the type string. type AddableByteseq interface { Addable Byteseq }
It may seem awkward to explicitly list types in a constraint, but it is clear both as to which type arguments are permitted at the call site, and which operations are permitted by the generic function.
If the language later changes to support operator methods (there are no such plans at present), then constraints. The expectation is that composite types will normally be handled using composite types in generic function and type declarations, rather than putting composite types in a type list. For example, we expect functions that want to index into a slice to be parameterized on the slice element type
T, and to use parameters or variables of type
[]T.
As shown in the
DoubleMySlice example above, this approach makes it awkward to declare generic functions that accept and return a composite type and want to return the same result type as their argument type. Defined composite types are not common, but they do arise. This awkwardness is a weakness of this approach. Constraint type inference can help at the call site. square brackets. For example,
List[int].
It's impossible for non-generic code to refer to generic code without instantiating it, so there is no reflection information for uninstantiated generic types or functions.. This new syntax, and the new support for type lists in interfaces, are the only new syntactic constructs in this design. The code within a generic function reads like ordinary Go code, as can be seen in the examples below. It is an easy shift to go from
[]int to
[]T. Type parameter constraints serve effectively as documentation, describing the type.
We expect that most packages will not define generic types or functions, but many packages are likely to use generic types or functions defined elsewhere. equivalence, with no attempt to resolve two types that are similar but not equivalent, which removes significant complexity.
Packages using generic types will have to pass explicit type arguments. The syntax for this is straightforward. algorithms that are currently duplicated for each element type. A
sets package may be added.
A new
constraints package will provide standard constraints, such as constraints that permit all integer types or all numeric types.
Packages like
container/list and
container/ring, and types like
sync.Map and
sync/atomic.Value, will be updated to be compile-time type-safe, either using new names or new versions of the packages.
The
math package will be extended to provide a set of simple standard algorithms for all numeric types, such as the ever popular
Min and
Max functions.
We may add generic variants to the
sort package.
It is likely that new special purpose compile-time type-safe container types will be developed. function].
==operator in terms of an
Equalmethod, or vice-versa.
type Matrix[T any] way to write a constraint to support either
return nil or
return 0.
Some approaches to this are:
var zero T, as above, which works with the existing design but requires an extra statement.
*new(T), which is cryptic but works with the existing design..
return ...to return zero values of the result types, as proposed in issue 21182.
We feel that more experience with this design is needed before deciding what, if anything, to do here.
The design doesn't provide any way to test the underlying type matched by a type argument. Code can test the actual type argument through the somewhat awkward approach of converting to an empty interface type and using a type assertion or a type switch. But that lets code test the actual type argument, which is not the same as the underlying type.
Here is an example that shows the difference.
type Float interface { type float32, float64 } func NewtonSqrt[T Float](v T) T { var iterations int switch (interface{}) constraint.
One way to handle this would be to permit type switches on the type
T, with the proviso that the type
T would always match a type defined in the constraint. This kind of type switch would only be permitted if the constraint lists explicit types, and only types listed in the constraint would be permitted as cases.
The design has no way to express convertibility between two different type parameters. For example, there is no way to write this function:
// Copy copies values from src to dst, converting them as they go. // It returns the number of items copied, which is the minimum of // the lengths of dst and src. // This implementation is INVALID. func Copy[T1, T2 any](dst []T1, src []T2) int { for i, x := range src { if i > len(dst) { return i } dst[i] = T1(x) // INVALID } return len(src) }
The conversion from type
T2 to type
T1 is invalid, as there is no constraint on either type that permits the conversion. Worse, there is no way to write such a constraint in general. In the particular case where both
T1 and
T2 can require some type list, then this function can be written as described earlier when discussing type conversions using type lists. But, for example, there is no way to write a constraint for the case in which
T1 is an interface type and
T2 is a type that implements that interface.
It's worth noting that if
T1 is an interface type then this can be written using a conversion to the empty interface type and a type assertion, but this is, of course, not compile-time type-safe.
// Copy copies values from src to dst, converting them as they go. // It returns the number of items copied, which is the minimum of // the lengths of dst and src. func Copy[T1, T2 any](dst []T1, src []T2) int { for i, x := range src { if i > len(dst) { return i } dst[i] = (interface{})(x).(T1) } return len(src) }
This design does not permit methods to declare type parameters that are specific to the method. The receiver may have type parameters, but the method may not add any type parameters.
In Go, one of the main roles of methods is to permit types to implement interfaces. It is not clear whether it is reasonably possible to permit parameterized methods to implement interfaces. For example, consider this code, which uses the obvious syntax for parameterized methods. This code uses multiple packages to make the problem clearer.
package p1 // S is a type with a parameterized method Identity. type S struct{} // Identity is a simple identity method that works for any type. func (S) Identity[T any](v T) T { return v } package p2 // HasIdentity is an interface that matches any type with a // parameterized Identity method. type HasIdentity interface { Identity[T any](T) T } package p3 import "p2" // CheckIdentity checks the Identity method if it exists. // Note that although this function calls a parameterized method, // this function is not itself parameterized. func CheckIdentity(v interface{}) { if vi, ok := v.(p2.HasIdentity); ok { if got := vi.Identity[int](0); got != 0 { panic(got) } } } package p4 import ( "p1" "p3" ) // CheckSIdentity passes an S value to CheckIdentity. func CheckSIdentity() { p3.CheckIdentity(p1.S{}) }
In this example, we have a type
p1.S with a parameterized method and a type
p2.HasIdentity that also has a parameterized method.
p1.S implements
p2.HasIdentity. Therefore, the function
p3.CheckIdentity can call
vi.Identity with an
int argument, which in the call from
p4.CheckSIdentity will be a call to
p1.S.Identity[int]. But package p3 does not know anything about the type
p1.S. There may be no other call to
p1.S.Identity elsewhere in the program. We need to instantiate
p1.S.Identity[int] somewhere, but how?
We could instantiate it at link time, but in the general case that requires the linker to traverse the complete call graph of the program to determine the set of types that might be passed to
CheckIdentity. And even that traversal is not sufficient in the general case when type reflection gets involved, as reflection might look up methods based on strings input by the user. So in general instantiating parameterized methods in the linker might require instantiating every parameterized method for every possible type argument, which seems untenable.
Or, we could instantiate it at run time. In general this means using some sort of JIT, or compiling the code to use some sort of reflection based approach. Either approach would be very complex to implement, and would be surprisingly slow at run time.
Or, we could decide that parameterized methods do not, in fact, implement interfaces, but then it's much less clear why we need methods at all. If we disregard interfaces, any parameterized method can be implemented as a parameterized function.
So while parameterized methods seem clearly useful at first glance, we would have to decide what they mean and how to implement that.
In some cases a parameterized function is naturally written such that it always invokes methods on addressable values. For example, this happens when calling a method on each element of a slice. In such a case, the function only requires that the method be in the slice element type's pointer method set. The type constraints described in this design have no way to write that requirement.
For example, consider a variant of the
Stringify example we showed earlier.
// Stringify2 calls the String method on each element of s, // and returns the results. func Stringify2[T Stringer](s []T) (ret []string) { for i := range s { ret = append(ret, s[i].String()) } return ret }
Suppose we have a
[]bytes.Buffer and we want to convert it into a
[]string. The
Stringify2 function here won‘t help us. We want to write
Stringify2[bytes.Buffer], but we can’t, because
bytes.Buffer doesn‘t have a
String method. The type that has a
String method is
*bytes.Buffer. Writing
Stringify2[*bytes.Buffer] doesn’t help because that function expects a
[]*bytes.Buffer, but we have a
[]bytes.Buffer.
We discussed a similar case in the pointer method example above. There we used constraint type inference to help simplify the problem. Here that doesn‘t help, because
Stringify2 doesn’t really care about calling a pointer method. It just wants a type that has a
String method, and it's OK if the method is only in the pointer method set, not the value method set. But we also want to accept the case where the method is in the value method set, for example if we really do have a
[]*bytes.Buffer.
What we need is a way to say that the type constraint applies to either the pointer method set or the value method set. The body of the function would be required to only call the method on addressable values of the type.
It's not clear how often this problem comes up in practice.
Constraint type inference lets us give a name to the element of a slice type, and to apply other similar type decompositions. However, there is no way to associate a float type and a complex type. For example, there is no way to write the predeclared
real,
imag, or
complex functions with this design. There is no way to say “if the argument type is
complex64, then the result type is
float32.”
One possible approach here would be to permit
real(T) as a type constraint meaning “the float type associated with the complex type
T”. Similarly,
complex(T) would mean “the complex type associated with the floating point type
T”. Constraint type inference would simplify the call site. However, that would be unlike other type constraints.
This design is not perfect, and there may be ways to improve it. That said, there are many ideas that we've already considered in detail. This section lists some of those ideas in the hopes that it will help to reduce repetitive discussion. The ideas are presented in the form of a FAQ.
An earlier draft design of generics implemented constraints using a new language construct called contracts. Type lists appeared only in contracts, rather than on interface types. However, many people had a hard time understanding the difference between contracts and interface types. It also turned out that contracts could be represented as a set of corresponding interfaces; there was no loss in expressive power without contracts. We decided to simplify the approach to use only interface types.
Type lists are weird. Why not write methods for all operators?
It is possible to permit operator tokens as method names, leading to methods such as
+(T) T. Unfortunately, that is not sufficient. We would need some mechanism to describe a type that matches any integer type, for operations such as shifts
<<(integer) T and indexing
[](integer) T which are not restricted to a single int type. We would need an untyped boolean type for operations such as
==(T) untyped bool. We would need to introduce new notation for operations such as conversions, or to express that one may range over a type, which would likely require some new syntax. We would need some mechanism to describe valid values of untyped constants. We would have to consider whether support for
<(T) bool means that a generic function can also use
<=, and similarly whether support for
+(T) T means that a function can also use
++. It might be possible to make this approach work but it's not straightforward. The approach used in this design seems simpler and relies on only one new syntactic construct (type lists) and one new name (
comparable). same package.
It also confuses package boundaries with type definitions. There is no particular reason to think that the uses of generic. This is very difficult to resolve without type information.
For example, consider a statement like
a, b = w < x, y > (z)
Without type information, it is impossible to decide whether the right hand side of the assignment is a pair of expressions (
w < x and
y > (z)), or whether it is a generic function instantiation and call that returns two result values (
(w<x, y>)(z)).
It is a key design decision of Go that parsing be possible without type information, which seems impossible when using angle brackets for generics.
F(T)?
An earlier version of this design used that syntax. It was workable but it introduced several parsing ambiguities. For example, when writing
var f func(x(T)) it wasn't clear whether this the type was a function with a single unnamed parameter of the instantiated type
x(T) or whether it was a function with a parameter named
x with type
(T) (more usually written as
func(x T), but in this case with a parenthesized type).
There were other ambiguities as well. For
[]T(v1) and
[]T(v2){}, at the point of the open parentheses we don‘t know whether this is a type conversion (of the value
v1 to the type
[]T) or a type literal (whose type is the instantiated type
T(v2)). For
interface { M(T) } we don’t know whether this an interface with a method
M or an interface with an embedded instantiated interface
M(T). These ambiguities are solvable, by adding more parentheses, but awkward.
Also some people were troubled by the number of parenthesized lists involved in declarations like
func F(T any)(v T)(r1, r2 T) or in calls like
F(int)(1).
F«T»?
We considered it but we couldn't bring ourselves to require non-ASCII.
Instead of writing out type lists, use names like
constraints.Arithmetic and
constraints only two new predeclared names,
comparable and
any.
We expect that if people find such names useful, we can introduce a package
constraints that defines those names in the form of constraints that can be used by other types and functions and embedded in other constraints. That will define the most useful names in the standard library while giving programmers the flexibility to use other combinations of types where appropriate.
In an earlier version of this design, we permitted using type assertions and type switches on variables whose type was a type parameter, or whose type was based on a type parameter. We removed this facility because it is always possible to convert a value of any type to the empty interface type, and then use a type assertion or type switch on that. Also, it was sometimes confusing that in a constraint with a type list, a type assertion or type switch would use the actual type argument, not the underlying type of the type argument (the difference is explained in the section on identifying the matched predeclared type). mandatory and explicit constraints..
C++ uses two-phase name lookup, in which some names are looked up in the context of the template definition, and some names are looked up in the context of the template instantiation. In this design all names are looked up at the point where they are written.
In practice, all C++ compilers compile each template at the point where it is instantiated. This can slow down compilation time. This design offers flexibility as to how to handle the compilation of generic functions.
The generics described in this design are similar to generics in Rust.
One difference is that in Rust the association between a trait bound and a type must be defined explicitly, either in the crate that defines the trait bound or the crate that defines the type. In Go terms, this would mean that we would have to declare somewhere whether a type satisfied a constraint. Just as Go types can satisfy Go interfaces without an explicit declaration, in this design Go type arguments can satisfy a constraint without an explicit declaration.
Where this design uses type lists, the Rust standard library defines standard traits for operations like comparison. These standard traits are automatically implemented by Rust's primitive types, and can be implemented by user defined types as well. Rust provides a fairly extensive list of traits, at least 34, covering all of the operators.
Rust supports type parameters on methods, which this design does not.
The following sections are examples of how this design could be used. This is intended to address specific areas where people have created user experience reports concerned with Go's lack of generics.. // This function has two type parameters, T1 and T2. // This works with slices of any type. func Map[T1, T2 any](s []T1, f func(T1) T2) []T2 { r := make([]T2, len(s)) for i, v := range s { r[i] = f(v) } return r } // Reduce reduces a []T1 to a single value using a reduction function. func Reduce[T1, T2 any](s []T1, initializer T2, f func(T2, T1) T2) T2 { r := initializer for _, v := range s { r = f(r, v) } return r } // Filter filters values from a slice using a filter function. // It returns a new slice with only the elements of s // for which f returned true. func Filter[T any](s []T, f func(T) bool) []T { var r []T for _, v := range s { if f(v) { r = append(r, v) } } return r }
Here are some example calls of these functions. Type inference is used to determine the type arguments based on the types of the non-type arguments.
s := []int{1, 2, 3} floats := slices.Map(s, func(i int) float64 { return float64(i) }) // Now floats is []float64{1.0, 2.0, 3.0}. sum := slices.Reduce(s, 0, func(i, j int) int { return i + j }) // Now sum is 6. evens := slices.Filter(s, func(i int) bool { return i%2 == 0 }) // Now evens is []int{2}.
Here is how to get a slice of the keys of any map.
// Package maps provides general functions that work for all map types. package maps // Keys returns the keys of the map m in a slice. // The keys will be returned in an unpredictable order. // This function has two type parameters, K and V. // Map keys must be comparable, so key has the predeclared // constraint comparable. Map values can be any type. func Keys[K comparable, V any](m map[K]V) []K { r := make([]K, 0, len(m)) for k := range m { r = append(r, k) } return r }
In typical use the map key and val types will be inferred.
k := maps.Keys(map[int]int{1:2, 2:4}) // Now k is either []int{1, 2} or []int{2, 1}.
Many people have asked for Go's builtin map type to be extended, or rather reduced, to support a set type. Here is a type-safe implementation of a set type, albeit one that uses methods rather than operators like
[].
// Package sets implements sets of any comparable type. package sets // Set is a set of values. type Set[T comparable] map[T]struct{} // Make returns a set of some element type. func Make[T comparable]() Set[T] { return make(Set[T]) } // Add adds v to the set s. // If v is already in s this has no effect. func (s Set[T]) Add(v T) { s[v] = struct{}{} } // Delete removes v from the set s. // If v is not in s this has no effect. func (s Set[T]) Delete(v T) { delete(s, v) } // Contains reports whether v is in s. func (s Set[T]) Contains(v T) bool { _, ok := s[v] return ok } // Len reports the number of elements in s. func (s Set[T]) Len() int { return len(s) } // Iterate invokes f on each element of s. // It's OK for f to call the Delete method. func (s Set[T]) Iterate(f func(T)) { for v := range s { f(v) } }
Example use:
// Create a set of ints. // We pass int as a type argument. // Then we write () because Make does not take any non-type arguments. // We have to pass an explicit type argument to Make. // Function argument type inference doesn't work because the // type argument to Make is only used for a result parameter type. s := sets.Make[int]() // Add the value 1 to the set s. s.Add(1) // Check that s does not contain the value 2. if s.Contains(2) { panic("unexpected 2") }
This example shows how to use this design to provide a compile-time type-safe wrapper around an existing API.
Before the introduction of
sort.Slice, a common complaint was the need for boilerplate definitions in order to use
sort.Sort. With this design, we can add to the sort package as follows:
// Ordered is a type constraint that matches all ordered types. // (An ordered type is one that supports the < <= >= > operators.) // In practice this type constraint would likely be defined in // a standard library package. type Ordered interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64, string } // orderedSlice is an internal type that implements sort.Interface. // The Less method uses the < operator. The Ordered type constraint // ensures that T has a < operator. type orderedSlice[T Ordered] []T func (s orderedSlice[T]) Len() int { return len(s) } func (s orderedSlice[T]) Less(i, j int) bool { return s[i] < s[j] } func (s orderedSlice[T]) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // OrderedSlice sorts the slice s in ascending order. // The elements of s must be ordered using the < operator. func OrderedSlice[T Ordered](s []T) { // Convert s to the type orderedSlice[T]. // As s is []T, and orderedSlice[T] is defined as []T, // this conversion is permitted. // orderedSlice[T] implements sort.Interface, // so can pass the result to sort.Sort. // The elements will be sorted using the < operator. sort.Sort(orderedSlice[T](s)) }
Now we can write:
s1 := []int32{3, 5, 2} sort.OrderedSlice(s1) // Now s1 is []int32{2, 3, 5} s2 := []string{"a", "c", "b"}) sort.OrderedSlice(s2) // Now s2 is []string{"a", "b", "c"}
Along the same lines, we can add a function for sorting using a comparison function, similar to
sort.Slice but writing the function to take values rather than slice indexes.
// sliceFn is an internal type that implements sort.Interface. // The Less method calls the cmp field. type sliceFn[T any] struct { s []T cmp func(T, T) bool } func (s sliceFn[T]) Len() int { return len(s.s) } func (s sliceFn[T]) Less(i, j int) bool { return s.cmp(s.s[i], s.s[j]) } func (s sliceFn[T]) Swap(i, j int) { s.s[i], s.s[j] = s.s[j], s.s[i] } // SliceFn sorts the slice s according to the function cmp. func SliceFn[T any](s []T, cmp func(T, T) bool) { sort.Sort(sliceFn[E]{s, cmp}) }
An example of calling this might be:
var s []*Person // ... sort.SliceFn(s, func(p1, p2 *Person) bool { return p1.Name < p2.Name })
Many simple general purpose channel functions are never written, because they must be written using reflection and the caller must type assert the results. With this design they become straightforward to write.
// Package chans implements various channel algorithms. package chans import "runtime" // Drain drains any elements remaining on the channel. func Drain[T any](c <-chan T) { for range c { } } // Merge merges two channels of some element type into a single channel. func Merge[T any](c1, c2 <-chan T) <-chan T { r := make(chan T) go func(c1, c2 <-chan T, r chan<- T) { defer close(r) for c1 != nil || c2 != nil { select { case v1, ok := <-c1: if ok { r <- v1 } else { c1 = nil } case v2, ok := <-c2: if ok { r <- v2 } else { c2 = nil } } } }(c1, c2, r) return r } // Ranger provides a convenient way to exit a goroutine sending values // when the receiver stops reading them. // //. func Ranger[T any]() (*Sender[T], *Receiver[T]) { c := make(chan T) d := make(chan bool) s := &Sender[T]{values: c, done: d} r := &Receiver[T]{values: c, done: d} // The finalizer on the receiver will tell the sender // if the receiver stops listening. runtime.SetFinalizer(r, r.finalize) return s, r } // A Sender is used to send values to a Receiver. type Sender[T any] struct { values chan<- T done <-chan bool } // Send sends a value to the receiver. It reports whether any more // values may be sent; if it returns false the value was not sent. func (s *Sender[T]) Send(v T) bool { select { case s.values <- v: return true case <-s.done: // The receiver has stopped listening. return false } } // Close tells the receiver that no more values will arrive. // After Close is called, the Sender may no longer be used. func (s *Sender[T]) Close() { close(s.values) } // A Receiver receives values from a Sender. type Receiver[T any] struct { values <-chan T done chan<- bool } // Next returns the next value from the channel. The bool result // reports whether the value is valid. If the value is not valid, the // Sender has been closed and no more values will be received. func (r *Receiver[T]) Next() (T, bool) { v, ok := <-r.values return v, ok } // finalize is a finalizer for the receiver. // It tells the sender that the receiver has stopped listening.maps provides an ordered map, implemented as a binary tree. package orderedmaps import "chans" // Map is an ordered map. type Map[K, V any] struct { root *node[K, V] compare func(K, K) int } // node is the type of a node in the binary tree. type node[K, V any] struct { k K v V left, right *node[K, V] } // New returns a new map. // Since the type parameter V is only used for the result, // type inference does not work, and calls to New must always // pass explicit type arguments. func New[K, V any](compare func(K, K) int) *Map[K, V] { return &Map[K, V]{compare: compare} } // find looks up k in the map, and returns either a pointer // to the node holding k, or a pointer to the location where // such a node would go. func (m *Map[K, V]) find(k K) **node[K, V] { pn := &m.root for *pn != nil { switch cmp := m.compare(k, (*pn).k); { case cmp < 0: pn = &(*pn).left case cmp > 0: pn = &(*pn).right default: return pn } } return pn } // Insert inserts a new key/value into the map. // If the key is already present, the value is replaced. // Reports whether this is a new key. func (m *Map[K, V]) Insert(k K, v V) bool { pn := m.find(k) if *pn != nil { (*pn).v = v return false } *pn = &node[K, V]{k: k, v: v} return true } // Find returns the value associated with a key, or zero if not present. // The bool result reports whether the key was found. func (m *Map[K, V]) Find(k K) (V, bool) { pn := m.find(k) if *pn == nil { var zero V // see the discussion of zero values, above return zero, false } return (*pn).v, true } // keyValue is a pair of key and value used when iterating. type keyValue[K, V any] struct { k K v V } // InOrder returns an iterator that does an in-order traversal of the map. func (m *Map[K, V]) InOrder() *Iterator[K, V] { type kv = keyValue[K, V] // convenient shorthand sender, receiver := chans.Ranger[kv]() var f func(*node[K, V]) bool f = func(n *node[K, V]) bool { if n == nil { return true } // Stop sending values if sender.Send returns false, // meaning that nothing is listening at the receiver end. return f(n.left) && sender.Send(kv{n.k, n.v}) && f(n.right) } go func() { f(m.root) sender.Close() }() return &Iterator[K, V]{receiver} } // Iterator is used to iterate over the map. type Iterator[K, V any] struct { r *chans.Receiver[keyValue[K, V]] } // Next returns the next key and value pair. The bool result reports // whether the values are valid. If the values are not valid, we have // reached the end. func (it *Iterator[K, V]) Next() (K, V, bool) { kv, ok := it.r.Next() return kv.k, kv.v, ok }
This is what it looks like to use this package:
import "container/orderedmaps" // Set m to an ordered map from string to string, // using strings.Compare as the comparison function. var m = orderedmaps.New[string, string](strings.Compare) // Add adds the pair a, b to m. func Add(a, b string) { m.Insert(a, b) }
The predeclared
append function exists to replace the boilerplate otherwise required to grow a slice. Before
append was added to the language, there was a function
Add in the bytes package:
// Add appends the contents of t to the end of s and returns the result. // If s has enough capacity, it is extended in place; otherwise a // new array is allocated and returned. func Add(s, t []byte) []byte
Add implements various slice algorithms. package slices // Append appends the contents of t to the end of s and returns the result. // If s has enough capacity, it is extended in place; otherwise a // new array is allocated and returned. func Append[T any](s []T, t ...T) []T { lens := len(s) tot := lens + len(t) if tot < 0 { panic("Append: cap out of range") } if tot > cap(s) { news := make([]T, tot, tot + tot/2) copy(news, s) s = news } s = s[:tot] copy(s[lens:], t) return s }
That example uses the predeclared
copy function, but that's OK, we can write that one too:
// Copy copies values from t to s, stopping when either slice is // full, returning the number of values copied. func Copy[T any](s, t []T) int { i := 0 for ; i < len(s) && i < len(t); i++ { s[i] = t[i] } return i }
These functions can be used as one would expect:
s := slices.Append([]int{1, 2, 3}, 4, 5, 6) // Now s is []int{1, 2, 3, 4, 5, 6}. slices.Copy(s[3:], []int{7, 8, 9}) // Now s is []int{1, 2, 3, provides a general mechanism for accumulating // metrics of different values. package metrics import "sync" // Metric1 accumulates metrics of a single value. type Metric1[T comparable] struct { mu sync.Mutex m map[T]int } // Add adds an instance of a value. func (m *Metric1[T]) Add(v T) { m.mu.Lock() defer m.mu.Unlock() if m.m == nil { m.m = make(map[T]int) } m.m[v]++ } // key2 is an internal type used by Metric2. type key2[T1, T2 comparable] struct { f1 T1 f2 T2 } // Metric2 accumulates metrics of pairs of values. type Metric2[T1, T2 comparable] struct { mu sync.Mutex m map[key2[T1, T2]]int } // Add adds an instance of a value pair. func (m *Metric2[T1, T2]) Add(v1 T1, v2 T2) { m.mu.Lock() defer m.mu.Unlock() if m.m == nil { m.m = make(map[key2[T1, T2]]int) } m.m[key2[T1, T2]{v1, v2}]++ } // key3 is an internal type used by Metric3. type key3[T1, T2, T3 comparable] struct { f1 T1 f2 T2 f3 T3 } // Metric3 accumulates metrics of triples of values. type Metric3[T1, T2, T3 comparable] struct { mu sync.Mutex m map[key3[T1, T2, T3]]int } // Add adds an instance of a value triplet. func (m *Metric3[T1, T2, T3]) Add(v1 T1, v2 T2, v3 T3) { m.mu.Lock() defer m.mu.Unlock() if m.m == nil { m.m = make(map[key3[T1, T2, T3]]int) } m.m[key3 implementation has a certain amount of repetition due to the lack of support for variadic generic type.
// Package lists provides a linked list of any type. package lists // List is a linked list. type List[T any] struct { head, tail *element[T] } // An element is an entry in a linked list. type element[T any][T any] struct { next **element[T] } // Range returns an Iterator starting at the head of the list. func (lst *List[T]) Range() *Iterator[T] { return Iterator[T]{next: &lst.head} } // Next advances the iterator. // It reports[T1, T2 any](lst *List[T1], f func(T1) T2) *List[T2] { ret := &List[T2]{} it := lst.Range() for { if v, ok := it.Val(); ok { ret.Push(f(v)) } if !it.Next() { break } } return ret }
A generic dot product implementation that works for slices of any numeric type.
// Numeric is a constraint that matches any numeric type. // It would likely be in a constraints package in the standard library. type Numeric interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64, complex64, complex128 } // DotProduct returns the dot product of two slices. // This panics if the two slices are not the same length. func DotProduct[T Numeric](s1, s2 []T) T { if len(s1) != len(s2) { panic("DotProduct: slices of unequal length") } var r T for i := range s1 { r += s1[i] * s2[i] } return r }
(Note: the generics implementation approach may affect whether
DotProduct uses FMA, and thus what the exact results are when using floating point types. It's not clear how much of a problem this is, or whether there is any way to fix it.)
Compute the absolute difference between two numeric values, by using an
Abs method. This uses the same
Numeric constraint vary based on the kind of type being used.
// NumericAbs matches numeric types with an Abs method. type NumericAbs[T any] interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64, complex64, complex128 Abs() T } // AbsDifference computes the absolute value of the difference of // a and b, where the absolute value is determined by the Abs method. func AbsDifference[T NumericAbs](a, b T) T { d := a - b return d.Abs() }
We can define an
Abs method appropriate for different numeric types.
// OrderedNumeric matches numeric types that support the < operator. type OrderedNumeric interface { type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64 } // Complex matches the two complex types, which do not have a < operator. type Complex interface { type complex64, complex128 } // OrderedAbs is a helper type that defines an Abs method for // ordered numeric types. type OrderedAbs[T OrderedNumeric] T func (a OrderedAbs[T]) Abs() OrderedAbs[T] { if a < 0 { return -a } return a } // ComplexAbs is a helper type that defines an Abs method for // complex types. type ComplexAbs[T Complex] T func (a ComplexAbs[T]) Abs() ComplexAbs[T] { d := math.Hypot(float64(real(a)), float64(imag(a))) return ComplexAbs[T](complex(d, 0)) }
We can then define functions that do the work for the caller by converting to and from the types we just defined.
// OrderedAbsDifference returns the absolute value of the difference // between a and b, where a and b are of an ordered type. func OrderedAbsDifference[T OrderedNumeric](a, b T) T { return T(AbsDifference(OrderedAbs[T](a), OrderedAbs[T](b))) } // ComplexAbsDifference returns the absolute value of the difference // between a and b, where a and b are of a complex type. func ComplexAbsDifference[T Complex](a, b T) T { return T(AbsDifference(ComplexAbs[T](a), ComplexAbs[T](b))) }
It's worth noting that this design is not powerful enough to write code like the following:
// This function is INVALID. func GeneralAbsDifference[T Numeric](a, b T) T { switch (interface{}) implement the
Numeric constraint can implement the
OrderedNumeric or
Complex constraints. Although the type switch means that this code would conceptually work at run time, there is no support for writing this code at compile time. This is another way of expressing one of the omissions listed above: this design does not provide for specialization.
We‘d like to thank many people on the Go team, many contributors to the Go issue tracker, and all the people who have shared their ideas and their feedback on earlier design drafts. We read all of it, and we’re grateful.
For this version of the proposal in particular we received detailed feedback from Josh Bleecher-Snyder, Jon Bodner, Dave Cheney, Jaana Dogan, Kevin Gillette, Mitchell Hashimoto, Chris Hines, Bill Kennedy, Ayke van Laethem, Daniel Martí, Elena Morozova, Roger Peppe, and Ronna Steinberg.
This appendix covers various details of the design that don't seem significant enough to cover in earlier sections.
A type alias may refer to a generic type, but the type alias may not have its own parameters. This restriction exists because it is unclear how to handle a type alias with type parameters that have constraints.
type VectorAlias = Vector
In this case uses of the type alias will have to provide type arguments appropriate for the generic type being aliased.
var v VectorAlias[int]
Type aliases may also refer to instantiated types.
type VectorInt = Vector[int]
Go normally permits you to refer to a function without passing any arguments, producing a value of function type. You may not do this with a function that has type parameters; all type arguments must be known at compile time. That said, you can instantiate the function, by passing type arguments, but you don't have to call the instantiation. This will produce a function value with no type parameters.
// PrintInts is type func([]int). var PrintInts = Print[int]
When a generic type is a struct, and the type parameter is embedded as a field in the struct, the name of the field is the name of the type parameter.
// A Lockable is a value that may be safely simultaneously accessed // from multiple goroutines via the Get and Set methods. type Lockable[T any] struct { T mu sync.Mutex } // Get returns the value stored in a Lockable. func (l *Lockable[T]) Get() T { l.mu.Lock() defer l.mu.Unlock() return l.T } // Set sets the value in a Lockable. func (l *Lockable[T]) Set(v T) { l.mu.Lock() defer l.mu.Unlock() l.T = v }
When a generic type is a struct, and the type parameter is embedded as a field in the struct, any methods of the type parameter's constraint are promoted to be methods of the struct. (For purposes of selector resolution, these methods are treated as being at depth 0 of the type parameter, even if in the actual type argument the methods were themselves promoted from an embedded type.)
// NamedInt is an int with a name. The name can be any type with // a String method. type NamedInt[Name fmt.Stringer] struct { Name val int } // Name returns the name of a NamedInt. func (ni NamedInt[Name]) Name() string { // The String method is promoted from the embedded Name. return ni.String() }
When embedding an instantiated type, the name of the field is the name of type without the type arguments.
type S struct { T[int] // field name is T } func F(v S) int { return v.T // not v.T[int] }
A generic type may be used as the type in a type assertion or as a case in a type switch.
Here are some trivial examples:
func Assertion[T any](v interface{}) (T, bool) { t, ok := v.(T) return t, ok } func Switch[T any](v interface{}) (T, bool) { switch v := v.(type) { case T: return v, true default: var zero T return zero, false } }
In a type switch, it's OK if a generic type turns out to duplicate some other case in the type switch. The first matching case is chosen.
func Switch2[T any](v interface{}) int { switch v.(type) { case T: return 0 case string: return 1 default: return 2 } } // S2a will be set to 0. var S2a = Switch2[string]("a string") // S2b will be set to 1. var S2b = Switch2[int]("another string")
This is a feature we are not suggesting now, but could consider for later versions of the language.
We could also consider supporting type inference for composite literals of generic types.
type Pair[T any] struct { f1, f2 T } var V = Pair{1, 2} // inferred as Pair(int){1, 2}
It's not clear how often this will arise in real code.
This is a feature we are not suggesting now, but could consider for later versions of the language.
In the following example, consider the call to
Find in
FindClose. Type inference can determine that the type argument to
Find is
T4, and from that we know that the type of the final argument must be
func(T4, T4) bool, and from that we could deduce that the type argument to
IsClose must also be
T4. However, the type inference algorithm described earlier cannot do that, so we must explicitly write
IsClose[T4].
This may seem esoteric at first, but it comes up when passing generic functions to generic
Map and
Filter functions.
// Differ has a Diff method that returns how different a value is. type Differ[T1 any] interface { Diff(T1) int } // IsClose returns whether a and b are close together, based on Diff. func IsClose[T2 Differ](a, b T2) bool { return a.Diff(b) < 2 } // Find returns the index of the first element in s that matches e, // based on the cmp function. It returns -1 if no element matches. func Find[T3 any](s []T3, e T3, cmp func(a, b T3) bool) int { for i, v := range s { if cmp(v, e) { return i } } return -1 } // FindClose returns the index of the first element in s that is // close to e, based on IsClose. func FindClose[T4 Differ](s []T4, e T4) int { // With the current type inference algorithm we have to // explicitly write IsClose[T4] here, although it // is the only type argument we could possibly use. return Find(s, e, IsClose[T4]) }
Although we don‘t suggest changing the reflect package, one possibility to consider for the future would be to add two new methods to
reflect.Type:
NumTypeArgument() int would return the number of type arguments to a type, and
TypeArgument(i) Type would return the i’th type argument.
NumTypeArgument would return non-zero for an instantiated generic type. Similar methods could be defined for
reflect.Value, for which
NumTypeArgument would return non-zero for an instantiated generic function. There might be programs that care about this information. | https://go.googlesource.com/proposal/+/master/design/43651-type-parameters.md | CC-MAIN-2021-25 | refinedweb | 17,039 | 63.59 |
You can subscribe to this list here.
Showing
1
results of 1
Adriaan de Groot wrote:
> I see that current CVS' sufreplace requires that the source and target
> suffix begin with a ".". Why was this restriction introduced? It makes
> sufreplace() useless for my purposes [1].
The check for the "from" suffix starting with a dot is desirable,
otherwise strange things might happen. If "from" doesn't start with a
dot this is probably a mistake by the user, e.g.:
sufreplace("c", "o", source)
This would change "foo.roc" to "foo.roo". But that mistake goes
unnoticed so long as you are feeding the function "*.c" files. It
should be:
sufreplace(".c", ".o", source)
I think it's essential that sufreplace() only replaces the suffix of a
file, not any tail that matches. Otherwise it is too easy to make a
mistake and be puzzled about why it sometimes doesn't work.
I can understand you would want to change a suffix from ".h" to
"_skel.cc". The question is whether sufreplace() should be used for
this, since you are not really replacing one suffix with another but
more than that.
Would a user mistakingly do:
sufreplace(".c", "o", source)
Not very likely to make this mistake, is it? So, perhaps we should
define sufreplace() to replace the suffix of the input into "anything".
That would work for your "fake sources", right? And still give an error
for the most common mistake a user can make.
> FWIW, here's a version of sufreplace() (based on AAP 1.006's
> sufreplace()) that uses var2dictlist for the dirty work (like my
> earlier suffixmangle). The RE's become a little simpler, and
> attributes are preserved.
Yes, that looks better than before. Including the check for the "from"
suffix and adding a few spaces to make it more readable. Oh, and now
that the regexp is used several times it's a good idea to use
re.compile(). I end up with this, please test it:
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
def sufreplace(suffrom, sufto, var):
"""
Replace suffixes in "var" from "suffrom" to "sufto".
When "suffrom" is empty accept any suffix.
When "sufto" is empty the suffix is removed.
"""
# Check that the from suffix starts with a dot.
if suffrom and suffrom[0] != ".":
recipe_error([], _('first sufreplace() argument must start with a dot'))
try:
if suffrom:
rex = re.compile(string.replace(suffrom, ".", "\\.") + "$")
else:
rex = re.compile("\\.[^. \t/\\\\]+$")
dl = var2dictlist(var)
for n in dl:
n["name"] = rex.sub(sufto, n["name"])
return dictlist2str(dl)
except StandardError, e:
recipe_error([], _('sufreplace() failed: ') + str(e))
return None # not reached
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
> I guess the only possibility left is to use {var_OBJSUF=_skel.o} now,
> as long as src2obj() doesn't use sufreplace().
AAAarrrrggghhh! :-)
--
hundred-and-one symptoms of being an internet addict:
174. You know what a listserv is.
/// Bram Moolenaar -- Bram@... -- \\\
/// Creator of Vim - Vi IMproved -- \\\
\\\ Project leader for A-A-P -- ///
\\\ Help AIDS victims, buy here: /// | http://sourceforge.net/p/a-a-p/mailman/a-a-p-develop/?viewmonth=200308&viewday=20 | CC-MAIN-2015-48 | refinedweb | 485 | 77.03 |
On Sun, Jan 16, 2011 at 09:44:26PM +0000, Al Viro wrote:> Already fixed. Actually, taking it out of ifdef would work (the only> place that actually cares about the value of that sucker is SMP side> of mntput()), but we are obviously better off just not touching it on> UP at all - why do pointless work and waste space?> > See the patch upthread. ->mnt_longterm is SMP-only optimization of> mntput(); it's there only to free the common case of mntput() from> cacheline bouncing and on UP it's needed at all.PS: the patch does survive UP beating. Could you pullgit://git.kernel.org/pub/scm/linux/kernel/git/viro/vfs-2.6.git/ for-linus ?There's only one patch at the moment:Al Viro (1): mnt_longterm is there only on SMP fs/namespace.c | 31 ++++++++++++++++++++++++------- 1 files changed, 24 insertions(+), 7 deletions(-) | http://lkml.org/lkml/2011/1/16/146 | CC-MAIN-2014-10 | refinedweb | 147 | 64.3 |
Whenever you create a React project, one of the first things you need to install along with the
react package is the
react-dom package. Have you ever wondered why you need it?
It may come as a surprise, but we cannot render UI components with just the
react package. For rendering the UI to the browser, we have to use
react-dom. In this guide, we will explore managing DOM components with ReactDOM by creating a sample app. As you follow along, we will make some changes to our code to learn about the multiple methods available to you.
You can check out the code for the sample app on Github and the deployed site.
ReactDOM
ReactDOM renders components or JSX elements to the DOM. The ReactDOM object has only a handful of methods; you’ve probably used the
render() method, which is responsible for rendering the app in the browser.
The
react-dom package serves as the entry point to the DOM. We import it at the top of our project like this:
import ReactDOM from 'react-dom';
Before we go into the details of ReactDOM’s methods, let’s first understand why we need ReactDOM instead of just using the DOM.
Virtual DOM (VDOM) vs DOM
JavaScript and HTML can’t communicate directly with one another, so the DOM was developed to deal with this issue. When you open a webpage, the browser engine translates all of its content into a format that JavaScript can understand — a DOM tree.
The structure of this tree is identical to that of the corresponding HTML document. If one element is nested inside another in the HTML code, this will be reflected in the DOM tree.
You can see for yourself what the DOM looks like by opening the Elements tab in the developer tools panel of your browser. What you’ll see will look very similar to HTML code, except that rather than looking at HTML tags, what you’re actually seeing is elements of the DOM tree.
The DOM is the logical representation of a web page created by, and stored in, the user’s browser. The browser takes the site’s HTML and transforms it into a DOM, then paints the DOM to the user’s screen, making the site visible to the user.
Let’s see DOM in action. The diagram shows how the DOM sees the HTML:
<body> <nav> <ul> <li>Home</li> <li>Contact</li> </ul> </nav> <section class="cards"> <img src="" alt="" /> <div class="post-content"> <h1>Virtual DOM vs DOM</h4> </div> </section> </body>
The DOM has some problems, though. Imagine the user clicks on a button to remove an item. That node and all the other nodes depending on it will be removed from the DOM.
Whenever a browser detects a change to the DOM, it repaints the entire page using the new version. But do we really need to repaint the whole page? Comparing two DOMs to determine which parts have changed is very time consuming.
As a result, it’s actually faster for browsers to simply repaint the entire page whenever a user interacts with the site. That’s where the Virtual DOM comes in.
A Virtual DOM is when React creates their own representation of the DOM as a JavaScript object. Whenever a change is made to the DOM, the library instead makes a copy of this JavaScript object, makes the change to that copy, and compares the two JavaScript objects to see what has changed. It then informs the browser of these changes and only those parts of the DOM are repainted.
Making changes to JavaScript objects and comparing them is far faster than trying to do the same with DOMs. Since this copy of the DOM is stored in memory as a JavaScript object it’s called a Virtual DOM.
The Virtual DOM prevents unnecessary repaints by only repainting updated elements and groups. The VDOM is a lightweight, fast, in-memory representation of the actual DOM.
Even though React works with the VDOM whenever possible, it will still regularly interact with the actual DOM. The process by which React updates the actual DOM to be consistent with the VDOM is called reconciliation.
ReactDOM.render()
Now that we have a better understanding of the DOM and VDOM, we can start learning about our first method:
ReactDOM.render. Usage of the render method is as follows:
ReactDOM.render(element, container[, callback]) ReactDOM.render(<h1>ReactDOM</h1>, document.getElementById("app"))
The first argument is the element or component we want to render, and the second argument is the HTML element (the target node) to which we want to append it.
Generally, when we create our project with
create-react-app, it gives us a
div with the
id of a
root inside
index.html, and we wrap our React application inside this root div.
So, when we use the
ReactDOM.render() method, we pass in our component for the first argument, and refer to
id="root" with
document.getElementById("root") as the second argument:
<!DOCTYPE html> <html lang="en"> <head> <!-- ... --> </head> <body> <!-- ... --> <div id="root"></div> </body> </html>
// src/index.js import React from 'react'; import ReactDOM from 'react-dom'; // create App component const App = () => { return <div>Render Me!</div> } // render App component and show it on screen ReactDOM.render(<App />, document.getElementById('root'));
Goodbye
ReactDOM.render()
In June, the React team announced React 18, and with the new update, we will not be using
ReactDOM.render() anymore. Instead, we will be using
ReactDOM.createRoot.
The alpha version of React 18 is available, but it will take several months for the public beta. If you want to experiment with the React 18 alpha version, install it like this:
npm install [email protected] [email protected]
With React 18, we will use
ReactDOM.createRoot to create a root, and then pass the root to the render function. When you switch to
createRoot, you’ll get all of the new features of React 18 by default:
import ReactDOM from "react-dom"; import App from "App"; const container = document.getElementById("app"); const root = ReactDOM.createRoot(container); root.render(<App />);
ReactDOM.createPortal()
Our second method on ReactDOM is
createPortal.
Do you ever need to create an overlay, or modal? React has different functions to deal with modals, tooltips, or other features of that nature. One is the
ReactDOM.createPortal() function.
To render a modal, or overlay, we need to use the
z-index property to manage the order in which elements appear on the screen.
z-index allows us to position elements in terms of depth, along the z-axis.
However, as you know, we can only render one div, with all the other elements nested inside our root div. With the help of the
createPortal function, we can render our modals outside of the main component tree. The modal will be the child of the body element. Let’s see how.
In our
index.html we will add another div for the modal:
// index.html <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <div id="modal"></div> </body>
The
ReactDOM.createPortal() function takes two arguments: the first is JSX, or what we want to render on the screen, and the second argument is a reference to the element we want to attach to our modal:
// Modal.js import { createPortal } from 'react-dom'; const modalRoot = document.querySelector('#modal'); const Modal = ({ children }) => createPortal(children, modalRoot); export default Modal;
Now, to render our component, we can pass whatever we want to show between our modal component’s opening and closing tags. This will be rendered inside the modal component as
children. I have rendered the modal inside
App.js.
In our
App.js file, we have a button to open the modal. When the user interacts with the button, we are showing the modal along with a close button:
// App.js import React, { useCallback, useState } from 'react'; import Modal from '../Modal'; const App = () => { const [showModal, setShowModal] = useState(false); const openModal = useCallback(() => setShowModal(true), []); const closeModal = useCallback(() => setShowModal(false), []); return ( <div className='App'> <button onClick={openModal} Click To See Modal </button> {showModal ? ( <Modal> <div className='modal-container'> <div class='modal'> <h1>I'm a modal!</h1> <button onClick={closeModal}</button> </div> </div> </Modal> ) : null} </div> ); }; export default App;
ReactDOM.unmountComponentAtNode()
We use this method when we need to remove a DOM node after it’s mounted, and clean up its event handlers and state.
We will continue on with our code again, this time we will unmount our
root div:
ReactDOM.unmountComponentAtNode(container)
For the container, we are passing in the root div, so when the user clicks on the button, it will unmount the app.
If you try to unmount the
modal id, you will see an error. This is because the modal is not mounted, so it will return
false:
// App.js const App = () => { ReactDOM.unmountComponentAtNode(document.getElementById("root")); return ( <button onClick={handleUnmount} Unmount App </button> ) }
This code is enough to unmount the root.
ReactDOM.findDOMNode()
We know that we can render our DOM elements with the
render method. We can also get access to the underlying DOM node with the help of
findDOMNode method. According to the React documentation, this method is discouraged because it pierces the component abstraction.
NOTE:
findDOMNodemethod has been deprecated in StrictMode.
Generally, if you need to refer to any DOM element, it’s advised to use the
useRef hook. In most cases, you can attach a ref to the DOM node and avoid using
findDOMNode at all.
Another key point is the Node element that you want to access must be mounted, which means it must be in the DOM. If it’s not mounted,
findDOMNode returns null. Once you get access to the mounted DOM node, you can use the familiar DOM API to inspect the node.
findDOMNode takes one parameter, and it’s the component:
ReactDOM.findDOMNode(component)
We will continue with the code that we used on the
createPortal method. I created a new button and added the text
Find The Modal Button and Change its Background Color, and added an
onClick handler function. With this function, I accessed its
className with the
document.querySelector method and changed its background color to black:
const App = () => { const handleFindDOMNode = () => { const node = document.querySelector('.node'); ReactDOM.findDOMNode(node).style. Find The Modal Button and Change its Background Color </button> ) }
ReactDOM.hydrate() and Server-Side Rendering (SSR)
The
hydrate method will help us pre-render everything on the server side, then send the user the complete markup. It is used to add content to a container that was rendered by the ReactDOMServer.
This may sound like a gibberish right now, but the main takeaway is that we can render our React applications on the client or server side. Here’s a quick overview of the main differences between Client-Side Rendering (CSR) and Server-Side Rendering (SSR).
Client-Side Rendering (CSR)
When we create and run our project with
create-react-app, it doesn’t show the contents of the page:
As you can see from the screenshot, we have only our divs and a reference to our JavaScript bundle, nothing else. So, this is actually a blank page. This means when we first load our page, the server makes a request to the HTML, CSS, and JavaScript. After the initial render, the server checks our bundled JavaScript (or React code, in our case) and paints the UI. This approach has some pros and cons.
Pros:
- Quick
- Static deployment
- Supports Single Page Applications (SPA)
Cons:
- Renders a blank page at initial load
- Bundle size may be large
- Not good for SEO
Server- Side Rendering (SSR)
With Server-Side Rendering, we don’t render an empty page anymore. With this approach, the server creates static HTML files which the browser renders.
This is how SSR works: when the user requests a website, the server renders the static version of the app, allowing users to see the website is loaded. The website is not interactive yet, so when the user interacts with the app, the server downloads the JavaScript and executes it.
The site becomes responsive by replacing the static content with the dynamic content.
ReactDOM.hydrate() function is actually called on the load event of these scripts and hooks the functionality with the rendered markup.
If you are curious, when we create our project with SSR, we can see the HTML and JavaScript code rendered at initial load:
Pros:
- Better performance
- Great for SEO to help us create easily indexable and crawlable websites
- Fast interactivity
- Speeds uploading time by running React on the server before serving the request to the user.
Cons:
- Creates lots server requests
- If you have lots of interactive elements on your site, it can slow down the rendering
Demo of
ReactDOM.hydrate()
As you can imagine, for this to work, we need to create a server. We will be creating the server with Express, but first we need to do some cleanup.
To run a Node.js server using
hydrate, we need to remove all references to the
window and
document, because we will render our markup in the server, not in the browser.
Let’s go to the
Modal.js file and move the
document.querySelector inside the modal component:
// Modal.js import { createPortal } from 'react-dom'; let modalRoot; const Modal = ({ children }) => { modalRoot = modalRoot ? modalRoot : document.querySelector('#modal'); return createPortal(children, modalRoot); }; export default Modal;
Next up, we need to change
ReactDOM.render to
ReactDOM.hydrate inside the
src/index.js file:
ReactDOM.hydrate( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
Now, we can create our server. Create a new folder called
server and create a file inside this folder named
server.js. Install Express with
npm install express:
// server/server.js import express from 'express'; import fs from 'fs'; import path from 'path'; import React from 'react'; import { renderToString } from 'react-dom/server'; import App from '../src/App'; const app = express(); app.use('^/$', (req, res, next) => { fs.readFile(path.resolve('./build/index.html'), 'utf-8', (err, data) => { if (err) { console.error(err); return res.status(500).send('Error'); } return res.send( data.replace( '<div id="root"></div>', `<div id="root">${renderToString(<App />)}</div>` ) ); }); }); app.use(express.static(path.resolve(__dirname, '..', 'build'))); app.listen(3000, () => { console.log('Listening on port 3000'); });
Here we have required Express, the
fs (file system) module, the path, React,
ReactDOMServer.renderToString, and
App from our src folder.
The
ReactDOMServer.renderToString returns the static HTML version of our app.
Next, run the build command
npm run build to create a
build folder. Configure Babel, then install
npm i @babel/preset-env @babel/preset-react @babel/register ignore styles. Finally, create a new file named
server/index.js:
// server/index.js require('ignore-styles'); require('@babel/register')({ ignore: [/(node_modules)/], presets: ['@babel/preset-env', '@babel/preset-react'], }); require('./server');
Add a script for SSR in
package.json:
"ssr": "node server/index.js". Run the server with
npm run ssr.
Remember, if you make changes in your app, first run
npm run build, and then
npm run ssr.
Changes to
hydrate with React 18
In React 18, a new Suspense-based SSR architecture is introduced. The
hydrate method will also be replaced by
hydrateRoot.
Conclusion
We have covered a lot about ReactDOM. To summarize, here are the key takeaways we learned throughout this post:
- React uses a Virtual DOM, which helps us prevent unnecessary DOM repaints, and updates only what has changed in the UI
- We use the
rendermethod to render our UI components to the browser, the most-often used ReactDOM method
- We use the
createRootmethod instead of the
rendermethod with React 18
- We can create modals and tooltips with the
createPortalmethod
- We can unmount a component with the
unmountComponentAtNodemethod
- We can get access to any DOM node with the
findDOMNodemethod, but the best way is to use
refinstead
- We can use SSR in React with the help of the
hydratemethod, just be prepared for React 18 and Suspense-based SSR architecture
- SSR helps us pre-render everything on the server side for better SEO optimization. | https://blog.logrocket.com/managing-dom-components-reactdom/ | CC-MAIN-2022-05 | refinedweb | 2,690 | 55.95 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.