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 |
|---|---|---|---|---|---|
By: Daniel Horn
Abstract: This paper discusses how to take a useful Java class, FontChooser, and extend its features even though the visibility and member access modifiers would ordinarily prevent one from doing so.
Among the many useful classes provided by JBuilder is one called FontChooser which
makes it easy to display a dialog box from which a user can select a font.
In a recent project in which I used FontChooser, I encountered some limitations with
this class. I wished to change its default behavior in two ways by:
One might think that the solution to this would be to derive a new class from
FontChooser, but things are not as simple as that. First of all,
FontChooser is not a Dialog, nor even a Panel; it's just an Object. When
the user makes the call to FontChooser.showDialog(), an instance of a
FontChooserDialog is created to display the information represented by the
FontChooser. There are two problems here: first, FontChooserDialog
is a non-public class defined in FontChooser.java which means that access to it
is restricted to members of the same package, com.borland.dbswing; second, even
if we could derive from the FontChooserDialog class, the FontChooser class
provides no way to assign it as its dialog.
This note will demonstrate a loophole in the member access settings in
FontChooser.java that let me workaround these limitations and provide the
functionality I needed.
The example code for this note was written and tested with JBuilder 9
Enterprise. It is important to remember that there is no guarantee that
this code will work with future versions of JBuilder as Borland may change
com.borland.dbswing.FontChooser at some point in the future.
As software source code copyrighted by Borland, there are licensing issues
and limitations with respect to using FontChooser.java. Please check the
license terms that come with your version of JBuilder before redistributing any
program or code based on the specific code provided here. The
MyFontChooser.java code derived from FontChooser.java is meant solely as an
example of how to workaround member access settings in certain situations.
The source code () for a sample Java application, the
FontChooserDemoApplication, demonstrates how to use a class called MyFontChooser
that is derived from FontChooser. There's not much to the program:
run it and choose the Options | Fonts... menu item to see the modified font
display dialog.
MyFontChooser.java overrides the FontChooser.showDialog() method to apply a
"PreferredSize" property to the dialog box and to apply the
"Reset fonts to defaults" functionality if the checkbox is selected
when the OK button is pressed. Rather than cut and paste functionality
from the FontChooserDialog class defined in FontChooser.java, I just use this
class.
But what a minute... didn't I say earlier that deriving from the FontChooser
class wouldn't work?
Well that's true... except if the MyFontChooser class is defined within the
same package as FontChooser, namely com.borland.dbswing. Just because this
package comes from somewhere else, there's nothing to prevent the compiler from
being fooled that code that I write is part of that package.
Most of the code written is in showDialog() and most of that simply
duplicates functionality in the base class version.
There are a few differences because of the new functionality added. The
rest of the differences are the result of using accessor functions to obtain
private members in the base class. For example, code that reads
if (availableFonts != null) {
dialog.setAvailableFonts(availableFonts);
}
if (availableFonts != null) {
dialog.setAvailableFonts(availableFonts);
}
in the base class version of the function, needs to be replaced by
Font[] availableFonts = getAvailableFonts();
if (availableFonts != null)
{
dialog.setAvailableFonts(availableFonts);
}
Font[] availableFonts = getAvailableFonts();
if (availableFonts != null)
{
dialog.setAvailableFonts(availableFonts);
}
in the derived class.
See MyFontChooser.java for the rest of the details.
See the jMenuItemFonts_actionPerformed
method in FontChooserDemoFrame.java for sample code on using this class and how
to set its preferred size.
Also, don't be fooled by the "frame" and
"setFrame()" members in FontChooser. The "frame"
is merely used as a window relative to which the FontChooserDialog is
positioned. Take a look at showDialog() and you'll see that if you prefer
to, say, always have the dialog centered in the screen, then the dependency on
the "frame" could easily be removed.
This example was not presented as a recommended way of working around member
access restrictions placed by a base class but as a reminder that the member access constructs in the programming
language are really guidelines as to how the members are to be used.
Unless a member is labeled "private", it can be accessed by using
the same trick I used for dbswing (i.e., by deriving a new class within the same
package).
Don't confuse member access rules with security; for example, user name and
password credentials stored as non-private members of a (non-final) class can be
read using this technique.
A better solution for attaining the functionality I want added would be to
have the class vendor, Borland, make changes to FontChooser and
FontChooserDialog that let developers customize them (hint, hint). In
particular, this would include changing FontChooserDialog to public (so that it
can be derived from) and changing FontChooser so that the showDialog() can
display an assigned dialog (derived from FontChooserDialog).
Questions, comments, and suggestions may be sent to the
author at dan@nerds.com ; use the title of the article or the words BDN
Article in the email subject.
Server Response from: SC1 | http://edn.embarcadero.com/article/31295 | crawl-002 | refinedweb | 916 | 55.03 |
DNS : Domain Name System
- Tyrone Fleming
- 3 years ago
- Views:
Transcription
1 1/30 DNS : Domain Name System Surasak Sanguanpong Last updated: May 24, 1999 Outline 2/30 DNS basic name space name resolution process protocol configurations
2 Why need DNS? 3/30 host table /etc/hosts compiled from HOST.TXT (maintain by SRI NIC) simple text file with has IP address to name mapping problems traffic and load name collision consistency A hierarchical name with distributed control is needed DNS basic 4/30 DNS is a distributed database TCP/IP applications use DNS to map hostname to IP address map IP address to hostname provide routing information mail > mail...ac.th handle aliases is actually is1...ac.th
3 Naming Scheme 5/30 cc...ac.th building tree from top to bottom th more specific ac name space is a tree of domain names are case-insensitive cc cc...ac.th Domain Name Space 6/30 root arpa com edu gov int mil net org au th in-addr usu ac cc cc.usu.edu tu cc cc...ac.th arpa domains generic domains country domains
4 DNS Management 7/30 managed by NIC root com th managed by Internic Thailand NIC manages root and top level domain name local admins manage 3rd level or more ac tu or manage by tu managed by Domain Name Concept 8/30 label domain name domain name every node has a label (except root) the list of labels, starting at that node, working up to the root, using a. to separate e.g..ac.th,..ac.th th ac absolute domain name absolute domain name domain name that ends with a period e.g. cc...ac.th. relative domain name relative domain name name to be completed e.g. cc cc
5 Domains 9/30 domain subtree of the domain name space th ac.th domain ac.ac.th domain tu cc cc...ac.th node Domains and Zones Zone is a subtree for which naming authority has been delegated.ac.th domain.ac.th zone ee.ac.th zone.ac.th domain ee 10/30 sci kps rdi lib sci kps rdi lib case 1 : single DNS administration case 2 : and have authority for their zones
6 Name Servers 11/30 Name server : Server that store information about the zone ns..ac.th ee ns...ac.th responsibility for..ac.th zone responsibility for.ac.th zone sci kps rdi lib ns...ac.th responsibility for..ac.th zone Type of Name Servers Primary Name server gets the data for zones from files on the host it runs on Secondary Name server gets its zone data from the primary for redundancy and workload distribution 12/30 nontri..ac.th: secondary ns..ac.th : primary ee ns...ac.th : primary ns2...ac.th : secondary sci kps rdi lib ns...ac.th: primary cc...ac.th: secondary
7 Zone Transfer 13/30 Secondary Name Server pulls zone data over from the primary called zone transfer. primary for.ac.th secondary for..ac.th ns..ac.th nontri..ac.th ns...ac.th primary for..ac.th secondary for.ac.th secondary for..ac.th ns2...ac.th secondary for..ac.th secondary for.ac.th secondary for..ac.th cc...ac.th secondary for..ac.th ns...ac.th primary for..ac.th secondary for.ac.th secondary for..ac.th Root Name Server 14/30 name server must contact other name servers for non local IP it has to know IP address of the top most server called root name server root name server - provide the names and address of the name server authoritative for top level domain name I have to connect root, when I don t have more info ns..ac.th root
8 Root Name Server (cont.) 15/30 13 root servers are currently available in Internet (Last updated Aug 97) Name Resolution Process 16/30 name server address of ask th name servers root name server address of ask ac.th name servers th name server th address of ask.ac.th name server ac.th name server ac or address of ask ns..ac.th name server.ac.th name server tu address of address is ns..ac.th name server www address is address of resolver
9 Reverse Resolution root 17/30 arpa in-addr in-addr.arpa domain in reverse direction of IP address au ac th tu cc cc...ac.th in-addr.arpa Caching 18/30 all name servers employ a cache to reduce the DNS traffic standard UNIX keep cache in name server with time-out cache data is non-authoritative
10 DNS message format (I) 19/ identification:16 flags:16 number of questions :16 number of authority RRs :16 1 or more questions 1 or more answers 1 or more authority 1 or more additional information number of answer RRs:16 number of additional RRs:16 fixed header query reply fixed 12 byte header with 4 variable lth fields DNS message format is defined for both queries and answers DNS message format (II) 20/ identification:16 identification:16 flags:16 flags:16 set by the client and return by the server lets the client match responses to requests
11 DNS message format (III) 21/30 identification:16 identification:16 flags:16 flags:16 QR QR opcode opcode AA AA TC TC RD RD RA RA (zero) (zero) rcode rcode QR opcode AA TC RD RA rcode 0 query, 1 response 0 standard query, 1inverse query, 2server status request 0 authoritatived answer,1 non authoritatived answer 1 truncated. using UDP, reply was>512 bytes, return only 512 bytes 1 recursive desired, 0 iterative 1 recursion available (server support recursion) return code : 0no error, 3name error DNS message format (IV) 22/30 questions questions :32 :32 query query name name query query type type query query class class query class normally 1 means Internet Address query type indicates desired response A 1 IP address NS 2 name server CNAME 5 canonical name PTR 12 pointer record query name is the name being loop, sequence of label begins with 1-byte count 3www322ac2th0 HINFO 13 host info MX 15 mail exchange record
12 DNS message format (V) 23/30 reply 1 or more answers 1 or more authority 1 or more additional information these three fields share a common resource record (RR) domain domain name name type type class class time-to-live resource lth resource data data domain name : corresp. response name, (query name format) type : response RR type code (see query type) time-to-live : cache life time of RR (often day) resource lth : specify the size of resource data resource data : the answer, e.g. IP address or other type Operations 24/30 use port 53 typically UDP request and reply if answer is too big, use TCP ip ip hdr hdr UDP UDP hdr hdr DNS DNS hdr hdr query query answer#1 answer#2
13 Resolver file 25/30 resolver must have address for local name server /etc/resolv.conf on UNIX /etc/resolv.conf # domain domain..ac.th # list of name server nameserver nameserver nameserver Setting up DNS 26/30 BIND (Berkeley Internet Name Domain) package /usr/somewhere/in.named - BSD named DNS server /etc/named.boot - named configuration (tell named where to find database files)
14 Sample named.boot 27/30 ; Boot file for server ns...ac.th. directory /usr/local/named cache. root.cache primary localhost. primary/local primary in-addr.arpa primary/local.rev primary..ac.th primary/ secondary.ac.th secondary/ secondary cpc..ac.th secondary/cpc secondary..ac.th secondary/ secondary in-addr.arpa secondary/.rev primary in-addr.arpa primary/zone/zone32 primary in-addr.arpa primary/zone/zone33 : : : New named.conf format 28/30 BIND Version 8 defines a new format of boot file : named.conf options { directory "/usr/local/named"; }; zone "." { type hint; file "root.cache"; }; zone "localhost." { type master; file "primary/local"; }; zone " in-addr.arpa" { type master; file "primary/local.rev"; }; zone "..ac.th" { type master; file "primary/"; }; zone ".ac.th" { type slave; masters { ; }; : :
15 Sample database file 29/30 ; address file for server ns...ac.th. IN SOA ns...ac.th. dnsadmin.ns...ac.th. ( ; Last Updated May 13, ; Refresh every 3 hours 3600 ; Retry every 1 hour ; Expire after 30 days ; Minimum TTL of 1 day ) ; Name Servers IN NS ns...ac.th. IN NS ns...ac.th. IN NS ns..ac.th. (continue on next page) Sample database file (cont.) 30/30 ; Mail Hubs for the Domain IN MX 10 mailhost...ac.th. IN MX 15 cc...ac.th. ; AI Lab mars IN HINFO "MP 1101D/DECstation " IN MX 10 mailhost...ac.th. IN A maspar IN CNAME mars...ac.th. saturn IN HINFO "SPARCstation 2" "SunOS 4.1.3" IN MX 10 mailhost...ac.th. IN A ailab2 IN CNAME saturn...ac.th.
Motivation. Domain Name System (DNS) Flat Namespace. Hierarchical Namespace
Motivation Domain Name System (DNS) IP addresses hard to remember Meaningful names easier to use Assign names to IP addresses Name resolution map names to IP addresses when needed Namespace set of all), Domain Name System
DNS Domain Name System Domain names and IP addresses People prefer to use easy-to-remember names instead of IP addresses Domain names are alphanumeric names for IP addresses e.g., neon.cs.virginia.edu,.
Applications and Services. DNS (Domain Name System)
Applications and Services DNS (Domain Name Service) File Transfer Protocol (FTP) Simple Mail Transfer Protocol (SMTP) Malathi Veeraraghavan Distributed database used to: DNS (Domain Name System) map between (DNS) Fundamentals
Domain Name System (DNS) Fundamentals Mike Jager Network Startup Resource Center mike.jager@synack.co.nz These materials are licensed under the Creative Commons Attribution-NonCommercial 4.0 International
Domain Name System. Overview. Domain Name System. Domain Name System
Overview Domain Name System We look first at how the Domain Name System (DNS) is implemented and the role it plays in the Internet We examine some potential DNS vulnerabilities and in particular we consider
ECE 4321 Computer Networks. Network Programming
ECE 4321 Computer Networks Network Programming Name Space System.Net Domain Name System (DNS) To resolve computer naming Host database is split up and distributed among multiple systems on the Internet
DNS Domain Name System
Domain Name System DNS Domain Name System The domain name system is usually used to translate a host name into an IP address Domain names comprise a hierarchy so that names are unique, yet easy to remember.
- Domain Name System -
1 Name Resolution - Domain Name System - Name resolution systems provide the translation between alphanumeric names and numerical addresses, alleviating the need for users and administrators to memorize
DNS Service on Linux. Supawit Wannapila CCNA, RHCE supawit.w@cmu.ac.th
DNS Service on Linux Supawit Wannapila CCNA, RHCE supawit.w@cmu.ac.th Host Name Resolution Common Host Name Service Files (/etc/hosts and /etc/networks) DNS (/etc/resolv.conf) Multiple client-side resolvers:
19 Domain Name System (DNS)
CHAPTER 9 Domain Name System (DNS) I n this chapter, we discuss the second application program, Domain Name System (DNS). DNS is a client/server application program used to help other application programs.
Domain Name System (DNS)
Chapter 18 CSC465 Computer Networks Spring 2004 Dr. J. Harrison These slides are based on the text TCP/IP Protocol Suite (2 nd Edition) Domain Name System (DNS) CONTENTS NAME SPACE DOMAIN NAME SPACE DISTRIBUTION
The Domain Name System (DNS)
The Domain Name System (DNS) Columbus, OH 43210 Jain@CIS.Ohio-State.Edu 24-1 Overview Naming hierarchy hierarchy Name resolution Other information in name servers 24-2
DNS. Computer networks - Administration 1DV202. fredag 30 mars 12
DNS Computer networks - Administration 1DV202 DNS History Who needs DNS? The DNS namespace How DNS works The DNS database The BIND software Server and client configuration The history of DNS RFC 882,
CS3250 Distributed Systems
CS3250 Distributed Systems Lecture 4 More on Network Addresses Domain Name System DNS Human beings (apart from network administrators and hackers) rarely use IP addresses even in their human-readable dotted
More Internet Support Protocols
Domain Name System (DNS) Ch 2.5 More Internet Support Protocols Problem statement: Average brain can easily remember 7 digits On average, IP addresses have 10.28 digits We need an easier way to remember
DNS. Computer Networks. Seminar 12
DNS Computer Networks Seminar 12 DNS Introduction (Domain Name System) Naming system used in Internet Translate domain names to IP addresses and back Communication works on UDP (port 53), large requests/responses
Goal of this session
DNS refresher Overview Goal of this session What is DNS? How is DNS built and how does it work? How does a query work? Record types Caching and Authoritative Delegation: domains vs zones Finding the error:
1 DNS Packet Structure
Fundamentals of Computer Networking Project 1 Primer: DNS Overview CS4700/CS5700 Fall 2009 17 September 2009 The DNS protocol is well-documented online, however, we describe the salient pieces here for
DNS Conformance Test Specification For Client
DNS Conformance Test Specification For Client Revision 1.0 Yokogawa Electric Corporation References This test specification focus on following DNS related RFCs. RFC 1034 DOMAIN NAMES - CONCEPTS AND FACILITIES
Internetworking with TCP/IP Unit 10. Domain Name System
Unit 10 Domain Name System Structure 10.1 Introduction 10.2 Fully Qualified Domain Names (FQDNs) Generic Domains Country Domains 10.3 Mapping domain names to IP addresses 10.4 Mapping IP Addresses to Domain
Introduction BIND. The DNS Protocol. History (1) DNS. History (2) Agenda
History (1) DNS Domain Name System The Internet's Name Service even in the early days of the Internet, hosts have been also identified by s e.g. /etc/hosts.txt file on UNIX systems all s have been maintained,
Domain Name Server. Training Division National Informatics Centre New Delhi
Domain Name Server Training Division National Informatics Centre New Delhi Domain Name Service (DNS) I. History of DNS II. DNS structure and its components III. Functioning of DNS IV. Possible Configurations
Internet Engineering 241-461 Robert Elz kre@munnari.oz.au kre@coe.psu.ac.th DNS The Domain Name System Kurose & Ross: Computer Networking Chapter 2 (2.5) James F. Kurose
NET0183 Networks and Communications
NET0183 Networks and Communications Lecture 25 DNS Domain Name System 8/25/2009 1 NET0183 Networks and Communications by Dr Andy Brooks DNS is a distributed database implemented in a hierarchy of many
K-Root Name Server Operations
K-Root Name Server Operations Andrei Robachevsky andrei@ripe.net 1 Outline Root Server System brief update Architecture Current locations Anycast deployment K.root-servers.net Server Major milestones Current
Motivation. Users can t remember IP addresses. Implemented by library functions & servers. - Need to map symbolic names (.
Motivation 2 cs.princeton.edu User 1 user @ cs.princeton.edu Name server Mail program 192.12.69.5 3 TCP 192.12.69.5 4 192.12.69.5 5 IP Users can t remember IP addresses - Need to map symbolic names ()
Creating a master/slave DNS server combination for your Grid Infrastructure
Creating a master/slave DNS server combination for your Grid Infrastructure When doing a Grid Infrastructure installation, a DNS server is needed to resolve addresses for the cluster- scan addresses. In
Introduction to DNS and Application Issues related to DNS. Kirk Farquhar
Introduction to DNS and Application Issues related to DNS Kirk Farquhar 1 Content What is DNS? How it all works Setting up your domain Creating your nameserver files The Resolver Testing Firewall configuration
In order to find resources on the network, computers need a system to look up the location of resources. This video looks at the DNS records that contain information about resources and services on the
by telnet 142.58.110.2. 1 E.g., the machine fraser has IP address 142.58.110.2. You can login to fraser from anywhere in the world
21 3.5 Naming and Look-Up Service 3.5.1 Host addresses and Port numbers A client requiring a service needs to lote a server that will provide the desired service. In JavaRMI discussed in 3.3, rmiregistry
CS640: Computer Networks. Naming /ETC/HOSTS
CS640: Computer Networks Aditya Akella Lecture 17 Naming and the DNS Naming Need naming to identify resources Once identified, resource must be located How to name resource? Naming hierarchy How do we
Introduction to the Domain Name System
CHAPTER 14 The Domain Name System (DNS) handles the growing number of Internet users. DNS translates names, such as, into IP addresses, such as 192.168.40.0 (or the more extended IPv6 addresses),
Application-layer Protocols
Application-layer Protocols Based on Notes by D. Hollinger Based on UNIX Network Programming, Stevens, Chapter 9 Also Java Network Programming and Distributed Computing, Chapter 3,8 Also Online Java Tutorial,
IPv6 support in the DNS
IPv6 support in the DNS How important is the DNS? Getting the IP address of the remote endpoint is necessary for every communication between TCP/IP applications Humans are unable to memorize millions of
Domain Name System DNS
CE443 Computer Networks Domain Name System DNS Behnam Momeni Computer Engineering Department Sharif University of Technology Acknowledgments: Lecture slides are from Computer networks course thought
Understanding DNS (the Domain Name System)
Understanding DNS (the Domain Name System) A white paper by Incognito Software January, 2007 2007 Incognito Software Inc. All rights reserved. Understanding DNS (the Domain Name System) Introduction...2
Chapter 7 Implementing Domain Name System (DNS)
[Previous] [Next] Chapter 7 Implementing Domain Name System (DNS) About This Chapter In this chapter, you will learn how Domain Name System (DNS) is used to resolve host names on your local area network
Introduction to DNS CHAPTER 5. In This Chapter
297 CHAPTER 5 Introduction to DNS Domain Name System (DNS) enables you to use hierarchical, friendly names to easily locate computers and other resources on an IP network. The following sections describe
The role of JANET CSIRT
The role of JANET CSIRT Bradley Freeman JANET(UK) CSIRT Member UKNOF 15 21 st January 2010 bradley.freeman@ja.net Copyright JNT Association 2009 1 What to expect Overview of how we detect and deal with
The Domain Name System: An Integral Part of the Internet. By Keiko Ishioka
The Domain Name System: An Integral Part of the Internet By Keiko Ishioka The Domain Name System (otherwise known as the Domain Name Server system) (DNS) is a distributed database that is accessed by anyone
DNS and BIND. David White
DNS and BIND David White DNS: Backbone of the Internet Translates Domains into unique IP Addresses i.e. developcents.com = 66.228.59.103 Distributed Database of Host Information Works seamlessly behind
Names vs. Addresses. Flat vs. Hierarchical Space. Domain Name System (DNS) Computer Networks. Lecture 5: Domain Name System
Names vs. Addresses Computer Networks Lecture 5: Domain Name System Names are easier for human to remember vs. 141.213.4.4 Addresses can be changed without changing names move
Domain Name System (DNS)
Lab Objectives Domain Name System (DNS) Acquiring skills related to the Domain Name System (DNS) functions Practical studying of DNS protocol in the process of its functioning Background Information DNS.
Domain Name System Richard T. B. Ma
Domain Name System Richard T. B. Ma School of Computing National University of Singapore CS 3103: Compute Networks and Protocols Names Vs. Addresses Names are easier for human to remember
3. The Domain Name Service
3. The Domain Name Service n Overview and high level design n Typical operation and the role of caching n Contents of DNS Resource Records n Basic message formats n Configuring/updating Resource Records,
Naming. Name Service. Why Name Services? Mappings. and related concepts
Service Processes and Threads: execution of applications or services Communication: information exchange for coordination of processes But: how can client processes (or human users) find the right server
Services: DNS domain name system
Services: DNS domain name system David Morgan Buying numbers and names numbers are IP addresses you buy them from an ISP the ISP makes sure those addresses go to your place the names are domain names you
The Domain Name System (DNS)
The Domain Name System (DNS) Each Internet host is assigned a host name and an IP address Host names are structured character strings, e.g., IP addresses are 32 bit integers, e.g., 129.186.3.6)
Domain Name System (or Service) (DNS) Computer Networks Term B10
Domain Name System (or Service) (DNS) Computer Networks Term B10 DNS Outline DNS Hierarchial Structure Root Name Servers Top-Level Domain Servers Authoritative Name Servers Local Name Server Caching and
DNS + DHCP. Michael Tsai 2015/04/27
DNS + DHCP Michael Tsai 2015/04/27 lubuntu.ova DNS + DHCP DNS: domain name < > IP address DHCP: gives you a IP + configuration when you joins a new network DHCP = Dynamic Host Configuration
Understand Names Resolution
Understand Names Resolution Lesson Overview In this lesson, you will learn about: Domain name resolution Name resolution process steps DNS WINS Anticipatory Set 1. List the host name of 4 of your favorite | http://docplayer.net/16732490-Dns-domain-name-system.html | CC-MAIN-2020-05 | refinedweb | 3,512 | 54.83 |
# $tcsh: BUGS,v 3.5 2006/03/02 18:46:44 christos Exp $ ============ Bugs in TCSH ============ -IAN! idallen@ncf.ca April 2002 -------------------------------------------------------------------------------- | *FIXED* | From: idallen | Subject: Can't redirect output of "source" | % echo "date" >file | % source file >output | Thu Sep 3 17:47:19 EDT 1987 -------------------------------------------------------------------------------- From: idallen Subject: nice is not cumulative % nice date % nice nice date Both have a nice of 4; nice does not accumulate. From: idallen Subject: no warning on integer overflow % @ x=99999999999999999999999 % echo $x -159383553 From: idallen Subject: goto seeks backwards in terminal input % goto x goto? ignored goto? ignored goto? ignored goto? x: % goto x The terminal is now hung - you have to break out. From: idallen Subject: nice applied to too many commands % nice +20 simple `long` The CSH shell applies the nice to both commands "simple" and "long". From: idallen Subject: redirection always happens in single-line "if" if ( 0 ) echo hi > date The file date is created empty. From: idallen Subject: Expanding variable with newline generates syntax error % set x="abc\ def" % echo "$x" Unmatched ". From: idallen Subject: Expanding variable with newline generates extra word % set x="abc\ def" % echo $x abc def % set y=( $x ) ; echo $#y 3 From: idallen Subject: Modifier ":e" doesn't work on history CSH is missing an entry in a case statement for it. From: idallen Subject: Shell messages appear on stdout; get redirected If a program in a shell script exits with a signal that the shell reports (e.g. Terminated), the report appears on standard output and if the output of the shell script is redirected the report gets sent there and you never find out. From: Steve Hayman <sahayman> Subject: No error message given for failure to NICE % nice -10 date Fri May 30 12:11:12 EDT 1986 CSH never checks the error returns from nice(). From: Ray Butterworth <rbutterworth> Subject: CSH history reading takes '#' as a comment % echo a b # c d a b # c d % exit % login % history ... 99 echo a b '#' indicates a comment when reading from a shell script file, and of course CSH thinks it is reading from a file when it reads the history back in. From: idallen Subject: csh: No current job, even if only one job % somecommand ^Z Suspended % bg [1] somecommand & % fg fg: No current job. The C shell always turns off the current job indicator for a job that is put in the background with "bg" -- even if it is the only job. From: idallen (Ian! D. Allen) Subject: Redirection ignored inside if ( { cmd >xxx } ) .... % if ( { date >out } ) echo hi Sun Apr 14 13:24:31 EDT 2002 hi The shell does not set up its file descriptors for the forked command. The redirection is completely ignored. >From idallen Subject: Error in CSH script causes script exit If a script has an error in a built-in command (e.g. redirection file not found), the script exits instead of continuing. From: idallen (Ian! D. Allen) Subject: Variables $$, $# don't accept :-modifiers echo $$:q $#:q 12345:q 0:q From: idallen (Ian! D. Allen) Subject: Variable $* (a synonym for argv) doesn't accept subscripts. % set argv=( a b c d ) % echo $argv[2] b % echo $*[2] echo: No match. >From idallen Subject: Using WHICH from CSH The WHICH command tells the wrong thing if you've created a new file and haven't done a REHASH. WHICH thinks you get the new file, but the CSH will give you the old one. From: idallen (Ian! D. Allen) Subject: Redirected input to built-in functions misbehaves badly % date | echo hi hi % % jobs [1] + Running date | Note the duplicate prompt and spurious job entry. % % date | echo hi hi % % date | echo hi hi % % jobs [1] + Running date | [2] - Running date | [3] Running date | % fg date | % fg date | fg: No such job (badjob). % fg [tcsh shell hangs here in an infinite loop] Just a general mess of mishandled processes. From: idallen (Ian! D. Allen) Subject: stopped pipes generate spurious job ID % date | sleep 99 ^Z Suspended [1] 123 456 >From idallen(idallen ) Subject: NICE and NOHUP have no effect as last component of sub-shells. % nice +10 ps -laxtd0 UID PID PPID CP PRI NI RSS WCHAN STAT TT TIME COMMAND 47 3559 1 0 15 0 33 ff000 S d0 0:16 -csh (csh) 47 7606 3559125 76 10 23 R N d0 0:01 ps -laxtd0 % (nice +10 ps -laxtd0) UID PID PPID CP PRI NI RSS WCHAN STAT TT TIME COMMAND 47 3559 1 3 15 0 33 ff000 S d0 0:16 -csh (csh) 47 7605 3559 92 48 0 23 R d0 0:01 ps -laxtd0 % (nice ps lx) ... Shows no nice. % (nice ps lx;date) ... Works. % (nohup sleep 999)& ... Doesn't ignore SIGHUP. % (nohup sleep 999;date)& ... Works. % echo `nice ps lx >/dev/tty` ... Shows no nice. % echo `nice ps lx >/dev/tty;date` ... Works. % echo `nohup sleep 999` ... Doesn't ignore SIGHUP. % echo `nohup sleep 999;date` ... Works. >From idallen Subject: you can't nest back-quotes % echo ` echo \`pwd\` ` Unmatched `. From: idallen (Ian! D. Allen) Subject: GLOB not applied to names in setenv or unsetenv % setenv `echo abc` def It doesn't set abc, it sets the nasty variable: `echo abc` % unsetenv `echo abc def ghi` Doesn't unset abc or def or ghi >From idallen Thu Mar 15 09:48:35 1984 Subject: Stopping jobs in list of command names throws away the rest. % a ; b ; c CSH documents that if you stop B, C will immediately start. It doesn't. The rest of the list gets thrown away. From: idallen (Ian! D. Allen) Subject: Stopping jobs in source'd file aborts the rest of the file. With the file TEST containing: mail echo Hi There you never see this and typing % source TEST and then using ^Z to stop MAIL, the rest of the TEST file is abandoned. This is especially annoying in one's .login or .cshrc. >From idallen Subject: CSH doesn't handle EXIT when it sees it. % date; exit 99 ; date ; date Wed Mar 14 19:21:51 EST 1984 Wed Mar 14 19:21:52 EST 1984 Wed Mar 14 19:21:53 EST 1984 The shell doesn't flush pending input when the EXIT is seen. The shell then exits with status 0 instead of status 99. >From idallen Subject: CSH mishandles suspend in subshells. % ( date; suspend; date ) Sun Mar 4 01:28:28 EST 1984 Suspended % fg ( date; suspend; date ) Suspended (tty input) ...and you can never get it started again. >From idallenSun Mar 18 01:28:16 Subject: ECHO mis-handles interrupts and errors in back-quotes % echo `sleep 999` <hit break> [1] 24244 % jobs [1] Interrupt ` ... ` Note the inability of CSH to tell you the command name used inside the back-quotes. >From idallen Subject: CSH botches $#X where X is environment var % echo $#path 4 % echo $#PATH /usr/ucb:/bin:/usr/bin:/usr/public >From idallen Wed Apr 18, 1984 Subject: Inconsistent handling of variables The manual says that "set x=word" assigns a single word to x. To assign multiple words, one is supposed to use "set x=(words)". But, CSH allows "set x=`date`", which sets x to the many words resulting from `date`, and $x[1] prints "Mon". One observes that if x and y are single-word variables, the statements: % set x=word2 % set y[1]=word2 are identical; both replace the contents of the variable with word2. But, you can't assign a word to y[1] if y doesn't exist, even though you can (of course) assign a word to plain "y" if y doesn't exist. >From idallen(Ian! D. Allen) Subject: extra next level when nested single-line IF line ends in THEN Any IF line that ends in THEN is taken as another nesting level, and requires a corresponding ENDIF: if ( 0 ) then if ( 0 ) echo This line ends with then endif echo You do not see this. endif # This shouldn't be needed; but it is. echo Now you do. >From idallen Subject: EXEC doesn't close the file descriptors /* This program will demonstrate that CSH leaves internal * file descriptors open across an EXEC built-in command. * * % exec ./a.out */ main() { int i; for( i=0; i < 20; i++ ){ printf("%d = %d\n", i, isatty(i) ); } } The output shows: > exec ./a.out 0 = 1 1 = 1 2 = 1 3 = 1 4 = 1 5 = 1 6 = 0 7 = 0 8 = 0 9 = 0 ... From: idallen Subject: can't test success of CD, CHDIR, etc. cd nosuchdir || echo CD failed cd nosuchdir && echo CD failed cd nosuchdir ; echo CD failed None of the above work in CSH. >From idallen Mon Dec 16 21:40:32 1985 Subject: GLOB loses memory on directories echo /*/*/* If you interrupt the above GLOB, CSH loses memory. From: idallen Subject: C Shells don't parse when looking for labels. The shells just look at the first word on each line. You can cause the shell to branch in to the middle of a HERE document: #!/bin/csh -f onintr quit sleep 999 cat << EOF quit: echo Amazing how this prints. exit 88 # this exit is taken when break is hit EOF quit: echo You never get here. >From arwhite Thu Aug 26 13:53:58 1982 Subject: CSH/Bourne shell inconsistent newlines "`command`" deletes newlines from the command in the cshell, not in the Bourne shell. >From idallen (Ian! D. Allen) Subject: aliases aren't seen after redirection % date >x % >x date % alias foo date % foo >x % >x foo foo: Command not found. >From idallen (Ian! D. Allen) Subject: $< misbehaves in pipes % date | /bin/echo aaa $< bbb abcdef aaa a bbb % bcdef bcdef: Command not found. >From chris@pixutl.UUCP (chris) Fri Oct 5 14:01:13 1984 Subject: bug in CSH (history) There are a couple of bugs in the 'history' command of /bin/csh (and offspring, such as newcsh): 1) The maximum number of arguments to the history command is set to 2. % history -h -r 2 # fails >From idallen Subject: C Shell expression operators explained Some odd CSH context-sensitive features. There is ambiguity on how !~ != and !( should be interpreted: 1 - % ~idallen/study # a valid command line 2 - % !~ # doesn't work 3 - % echo " !~ " # no history 4 - % if ( abc !~ def ) echo hi 1 - % =xxx # a valid command line 2 - % != # doesn't work 3 - % echo " != " # no history 4 - % if ( 1 != 2 ) echo hi 1 - % ( date ) # a valid command line 2 - % !( # doesn't work 3 - % echo " !( " # no history 4 - % if ( !( 1 + 1 ) ) echo hi The C Shell parser isn't clever enough to distinguish any of cases 2, 3, or 4, so it always behaves as if the character pair was part of an expression, not a history substitution. -------------------------------------------------------------------------------- | *NOT A BUG* | >From idallenThu Jun 27 08:20:08 1985 | Subject: Re: Using > vs. | on shell built-in commands. | | CSH cannot put the output of the JOBS command into a pipe. In fact, | the output is going into the pipe, but the output is empty. You | couldn't know this, but these shells implement piped built-in commands | by forking the shell to create an independent process for which the | main shell can wait. But the internal process table is cleaned | out after a fork(), since a forked shell is just like a subshell | and must have its own clean process table in which to enter its own | running jobs. So by the time the JOBS command executes, it's in a | child shell that has no jobs running. Hence, the output is empty. | "echo `jobs`" and "( jobs )" are both empty, for the same reason. -------------------------------------------------------------------------------- From: jjg@security.UUCP (Jeff Glass) Subject: csh and I/O redirection put these four lines in a file, say cshtest : #! /bin/csh -f cat << END | ( sh & ) echo hi there END ( the intent is to send some commands to sh to be executed in the background, without csh printing the job number of the sh. ) now, from csh, enter the command source cshtest and note that you see the message "hi there". now enter the commands chmod +x cshtest ./cshtest and you get no output. removing either the parentheses or the ampersand causes the message to appear, but not quietly in the background. I don't understand why it works when source'd but not when exec'd, either. -------------------------------------------------------------------------------- | *FIXED* | From: matt@prism.UUCP | Subject: Pointless csh puzzle | | Here's a pointless little csh puzzle: In the c-shell, it is | possible to set and environment variable whose name consist of | more than one word, in the obvious way: | | % setenv "FOO BAR" quux | | The printenv builtin will show it residing happily in the | environment. Now for the puzzle: can anyone find a way to GET | TO the value of this variable, using only csh builtins? In | other words, is there an <expression> such that | | % echo <expression> | | will print "quux" on the screen, where <expression> is formed | only from csh commands? -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- | *FIXED* | >From tim@ISM780B.UUCP Wed Nov 20 18:00:00 1985 | Subject: Re: C-shell puzzles | | Here's another good C shell quirk: | | $ echo foo | foo | $ repeat 3 echo foo | foo | foo | foo | $ repeat 3 repeat 3 echo foo | foo | foo | foo | foo | foo | $ repeat $N repeat $M echo foo # $N and $M are integers | [ $N + $M - 1 foo's ] | $ repeat $N1 repeat $N2 ... repeat $Nk echo foo | [ $N1 + $N2 + ... + $Nk - k + 1 foo's ] | $ -------------------------------------------------------------------------------- >From pur-ee!uiucdcsb!liberte Mon Dec 30 23:20:31 EST 1985 Subject: Csh null strings There are at least two different-sized null strings in csh. But sometimes they are equal anyway. % set x = "" % set y = "`echo`" % echo $#x $#y 1 0 % set x = % set y = `echo` % echo $#x $#y 1 0 % set x = ("") % set y = ("`echo`") % echo $#x $#y 1 0 % set x = () % set y = (`echo`) % echo $#x $#y 0 0 % if (() == "`echo`") echo huh % if (() == ("`echo`")) echo huh huh % if ("" == ("`echo`")) echo huh % if ("" == "`echo`") echo "huh?" huh? >On Jul 18, 8:15am, mark@peek.org (Mark Peek) wrote: >-- Subject: Updated tcsh-6.12.0 release date? > >| Hi Christos, >| I know I've been (part of) the cause of slipping the release date out >| for tcsh-6.12.0. :-) Do you have an updated date for releasing it? >| I'm trying to determine whether it will fit in the time frame for >| shipment with the next FreeBSD 5.0-DP release. > >I hope to release it sometime next week. There are only minor changes in it. >Is that convenient, or would you like me to push it more? I sent a note to the FreeBSD release engineers and they're inclined to hold off on including the new version in the release which they're branching later today. If DP2 slips out a bit they might consider including it. I'd say go ahead with your current schedule and I'll import it whenever it is available. I definitely will be including it into the next -stable FreeBSD 4.7 release. BTW, one of the release engineers pointed out a bug with using jobcmd. If you use the example in the book to update an xterm and then run something like grep bar `cat file.list` It screws up the xterm title bar containing "Faulty alias 'jobcmd' removed" plus the list of files from the cat command. The good news is that I was able to reproduce this at home last night. The bad news is that it is working fine right now here at work. Oh wait, let me log in remotely and look at the alias I was using...got it! The command fails if you use: alias jobcmd 'echo -n "^[]2;\!#^G"' but works fine if you use: (note the switch of ' and " quotes) alias jobcmd "echo -n '^[]2;\!#^G'" Note: I used the above by vi'ing a file and sourcing it from the shell. If you can confirm, I think this just needs to be updated in the man page. >Thanks for all the help BTW... No problem. I like fixing bugs and contributing code...especially for a great piece of software like tcsh that I use *all* the time. Thank you for keeping it going! Mark | http://opensource.apple.com/source/tcsh/tcsh-64/tcsh/BUGS | CC-MAIN-2015-27 | refinedweb | 2,705 | 80.21 |
Is it possible programmatically change resource configuration qualifier?
I mean, make system for some hdpi devices took resources from xhdpi folder instead of hdpi.
In my project i have ldpi, mdpi, hdpi and xhdpi
image resources. For Kindle fire(1024 x 600 – 169 dpi) android system
takes resources from mdpi folder and application looks very bad. I
want to make android took resources from hdpi folder.
Related to your comment I usually provide resources only for hdpi screen and all other densities work fine. Testing at 2.1+ or 2.2+ devices which I usually target!
I understand the risk that is not documented, so it will not supposed to work although it does! In that way I avoid the some KB from my final apk.
But I do not suggest using xhdpi instead of hdpi as xhdpi works only in 3+ or something devices.
Just for testing different densities on a single device you can change AVD by:
am display-density 480
See android doc for more info:
Answer:
I’m not sure if you can. Don’t get me wrong: I personally would like to know the answer to this as well. What exactly would you like to do?
If you are going to do things programatically anyways, it might be better to put the asset into straight drawable, and then apply scaling. You can get the density multiplier pretty easily
Answer:
Kindle has large screen but with medium density
It takes the layout from res/layout-large/your.xml
But the images from res/drawable/mdpi so just create a folder called res/drawable/mdpi-large
hope this will work for you but the images must be as per the kindle’s resolution
Answer:
Try this code. Hope it helps.
import android.util.DisplayMetrics; private int result = 0; //Activity member public void determineDeviceResolution { switch(metrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: { result = DisplayMetrics.DENSITY_LOW; break; } case DisplayMetrics.DENSITY_MEDIUM: { result = DisplayMetrics.DENSITY_MEDIUM; break; } case DisplayMetrics.DENSITY_HIGH: { result = DisplayMetrics.DENSITY_HIGH; break; } default: break; } } private Drawable getDrawable(String icon) { //Pass file name of the resource file //while invoking this method for e.g. play_icon.png //You can specify the folder from which resource //needs to be picked for e.g. drawable_hd,drawable_xhdpi etc.. Drawable drawable = null; if(result == DisplayMetrics.DENSITY_HIGH) { drawable=create_drawable("/drawable_hd/" + icon); } else { drawable=create_drawable("/drawable/" + icon); } return drawable; } Drawable create_drawable(String absolute_filepath) { InputStream in = null; Bitmap bMap = null; BufferedInputStream buf = null; Drawable d = null; try { in = getClass().getResourceAsStream(absolute_filepath); buf = new BufferedInputStream(in); bMap = BitmapFactory.decodeStream(buf); if(in == null || buf == null || bMap== null) { return null; } if (in != null) { in.close(); } if (buf != null) { buf.close(); } } catch (Exception e) { e.printStackTrace(); } d = new BitmapDrawable(bMap); return d; }
Finally you can pass the drawable to the UI element’s setBackgroundDrawable() method.
Answer:
You can also customize the resources for the width and other properties of devices. Read this:
Tags: androidandroid | https://exceptionshub.com/android-change-resource-qualifier-programmatically.html | CC-MAIN-2021-17 | refinedweb | 480 | 51.24 |
See lazy (evaluate by need), so-called pure functional (no assignments or side-effects) language. It supports parametric polymorphism (ala C++ templates, but more powerful), and ad-hoc polymorphism ( operator overloading) through type classes (ala Java Interfaces). Python offers the programmer a profusion of styles, including procedural, functional, and object-oriented. Lazy programming can be accomplished using generators and itertools. Python has some support for a functional style of programming, but the profusion of side effects and the lack of built-in tail recursion optimization support, makes it an awkward style to use in Python. Haskell supports procedural programming through monads (from category theory) which are also Haskell's interface to the world of side effects (e.g. graphics, file systems, sockets, etc.). However, imperative programming is neither Haskell's intention nor strength (though this is debateable -- many Haskell coders have been known to state that Haskell is their favourite imperative language).
Compiled vs Interpreted:
Python's primary implementation is an interpreter. Haskell has a handful of implementations, including some interpreters (Hugs) and some native-code compilers (GHC, nhc98). Haskell is a high-level language like python, so equal-to-C-or-asm performance should not be expected. The Haskell type system, however, does provide more compile-time information than python's does, meaning the optimizing native-code compilers have a speed advantage over python in many cases.
The pythonic philosophy of dropping into C for critical sections applies equally well to haskell. Through the foreign function interface, haskell functions can call and be called from C code. As an alternative, compiler-specific extensions (specifically, ghc's) and strictness annotations can be used to get closer to the metal.
Static vs Dynamic Typing:
Both Haskell and Python have strong (not weak) typing, meaning instances of a type cannot be cast into another type. Explicit conversions must be performed. The difference is, and objects can pretend to be different types by providing the correct functions, e.g. _ _ len _ _, etc. Since typing is such a fundamental part of Haskell (it's part of what makes the language easy to reason about), this difference with Python is a fundamental one. However, for those python users who shudder to think of typing "int i" before every variable use, take heart: Haskell's compilers and interpreters are smart enough to infer the types of your expressions almost all the time, so you don't have to type them. Type inference is "static typing done right." For example, to assign a value of 5 to the identifier 'a', it's the exact same code in Python and Haskell:
a = 5
The fact that it's an integer is inferred by the Haskell compiler.
There is also one similarity I feel compelled to point out:
List Comprehension Syntax:
Python's list comprehension syntax is taken (with trivial keyword/symbol modifications) directly from Haskell. The idea was just too good to pass up.
Significant Whitespace:
Both use indentation as syntax. In Python, tabs/spaces are the syntax, whereas in Haskell, tabs/spaces are simply well-defined sugar for converting to the braces/semi-colon block syntax. Some would say that Haskell's way is an improvement on the idea of significant whitespace by allowing the optional use of explicit braces/semi-colons for blocks, saving certain amounts of headache, e.g. when copy-pasting from web-pages.
Learning Curve:
Haskell has a much steeper learning curve for programmers who are not used to functional programming. In many cases, lazy evaluation seems counterintuitive to an imperative-trained mind and you must unlearn techniques to prevent your program from eating up memory.
For me (Nioate), learning OCaml first smoothed the way into Haskell because ML has a very similar (though less flexible) type system. After understanding the type system, the jump to haskell is much less daunting: beyond new syntax, it only involves learning to utilize lazy evaluation, type classes, and monads. (Don't let monads scare you; learn about the list and Maybe monads first. Jeff Newbern's All About Monads is the best.)
Contributors: MichaelChermside
See also [LanguageComparisons].
Berp: a Python 3 Compiler implemented in Haskell.
Using both Python & Haskell with ctypes (-;
You can have your cake and eat it too. This is a technique using ctypes to interface with a haskell library compiled with ghc:
On Linux
Most of this technique is thanks to Tomáš Janoušek's incredibly useful blog entry at. I will merely include the content of the files to show how it can be done. Please visit his site for more details:
First create a test haskell library (Test.hs):
{-# LANGUAGE ForeignFunctionInterface #-} module Test where import Foreign.C.Types import Foreign.C.String add :: Num a => a -> a -> a add x y = x + y f1 :: CInt -> IO CInt f1 x = do return (42 + x) f2 :: CFloat -> IO CFloat f2 x = do return (10.0 + x) f3 :: CFloat -> IO CFloat f3 x = do return (add 10.0 x) f4 :: CString -> IO CString f4 s = do w <- peekCString s newCString (w ++ " world!") foreign export ccall f1 :: CInt -> IO CInt foreign export ccall f2 :: CFloat -> IO CFloat foreign export ccall f3 :: CFloat -> IO CFloat foreign export ccall f4 :: CString -> IO CString
Now create Tomas' shared library entry point (module_init.c):
#define CAT(a,b) XCAT(a,b) #define XCAT(a,b) a ## b #define STR(a) XSTR(a) #define XSTR(a) #a #include <HsFFI.h> extern void CAT (__stginit_, MODULE) (void); static void library_init (void) __attribute__ ((constructor)); static void library_init (void) { /* This seems to be a no-op, but it makes the GHCRTS envvar work. */ static char *argv[] = { STR (MODULE) ".so", 0 }, **argv_ = argv; static int argc = 1; hs_init (&argc, &argv_); hs_add_root (CAT (__stginit_, MODULE)); } static void library_exit (void) __attribute__ ((destructor)); static void library_exit (void) { hs_exit (); }
Then create a build script to compile it all and clean up residuals (build.sh):
ghc -O2 --make \ -no-hs-main -optl '-shared' -optc '-DMODULE=Test' \ -o Test.so Test.hs module_init.c rm *.hi *.h *.o rm Test_stub.c
You can now easily access the shared library using ctypes (test.py)::
from ctypes import * lib = cdll.LoadLibrary('./Test.so') funcs = { # name restype argtypes input expected value 'f1': (c_int, [c_int], (10, 52)), 'f2': (c_float, [c_float], (10.0, 20.0)), 'f3': (c_float, [c_float], (11.0, 21.0)), 'f4': (c_char_p, [c_char_p], ("hello", "hello world!")), } for func in funcs: f = getattr(lib, func) f.restype, f.argtypes, test = funcs[func] input, expected = test assert f(input) == expected print '{0}({1}) == {2}'.format(func, input, expected)
you should get:
f1(10) == 52 f2(10.0) == 20.0 f3(11.0) == 21.0 f4(hello) == hello world!
Enjoy!
Contributers: AliaKhouri
On Windows
Note: this technique may be dated.
First a test haskell program (mylib.hs):
module Mylib where import Foreign.C.Types import Foreign.C.String adder :: Int -> Int -> IO Int adder x y = return (x+y) subtractor :: Float -> Float -> IO Float subtractor x y = return (x - y) fact :: Int -> Int fact n = if n == 1 then 1 else (n * fact (n-1)) factorial :: Int -> IO Int factorial n = return (fact n) hello :: CString -> IO CString hello w = do s <- peekCString w newCString (s ++ "World!") mystring :: IO CString mystring = newCString "hello world!" foreign export stdcall adder :: Int -> Int -> IO Int foreign export stdcall subtractor :: Float -> Float -> IO Float foreign export stdcall factorial :: Int -> IO Int foreign export stdcall hello :: CString -> IO CString foreign export stdcall mystring :: IO CString
create file dllMain.c as entry point for the dll:
#include <windows.h> #include <Rts.h> extern void __stginit_Mylib); return TRUE; } return TRUE; }
compile everything by running this batch file (build.bat):
REM test making haskell dll ghc -c mylib.hs -fglasgow-exts ghc -c dllMain.c dlltool -A -z mylib.def mylib_stub.o --export-all-symbols ghc --mk-dll -o mylib.dll mylib.o mylib_stub.o dllMain.o -optdll-def -optdll mylib.def REM cleanup rm mylib.o rm mylib_stub.o rm dllMain.o rm mylib.hi rm mylib_stub.c rm mylib_stub.h
and then having installed ctypes, run the following python script (test_mylib.py) to test it:
from ctypes import * lib = windll.mylib api = { # func name restype argtypes 'adder' : (c_int, [c_int, c_int]), 'subtractor': (c_float, [c_float, c_float]), 'factorial' : (c_int, [c_int]), 'hello' : (c_char_p, [c_char_p]), 'mystring' : (c_char_p, []), } for func in api: f = getattr(lib, func) f.restype, f.argtypes = api[func] globals()[func] = f print adder(1,2) print subtractor(10.5, 2.5) print factorial(10) print hello('hello') print mystring() | https://wiki.python.org/moin/PythonVsHaskell | CC-MAIN-2016-26 | refinedweb | 1,407 | 65.32 |
Supporting ParallelFor Jobs in Ranged Native Collections
Native collections are funny things. On one hand they’re structs, which are supposed to be value types that get copied on assignment. On the other hand, they act like reference types because they contain a hidden pointer internally. This can make using and implementing them difficult to understand, especially in the context of a ParallelFor job. Today we’ll examine more closely how to properly support ParallelFor jobs, especially with ranged containers like
NativeList<T>.
Copying NativeArray
Since native collection types like
NativeArray<T> are structs, a copy is made whenever a variable is assigned, parameter is passed, or value returned. Changing one copy normally doesn’t change the other, such as with
Vector3:
Vector3 a = new Vector3(10, 20, 30); // Make a copy Vector3 b = a; // Change the original. Doesn't change the copy. a.x = 100; Debug.Log(b); // [ 10, 20, 30 ]
This is still technically the case with native collection types, Consider
NativeArray<T>, which has these fields according to the reference source:
[NativeDisableUnsafePtrRestriction] internal void* m_Buffer; internal int m_Length; internal int m_MinIndex; internal int m_MaxIndex; internal AtomicSafetyHandle m_Safety; [NativeSetClassTypeToNullOnSchedule] internal DisposeSentinel m_DisposeSentinel; internal Allocator m_AllocatorLabel;
Note: the reference source omits the
#if ENABLE_UNITY_COLLECTIONS_CHECKS wrapper around the middle section of fields.
Now let’s look at what happens when a copy of a
NativeArray<T> is made:
NativeArray<int> a = new NativeArray<int>(3, Allocator.Temp); a[0] = 10; a[1] = 20; a[2] = 30; // Make a copy NativeArray<int> b = a; // Change the original. Sort of changes the copy... a[0] = 100; Debug.Log(b[0]); // 100
The reason for this behavior is that making a copy of
a into
b makes a copy of the
m_Buffer field along with all the others. The
NativeArray<T>
set indexer changes the memory this field points to, not the pointer itself. Then the
NativeArray<T>
get indexer reads the memory this field points to, not the pointer itself. Since both
a and
b have the same pointer, they end up reading and writing the same memory.
This behavior makes
NativeArray<T> partly a value type because assignment is done by copying and partly a reference type because changes to one are reflected in changes to the other.
Copying NativeList
NativeArray<T> stores its length in its
m_Length field. Like all fields,
m_Length is copied during assignment, parameter passing, and value returning. This is fine for
NativeArray<T> because the length never changes. This isn’t the case for other types like
NativeList<T> because its length will change as elements are added to it. So how does it handle synchronizing this across all copies? The answer is to put the length inside the data pointed to by the pointer. Here’s a trimmed-down version of how it looks as of
preview.9 of the
com.unity.collections package:
public struct NativeList<T> : IDisposable where T : struct { internal NativeListImpl<T, DefaultMemoryManager> m_Impl; } unsafe struct NativeListData { public void* buffer; public int length; public int capacity; } public unsafe struct NativeListImpl<T, TMemManager> where T : struct where TMemManager : struct, INativeBufferMemoryManager { [NativeDisableUnsafePtrRestriction] NativeListData* m_ListData; }
The
NativeList<T> contains a
NativeListImpl<T, TMemManager> which in turn contains a pointer to a
NativeListData which contains a pointer to the backing array as well as the length and capacity. Let’s look at how this allows
NativeList<T> to handle copying in such a way that it acts like a reference type:
NativeList<int> a = new NativeList<int>(Allocator.Temp); a.Add(10); a.Add(20); a.Add(30); NativeList<int> b = a; b.Add(100); b.Add(200); b.Add(300); Debug.Log(a[0]); // 10 Debug.Log(a[3]); // 100 Debug.Log(a.Length); // 6
If
NativeList<T> simply contained its length as a field like how
NativeArray<T> contained
m_Length, copying
a to
b would have copied this field. The calls to
b.Add would have changed
b.m_Length without updating
a.m_Length, so the
Debug.Log(a.Length) at the end would have printed
3.
Instead, the length is stored in a
NativeListData that the
NativeList<T> has a pointer to, indirectly through
NativeListImpl<T, TMemManager>. This allows the length to be shared between copies just like how
NativeArray<T> shared its array elements.
Ranged Collections
NativeArray<T> has the
[NativeContainerSupportsMinMaxWriteRestriction] attribute and is therefore a ranged collection. To support this, it has the
m_Length,
m_MinIndex, and
m_MaxIndex fields. Since this is currently undocumented, let’s break down what each field means.
m_Length is an
int with that specific name. When a ParallelFor job that has the collection as a field is executed, Unity reads this field and uses it to write
m_MinIndex and
m_MaxIndex. Note that Unity never writes to
m_Length.
m_MinIndex and
m_MaxIndex are also
int fields with those specific names, in that specific order, and must directly follow
m_Length. When a ParallelFor job that has the collection as a field is executed, Unity writes these fields based on the portion of the size that was passed to
Schedule that is currently being executed. Note that Unity never reads from
m_MinIndex or
m_MaxIndex.
It’s the responsibility of the native collection to use the
m_MinIndex and
m_MaxIndex fields to bounds-check all accesses. For example, the indexer for
NativeArray<T> contains this code:
if (index < m_MinIndex || index > m_MaxIndex) FailOutOfRangeError(index);
Dynamic Ranged Collection Problems
Now let’s say we want to create a collection like
NativeList<T> that’s dynamically resizable but also supports ParallelFor jobs as a ranged collection. This sounds easy because we’ve already seen how to solve the problem of sharing changes to the length and the bounds-checking should be trivial with a collection that’s just a one-dimensional array.
Unfortunately, supporting this is quite awkward with the native collections system. The issue is that Unity reads
m_Length from ranged collections but this isn’t where collections like
NativeList<T> store the length. Unity doesn’t know to read
m_Impl.m_ListData->length and instead insists on reading
m_Length. This puts us back in the same quandary as before: how do we synchronize
m_Length across all copies of the
NativeList<T>?
Unity has solved this in two ways. First, they’ve provided an implicit conversion operator to create a
NativeArray<T> that shares its pointer with the
NativeList<T>. This has some limitations. First,
NativeArray<T> has almost no methods and therefore can’t be used with any extra functionality that might be present in
NativeList<T>. Second, and more importantly, if the
NativeList<T> changes its length after the
NativeArray<T> is created then the
m_Length field of the
NativeArray<T> won’t be updated and the
NativeArray<T> will continue to have the old length. Even worse, if adding elements to the
NativeList<T> makes it run out of capacity then it’ll deallocate the buffer that the
NativeArray<T> is still using. Unity will provide the appropriate error, but it’s very easy to write brittle code because calling
NativeList<T>.Add only sometimes deallocates the array and even so it’s not obvious that it will ever resize as this is an implementation detail.
The second solution is to provide
NativeList<T>.ToDeferredJobArray. This also creates a
NativeArray<T>, but it sets its length to zero, allocator to
Invalid, and pointer to one byte after the
NativeListData pointer. This odd pointer memory address signals to Unity’s job system that the length of the
NativeArray<T> needs to be written before jobs using it are executed. Exactly how this works seems to exist only inside the closed source portion of Unity and there is apparently no documentation available. If you know of any, please comment to point the way.
Dynamic Ranged Collection Solutions
Unity’s first solution, creating a
NativeArray<T> with fixed size, is suitable for collections like
NativeList<T> that have exactly one backing array. It isn’t suitable for collections like
NativeChunkedList<T> in the NativeCollections GitHub project which contain many backing arrays. Even
NativeLinkedList<T> isn’t a very good candidate since its nodes are in an arbitrary order until
SortNodeMemoryAddresses is called.
The second solution seems closed to all but
NativeList<T>. It’s possible that with better understanding of Unity’s internals that this is a system that can be leveraged by collections other than
NativeList<T>, but for now that is unknown and best avoided. Even if the current implementation could be reverse-engineered, there are no guarantees that the implementation will remain consistent and well-supported from version to version.
This means that we need a third solution for types like
NativeChunkedList<T> and
NativeLinkedList<T>. One way that’s simple, straightforward, and effective is the following strategy. First, initialize
m_Length,
m_MinIndex, and
m_MaxIndex to
-1. This flags the collection as being used outside of a
ParallelFor job.
public MyCollection() { #if ENABLE_UNITY_COLLECTIONS_CHECKS m_Length = -1; m_MinIndex = -1; m_MaxIndex = -1; #endif }
Next, never write
m_MinIndex or
m_MaxIndex in the collection’s code after initialization. This means only Unity will write them and only when a copy is used in a ParallelFor job.
Finally, add a method to synchronize
m_Length to the value stored in the shared memory each copy has a pointer to. This allows users who are about to execute a
ParallelFor job to manually synchronize the length so that Unity will read the correct value and therefore write the correct values of
m_MinIndex and
m_MaxIndex.
public void PrepareForParallelForJob() { #if ENABLE_UNITY_COLLECTIONS_CHECKS m_Length = m_State->m_Length; #endif }
Since only Unity will write non-negative values of
m_MinIndex and
m_MaxIndex, it will only write them when the collection is being used in a ParallelFor job, and it will write the values that need to be bounds-checked, this leads to the following updated error-checking code:
#if ENABLE_UNITY_COLLECTIONS_CHECKS // Used within a ParallelFor job if (m_MinIndex != -1 || m_MaxIndex != -1) { // Make sure the length is correct if (m_Length != m_State->m_Length) { throw new Exception( "Call PrepareForParallelForJob before a ParallelFor job"); } // Perform a bounds check if (index < m_MinIndex || index > m_MaxIndex) { throw new Exception( "Index " + m_Index + " out of bounds: [" + m_MinIndex + ", " + m_MaxIndex + "]"); } } #else
Usage is then simple and explicit:
// Initially length is zero MyCollection a = new MyCollection(); // Make a copy MyCollection b = a; // Add some elements so A's length is now 3 a.Add(10); a.Add(20); a.Add(30); // Synchronize B's length so it can be used in a ParallelFor job b.PrepareForParallelForJob(); // Use B in a ParallelFor job const int innerloopBatchCount = 1; MyJob job = new MyJob { Collection = b }; job.Schedule(b.Length, innerloopBatchCount).Complete();
Conclusion
Unity’s native collection support is still new and currently not very friendly to ranged collection types that change their length within ParallelFor jobs. The above strategy is a workaround that requires some manual code: a call to
PrepareForParallelForJob. It also limits how much code can be run in jobs before synchronizing back to the main thread so that
PrepareForParallelForJob can be called to update the ranged collections for future jobs. Hopefully this will be addressed in future versions of Unity. Due to the lack of documentation and closed engine source code, there is some degree of guesswork in this article. If any of it is incorrect, please comment to let me know.
Both
NativeLinkedList<T> and
NativeChunkedList<T> in the NativeCollections GitHub project have been updated with a
PrepareForParallelForJob method to improve their correctness within a ParallelFor job context. Feel free to check out the code to see how it works in more complete types or to simply integrate it into your own projects. | https://jacksondunstan.com/articles/4987 | CC-MAIN-2019-09 | refinedweb | 1,921 | 53.1 |
> > I'll try to explain my setup: > > > > I want tables (containing namespaces) as follows: > > > > Tests > > Tests.Component1 -- Contains all the tests for Component1 > > May I suggest a different setup? > > What about > > /Tests > /Component1 > Feature1.lua > > and then use only > > require "Tests.Component1.Feature1" > > whenever you need to test feature1 from component1. The file could be only > > module "Tests.Component1" > ... some more code to implement tests for feature 1. > > Notice that you can have more than one FeatureN file using the same module > namespace (although local functions won't be visible among the different > files). > This could work. How would I provide my users with the ability to load all the tests for component1? How would they load the tests for all the components? (BTW: I think there was a discussion on this somewhere else) > > To summarise: It is possible to either prevent a library from loading or > > loading it into unexpected tables by declaring global variables with > this > > implementation of compat. > > I have to insist that apparently that is not the issue here, using the > above namespace scheme should make things easier for you and your users, > no? > I've managed to reduce all of this into 1 file that demonstrates the issue. Put all of this into ./Tests.lua. One could also distribute it over the files as indicated by the comments module "Tests" --require 'Tests.Component1' -- In ./Tests/Component1.lua --require "Tests.Component1.Feature1" -- In ./Tests/Component1/Feature1.lua module "Tests.Component1" Start Lua and assign something to the global variable Component1. Now require 'Tests' e.g. - Component1 = function() end - require 'Tests' The response I see is (Lua 5.0.2, compat-5.1r2): compat-5.1.lua:122: name conflict for module `Tests.Component1' stack traceback: [C]: in function `error' compat-5.1.lua:122: in function `module' Tests.lua:8: in function `f' compat-5.1.lua:79: in function `require' stdin:1: in main chunk [C]: ? By making the change to getfield(), this will work. Jarno | https://lua-users.org/lists/lua-l/2005-06/msg00001.html | CC-MAIN-2020-45 | refinedweb | 331 | 60.51 |
Tax
Have a Tax Question? Ask a Tax Expert
Join the 9 million people who found a smarter way to get Expert help
Recent tax questions
I am a foreign student on F-1 visa who have been in the US for 5 years. I didn't work in my first year here. I don't have a green card. If my income in 2015 falls within the specified range of the Earned Income Tax Credits, am I eligible to claim the Earned Income Tax Credits?
Read more
Enrolled Agent, Paralegal
I have a question regarding my EIC. I want to ask how it works because my refund is just a little more for 2015 than for 2014. But my third son also became a full time student so I thought I would get more. But maybe because I don't know how it works I am confused.
Hello. I wanted to know would it be wise for my husband and I to file an amended tax return. Here is my situation... My husband does have previous tax debt (has payment agreements/arrangements set up already) that he had previously accrued prior to our relationship and prior to our getting married back in November of 2015. Because I already knew this... I went ahead and filed my own separate tax return, but am not happy about not getting to claim all the exemptions due to being 'Married filing a separate return' . My question is, would it be beneficial for me to file an amended return (add him) so that we can capitalize on the head of house hold & earned income tax credits? Even if we don't get anything more BACK as a tangible refund my thoughts are maybe THIS YEARS taxes for him will be covered??? Please help !!! is this something I need to look into?
Masters
We have two children who are full time students (ages 18 and 20) and we we claim as dependents on our form 1040. Does each of them still need to file a separate tax return under their own name(s)? And a related question if yes, how can we determine if they should file form 1040 or 1040EZ. And finally, one of them has a small amount of self-employment income as well as salary. Does that define which form he will need to file, regardless of total income? Thank you.
Sr Financial & Tax Consultant
Bachelor's Degree
I live in Alabama. My wife and I are raising a non immediate family member who is on Medicaid. I want to know if I claim her if it will affect any benefits. Thanks.
JD, MBA, CFP, CRPS
Doctoral Degree
My wife and I are resident alien and have SS number. but my kids are no resident alien and do not have TAX id.I will apply for my kids' tax id with my 1040 tax return. Can we claim the EIT for me and my wife only in this return?
Retired
Bachelor's Degree Equivalent
hi, i have rental properties which i manage myself and that is all i do for living, i do qualify as material participated and a real estate professional, i use schedule E and line 26 shows NPA, can i give myself a W2 to qualify for EIC? (i do pass other conditions for EIC)JA: The Accountant will know how to help. Is there anything else important you think the Accountant should know?Customer: properties are under my name and my wife, i have Sole proprietorship with EIN no., leases are under Sole proprietorship and i collect rent under Sole proprietorship, can i pay myself from the Sole proprietorship for management fees and get W2?JA: OK. Got it. I'm sending you to a secure page on JustAnswer so you can place the fully-refundable deposit now. While you're filling out that form, I'll tell the Accountant about your situation and connect you two.
Hello My name is ***** ***** - I have a question about the EITCJA: Thanks. Can you give me any more details about your issue?Customer: I am helping my mother with taxes and she is a divorced woman who files as single. My brother and I live under her roof, but we both make enough money to support ourselves and pay for our own college. Last year, my mom's account didn't get her the EITC, however, I am doing her taxes right now and think she should be able to get the EITC, even though we are not dependents of her We just claim ourselves on our own taxes, both as single I am using TurboTax by the wayJA: OK got it. Last thing — Tax Professionals generally expect a deposit of about $32 to help with your type of question (you only pay if satisfied). Now I'm going to take you to a page to place a secure deposit with JustAnswer. Don't worry, this chat is saved. After that, we will finish helping you.
Tax advisor and Enrolled Agent
I have had my grand sons for 14 years. 2014 they went to help their mom after surgery they went to school in sac but I got them every weekend, break and holiday which added up to over half the year. I paid for their clothes and to wash them. I even helped with the rent but never thought to save receipts. My daughter is not working and was not at the time they were there. The IRS says I could not claim them and I owe. Does the IRS not have to prove before the tell someone they defrauded the Government and breaking tax laws. No one has ever claimed them but me I take care of them. I need advise. I have been mailing them what I had to show but nothing is good enough. I have till 3/6/16 to answer their last letter | http://www.justanswer.com/topics-earned-income-tax-credit/ | CC-MAIN-2016-26 | refinedweb | 988 | 79.4 |
by Code Realm
Meet Material-UI — your new favorite user interface library
Update (17/05/2018): Material-UI v1.0.0 is out! Check out this post by Olivier.
Huh? Yet another library? What’s wrong with Bootstrap? And why not v0.20?
Great questions! Let’s start with a brief introduction. In a nutshell, Material-UI is an open-source project that features React components that implement Google’s Material Design.
It kick-started in 2014, not long after React came out to the public, and has grown in popularity ever since. With over 35,000 stars on GitHub, Material-UI is one of the top user interface libraries for React out there.
Its success didn’t come without challenges though. Designed with LESS, Material-UI v0.x was prone to common CSS pitfalls, such as global scope, which lead the project on the CSS-in-JS trajectory. This is how
next came about in 2016.
The journey towards better style, as Olivier Tassinari puts it, began with inline styles, but their suboptimal performance and limited feature support (think pseudo selectors or media queries), ultimately made the team transition to JSS. And boy did they make a smart choice.
What’s the hype with the v1 release?
It’s bad-ass. Not only does it address the problems inherent with LESS, but it also unlocks a ton of terrific features, including
- dynamic styles generated at runtime
- nested themes with intuitive overrides
- reduced load time with code splitting
And many more. The library is also mature enough to be used in production So much so that the team suggests v1 for all new projects going forward.
Alright, are we gonna build an app, or what?
Glad you asked! For this demo, we’ll build a simple fitness app. Everyone is bored of to-do apps by now anyway, right?
Reading is great and all, but watching is often more fun! Check out this playlist I made on YouTube if you want to build a more advanced app.
Ok, you got me convinced. How do I get started?
We’ll first bootstrap our app with create-react-app
create-react-app mui-fitnesscd mui-fitnesscode .
And what about Material-UI?
If you have yarn, the installation is as simple as
yarn add @material-ui/core
Otherwise, with
npm
npm i @material-ui/core
Not long ago, we would specify
@next tag to pull in the latest pre-release (for example, it might have looked like
v1.0.0-beta.47). Now that both v1 and v0.x are under
material-ui scope, we need to reference the core of the library with
/core to target the latest release. Don’t miss that last part, or else you’ll end up with the stable
0.20 dependency!
Wait, is that really it?
Almost! One last thing is fonts. We’ll go with the recommended Roboto Font from Google’s CDN:
<link rel="stylesheet" href="">
Alternatively, you can pull it in from NPM with
yarn add typeface-roboto# or npm i typeface-roboto
in which case, you’ll need to have an import at the root of your project
// Make sure you only load 300, 400, & 500 font weights though!import 'typeface-roboto'
Done! What do I do next?
Well, let’s refactor our
App.js component before we go any further
import React, { Component } from 'react'
export default class App extends Component { state = { exercises: [], title: '' }
render() { return <h1>Exercises</h1> }}
And why not clean up
index.js while we’re at it?
import React from 'react'import { render } from 'react-dom'import App from './App'
render(<App />, document.getElementById('root'))
Feel free to remove the remaining files under
src, as we won’t need them.
Where does Material-UI come in?
Fair enough, it’s time to see it in action. Let’s change the ugly
h1 to a beautiful
Typography heading:
import Typography from '@material-ui/core/Typography'
...
render() { return ( <Typography variant='display1' align='center' gutterBottom> Exercises </Typography> ) }}
Note that since v1.0.0-rc.0, MUI moved to
@material-ui/coreand the import path was flattened. This was the last breaking change in the pre-release.
Then go ahead and run
yarn start to see the magic.
We’re on to a good start!
Typography component comes with a pre-defined set of type sizes. Other
variants include
body1,
title,
display2, and so on. Among other built-in props are
align which we use here to center the text horizontally, and
gutterBottom which adds a bottom margin.
Why don’t we expand this to a form, so we can create our own exercises? We’ll start with a
TextField and bind it to the
title on the state
import Typography from '@material-ui/core/Typography'import TextField from '@material-ui/core/TextField'
...
handleChange = ({ target: { name, value } }) => this.setState({ [name]: value })
render() { const { title } = this.state return ( ... <form> <TextField name='title' label='Exercise' value={title} onChange={this.handleChange} </form> ) }}
Of course, we’d need to make React happy by wrapping
Typography and
form with a parent element. What could be a better opportunity for a paper-sheet card-like background? Let’s reach out to
Paper then
import Paper from '@material-ui/core/Paper'
...
render() { const { title } = this.state return <Paper> ... </Paper> } }}
It’s also about time to start using named imports (assuming our Webpack setup allows for tree shaking):
import { Paper, Typography, TextField } from '@material-ui/core'
Sweet! And what good is a form without the submit button?
Buttons are a staple component in Material-UI; you’ll see them everywhere. For instance,
import { Paper, Typography, TextField, Button } from '@material-ui/core'... <Button type='submit' color='primary' variant='raised' > Create </Button> </form> </Paper> }}
It should read well.
type is a regular React prop,
color and
variant are Material-UI-specific, and make up a rectangle-shaped button. Another variant would be
fab for a floating button, for example.
It doesn’t do much though. We’ll have to intercept the form submit event
return <Paper> ... <form onSubmit={this.handleCreate}> ... </form> </Paper> }}
and then handle it with
handleCreate = e => { e.preventDefault()
if (this.state.title) { this.setState(({ exercises, title }) => ({ exercises: [ ...exercises, { title, id: Date.now() } ], title: '' })) } }
Whoa! What’s that cryptic code all about? Very quickly, we
- Prevent the default page reload
- Check if the
titlefield is non-empty
- Set the state with an updater function to mitigate async updates
- Destructure
exercisesand
titleoff the
prevStateobject
- Spread out the
exerciseson the next state with a new exercise object
- Reset the
titleto clear out the input field
Guess I should have mentioned that I’m in love with ES6 too. Aren’t we all?
But how do we list them?
Now is the right time to. Is there a list component? Of course, you silly goose!
Inside a
List, we’ll loop through our
exercises and return a
ListItem with some
ListItemText for each
import { List, ListItem, ListItemText } from '@material-ui/core'
...
render() { const { title, exercises } = this.state return <Paper> ... <List> {exercises.map(({ id, title }) => <ListItem key={id}> <ListItemText primary={title} /> </ListItem> )} </List> </Paper> }}
Let’s also hard-code a few initial exercises to get something on the screen. You guessed it, the trinity of all weight lifting workouts, ladies and gents:
state = { exercises: [ { id: 1, title: 'Bench Press' }, { id: 2, title: 'Deadlift' }, { id: 3, title: 'Squats' } ], title: '' }
Last but not least, our users are likely to make typos, so we better add a delete button next to each exercise, so they could remove entries they no longer want in their list.
We can use
ListItemSecondaryAction to do exactly that. Placed on the far right of the list item, it can hold a secondary control element, such as an
IconButton with some action
import { /*...*/, ListItemSecondaryAction, IconButton} from '@material-ui/core'
...
<ListItem key={id}> <ListItemText primary={title} /> <ListItemSecondaryAction> <IconButton color='primary' onClick={() => this.handleDelete(id)} > {/* ??? */} </IconButton> </ListItemSecondaryAction> </ListItem>
...
And let’s not forget the delete handler as well:
handleDelete = id => this.setState(({ exercises }) => ({ exercises: exercises.filter(ex => ex.id !== id) }))
which will simply filter our exercises down to those that don’t match the
id of the one that needs to be removed.
Can we have a trash bin icon inside the button?
Yes, that would be great! Though you could use Material Icons from Google’s CDN directly with either
Icon or
SvgIcon components, it’s often preferable to go with a ready-made preset.
Luckily, there’s a Material-UI package for those
yarn add @material-ui/icons# or npm i @material-ui/icons
It exports 900+ official material icons as React components, and the icon names are nearly identical, as you’ll see below.
Let’s say we wanted to add a trash icon. We’d first head over to material.io/icons to find out its precise name
Then, we turn that name into PascalCase in our import path
import Delete from '@material-ui/icons/Delete'
Just like with Material-UI components, if your setup has tree-shaking enabled, you could shorten the import to
import { Delete } from '@material-ui/icons'
which is especially useful when importing several icons at once.
Now that we have our trash icon, let’s display it inside our delete button
<IconButton color='primary' onClick={() => this.handleDelete(id)}> <Delete /></IconButton>
How can I make the form look less ugly?
Ah, styling. I thought you’d never ask! A gentle touch of CSS wouldn’t hurt. So then, do we import an external stylesheet with global styles? Or, perhaps, use CSS modules and assign scoped class names to our elements? Not quite.
Under the hood, Material-UI forks a CSS-in-JS library known as react-jss.
It’s a React integration of the JSS library by the same author, Oleg Isonen. Remember we touched on it in the beginning? Its basic idea is to enable you to define styles in JavaScript. What makes JSS stand out among other libs though, is its support for SSR, small bundle size, and rich plugin support.
Let’s give it a try! In our
App component, create a styles object just like you would with inline styles. Then, come up with a key, for instance
root, referring to the root
Paper element, and write out some styles in camelCase
const styles = { root: { margin: 20, padding: 20, maxWidth: 400 }}
Next, import
withStyles HOC from
material-ui
import { withStyles } from '@material-ui/core/styles'
and wrap the
App component with it, passing
styles object as the arg
export default withStyles(styles)( class App extends Component { ... })
Note that you could also use
withStylesHOC as a decorator. Keep in mind that create-react-react doesn’t support decorators out of the box yet, so if you insist on using them, you’d need to eject or fork to tweak the config.
This will inject a
classes prop into
App containing a dynamically-generated class name for our
root element
The class name is guaranteed to be unique, and it will often be shortened in a production build. We then assign it to
Paper via
className attribute
render() { const { title, exercises } = this.state const { classes } = this.props
return <Paper className={classes.root}> ... </Paper> }
How does this magic work? Turns out,
withStyles is responsible for the dirty work. Behind the scenes, it injected an array of styles into the DOM under
<style> tags. You could spot them if you dig int
o the <head> with dev tools
You could also see other
style tags related to native components, such as
MuiListItem for the
ListItem component we imported earlier. Those are auto-injected on demand, for each given UI element that you import.
That means that Material-UI will never load any styles for the components that we don’t use. Hence, increased performance and faster load times. This is very different from Bootstrap, which requires loading the entire monolithic CSS bundle, whether you happen to use its vast assortment of classes or not.
Let’s also style the form so it looks neat
const styles = { root: { ... }, form: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-evenly' }}
This will make the text field and the button nicely spaced out. Feel free to refer to align-items and justify-content at CSS-Tricks should you need any further clarification on the Flexbox layout.
Sure, but what’s up with theming then?
withStyles HOC is tailored for customizing a one-off component, but it’s not suited for application-wide overwrites. Whenever you need to apply global changes to all components in Material-UI, your first instinct would be to reach out to the
theme object.
Themes are designed to control colors, spacing, shadows, and other style attributes of your UI elements. Material-UI comes with built-in light and dark theme types, light being the default.
If we turn our
styles into an anonymous function, it will receive the
theme object as an arg, so we can inspect it
const styles = theme => console.log(theme) || ({ root: ..., form: ...})
The way you customize your theme is through configuration variables, like
palette,
type,
typography, etc. To have a closer look at all the nested properties and options, visit the Default Theme section of the Material-UI docs.
Let’s say we wanted to change the primary color from
blue to
orange. First off, we need to create a theme with
createMuiTheme helper in
index.js
import { createMuiTheme } from '@material-ui/core/styles'
const theme = createMuiTheme({ /* config */ })
In Material-UI, colors are defined under the
palette property of
theme. The color palette is subdivided into intentions which include
primary,
secondary, and
error. To customize an intention, you can simply provide a color object
import { orange } from '@material-ui/core/colors'
const theme = createMuiTheme({ palette: { primary: orange }})
When applied, the color will then be calculated for
light,
main,
dark, and
contrastText variations. For more granular control though, you could pass in a plain object with any of those four keys
const theme = createMuiTheme({ palette: { primary: { light: orange[200] // same as '#FFCC80', main: '#FB8C00', // same as orange[600] dark: '#EF6C00', contrastText: 'rgb(0,0,0)' } }})
As you can see, individual colors can be expressed as both a hex or rgba string (
#FFCC80) and a hue/shade pair (
orange[200]).
Creating a theme on its own won’t suffice. To overwrite the default theme, we would need to position
MuiThemeProvider at the root of our app and pass our custom
theme as a prop
import { /*...*/, MuiThemeProvider } from '@material-ui/core/styles'
const theme = createMuiTheme({ palette: { primary: orange }})
render( <MuiThemeProvider theme={theme}> <App /> </MuiThemeProvider>, document.getElementById('root'))
MuiThemeProvider will then pass down the
theme to all its child elements through React context.
Though it may seem like a lot of work to change a color, keep in mind that this overwrite will propagate to all components nested under the provider. And apart from colors, we can now fine-tune viewport sizes, spacing, opacity, and many other parameters.
Utilizing config variables when styling your components will aid with consistency and symmetry in your app’s UI. For example, instead of hard-coding magic values for
margin and
padding on our
Paper component, we could instead rely on the spacing unit off the theme
const styles = ({ spacing: { unit } }) => ({ root: { margin: unit, padding: unit * 3, maxWidth: 400 }, form: ...}
theme.spacing.unit comes at
8px by default, but if it’s used uniformly across the app, when we need to update its value, rather than scavenging across the entire codebase, we only need to change it in one place, that is, in our options object that we pass to
createMuiTheme.
Theme variables are plentiful, and if you run into a use case that’s not covered by the built-in theme object, you could always define your own custom vars. Here’s a slightly modified version of our fitness app that showcases color palette, theme type, and spacing unit options
Note that the example above is only a demo. It re-creates a new theme each time an option changes, which leads to a new CSS object being re-computed and re-injected into the DOM. Most often than not, your theme config will remain static.
There are far more interesting features that we haven’t covered. For example, Material-UI comes with an opt-in
CssBaseline component that applies cross-browser normalizations, such as resetting margins or font family (very much like normalize.css does).
As far as components go, we have our standard
Grid with a 12-column layout and five viewports (
xs,
sm,
md,
lg, and
xl). We’ve also got familiar components like
Dialog,
Menu, and
Tabs, as well as elements, such as
Chip and
Tooltip. Indeed, there’s a whole slue of others, and fortunately, they are all very-well documented with runnable demo code from CodeSandbox
Aside from that, Material-UI Next also works with SSR, if you’re into that. Besides, although it comes with JSS out of the box, it can me made to work with just about any other library, like Styled Components, or even raw CSS.
Be sure to check out the official docs for more info.
I hope you found this read useful! And if you like it so much that you are excited to learn more about Material-UI or React, then check out my YouTube channel maybe?
Thanks for stopping by! And big thanks to the team over at Call-Em-All and all the backers who helped to build this awesome library ❤️
Cheers,
Alex | https://www.freecodecamp.org/news/meet-your-material-ui-your-new-favorite-user-interface-library-6349a1c88a8c/ | CC-MAIN-2020-24 | refinedweb | 2,907 | 64.61 |
As serializing of a TreeNode object does not work as it is said in the Microsoft’s online page, or other Web pages, e.g. Object Serialization using C# on this Web site.
TreeNode
If you try to write a class inherited from a TreeNode object, you will find a NullPointerException during serialization to/from the file. Your process crashes, and a wonderful and beautiful NullPointerException is shown (if you've not caught it).
TreeNode
NullPointerException
NullPointerException
The reason is one, simple and not easy to reach: the TreeNode object implements the ISerializable interface but deserialization does not work very well, that's because you cannot simply serialize an object that inherits the TreeNode and be able to [Serialize] it.
ISerializable
[Serialize]
You can find an example of the problem here. I did not write that code, but it's a great example, and in this article you can find how to resolve it.
So, if you try to write code like this:
[Serializable]
public class MyObject : TreeNode
{
public MyObject(string dirName) : base(dirName)
{
}
You will find that, one of the most simple code ever made will crash when you try to serialize and de-serialize the MyObject object.
MyObject
static void Main(string[] args)
{
MyObject obj = new MyObject("blabla");
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
}
Don't worry, there is a SIMPLE and EASY solution, but it would be easier if [Serialize] tag worked as it was supposed to (like Java). I think it's not necessarily a full project to show how it can be done, it's really very simple!
I surfed the Internet, spending a lot of hours trying to find the answer for this problem in C#. Don’t worry, it does not exist anywhere but here. I found some objects that used TreeNode and TreeView as a base class, and derived it (and you had to derive that derived class, not very practical). I suggest that you inherit the TreeNode class, because the TreeView class is used only for GUI approaches (I must say it: use the Facade pattern, very easy and useful while using a memory-GUI duet).
TreeView
But it was not what I wanted, and it was a lot of work to change my project, and mapping all my work to store it in an XML (so cool, so fantastic, …) but I wanted binary files.
What I wanted was to derive a TreeNode, and store it to a binary or XML file, does not matter what the structure of my object was. At Microsoft's Web page was no answer, I tried to find it. And I won.
After a long time, I found the answer: you can derive your class from TreeNode, but the serializing way works different from other classes (not to say Microsoft’s help). This is how I did it:
First of all, derive your class:
[Serializable]
public class DbVisioFile: TreeNode, …
{
///THIS IS WHAT I WANT TO STORE IN BINARY OR XML FILES
private string mFilePath;
private string mOwner;
private string mSummary;
private string mDifferences;
private string mComments;
private Version mVersion;
After this, make your own Serialization control-code:
Serialization
#region Serialization control
protected DbVisioFile(SerializationInfo si, StreamingContext context)
: base(si, context)
{
this.FilePath = si.GetString("FilePath");
this.Owner = si.GetString("Owner");
this.Summary = si.GetString("Summary");
this.Differences = si.GetString("Differences");
this.Comments = si.GetString("Comments");
this.Version = new Version(si.GetString("Version"));
}
protected override void Serialize(SerializationInfo si, StreamingContext context)
{
base.Serialize(si, context);
si.AddValue("FilePath", this.FilePath);
si.AddValue("Owner", this.Owner);
si.AddValue("Summary", this.Summary);
si.AddValue("Differences", this.Differences);
si.AddValue("Comments", this.Comments);
si.AddValue("Version", this.Version.ToString());
}
#endregion
You can see that the code has no reason to work, but it does. It is a mixture of the ISerializable and [Serializable] point of view.
[Serializable]
In the overriding of the Serialize method, the first line is:
Serialize
base.Serialize(si, context);
As a result of this, the treenode structure is serialized to disk.
treenode
You have to be very careful with calling the following line in the constructor code.
:base(si, context)
... or if you have any questions, please send me an email at victoragus@yahoo.es with a clear question and the source code.
Remember, the beginnings are very hard. And if you work with a language that doesn't work as it is supposed to, it is even harder.
So sorry for my English, but if you are English, try to rewrite it in Spanish and send me. We both will have some laughs!
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Victor_Gus wrote:I dunno why.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/24508/How-to-Serialize-a-TreeNode-Object?msg=3061611 | CC-MAIN-2017-34 | refinedweb | 829 | 51.58 |
This is the second part in a series of articles on how debuggers work. Make sure you read the first part before this one.
In this part
I'm going to demonstrate how breakpoints are implemented in a debugger. Breakpoints are one of the two main pillars of debugging - the other being able to inspect values in the debugged process's memory. We've already seen a preview of the other pillar in part 1 of the series, but breakpoints still remain mysterious. By the end of this article, they won't be.
Software interrupts
To implement breakpoints on the x86 architecture, software interrupts (also known as "traps") are used. Before we get deep into the details, I want to explain the concept of interrupts and traps in general.
A CPU has a single stream of execution, working through instructions one by one [1]. To handle asynchronous events like IO and hardware timers, CPUs use interrupts. A hardware interrupt is usually a dedicated electrical signal to which a special "response circuitry" is attached. This circuitry notices an activation of the interrupt and makes the CPU stop its current execution, save its state, and jump to a predefined address where a handler routine for the interrupt is located. When the handler finishes its work, the CPU resumes execution from where it stopped.
Software interrupts are similar in principle but a bit different in practice. CPUs support special instructions that allow the software to simulate an interrupt. When such an instruction is executed, the CPU treats it like an interrupt - stops its normal flow of execution, saves its state and jumps to a handler routine. Such "traps" allow many of the wonders of modern OSes (task scheduling, virtual memory, memory protection, debugging) to be implemented efficiently.
Some programming errors (such as division by 0) are also treated by the CPU as traps, and are frequently referred to as "exceptions". Here the line between hardware and software blurs, since it's hard to say whether such exceptions are really hardware interrupts or software interrupts. But I've digressed too far away from the main topic, so it's time to get back to breakpoints.
int 3 in theory
Having written the previous section, I can now simply say that breakpoints are implemented on the CPU by a special trap called int 3. int is x86 jargon for "trap instruction" - a call to a predefined interrupt handler. x86 supports the int instruction with a 8-bit operand specifying the number of the interrupt that occurred, so in theory 256 traps are supported. The first 32 are reserved by the CPU for itself, and number 3 is the one we're interested in here - it's called "trap to debugger".
Without further ado, I'll quote from the bible itself [2]:).
The part in parens is important, but it's still too early to explain it. We'll come back to it later in this article.
int 3 in practice
Yes, knowing the theory behind things is great, OK, but what does this really mean? How do we use int 3 to implement breakpoints? Or to paraphrase common programming Q&A jargon - Plz show me the codes!
In practice, this is really very simple. Once your process executes the int 3 instruction, the OS stops it [3]. On Linux (which is what we're concerned with in this article) it then sends the process a signal - SIGTRAP.
That's all there is to it - honest! Now recall from the first part of the series that a tracing (debugger) process gets notified of all the signals its child (or the process it attaches to for debugging) gets, and you can start getting a feel of where we're going.
That's it, no more computer architecture 101 jabber. It's time for examples and code.
Setting breakpoints manually
I'm now going to show code that sets a breakpoint in a program. The target program I'm going to use for this demonstration is the following:
section .text ; The _start symbol must be declared for the linker (ld) global _start _start: ; Prepare arguments for the sys_write system call: ; - eax: system call number (sys_write) ; - ebx: file descriptor (stdout) ; - ecx: pointer to string ; - edx: string length mov edx, len1 mov ecx, msg1 mov ebx, 1 mov eax, 4 ; Execute the sys_write system call int 0x80 ; Now print the other message mov edx, len2 mov ecx, msg2 mov ebx, 1 mov eax, 4 int 0x80 ; Execute sys_exit mov eax, 1 int 0x80 section .data msg1 db 'Hello,', 0xa len1 equ $ - msg1 msg2 db 'world!', 0xa len2 equ $ - msg2
I'm using assembly language for now, in order to keep us clear of compilation issues and symbols that come up when we get into C code. What the program listed above does is simply print "Hello," on one line and then "world!" on the next line. It's very similar to the program demonstrated in the previous article.
I want to set a breakpoint after the first printout, but before the second one. Let's say right after the first int 0x80 [4], on the mov edx, len2 instruction. First, we need to know what address this instruction maps to. Running objdump -d:
traced_printer2: file format elf32-i386 Sections: Idx Name Size VMA LMA File off Algn 0 .text 00000033 08048080 08048080 00000080 2**4 CONTENTS, ALLOC, LOAD, READONLY, CODE 1 .data 0000000e 080490b4 080490b4 000000b4 2**2 CONTENTS, ALLOC, LOAD, DATA Disassembly of section .text: 08048080 <.text>: 8048080: ba 07 00 00 00 mov $0x7,%edx 8048085: b9 b4 90 04 08 mov $0x80490b4,%ecx 804808a: bb 01 00 00 00 mov $0x1,%ebx 804808f: b8 04 00 00 00 mov $0x4,%eax 8048094: cd 80 int $0x80 8048096: ba 07 00 00 00 mov $0x7,%edx 804809b: b9 bb 90 04 08 mov $0x80490bb,%ecx 80480a0: bb 01 00 00 00 mov $0x1,%ebx 80480a5: b8 04 00 00 00 mov $0x4,%eax 80480aa: cd 80 int $0x80 80480ac: b8 01 00 00 00 mov $0x1,%eax 80480b1: cd 80 int $0x80
So, the address we're going to set the breakpoint on is 0x8048096. Wait, this is not how real debuggers work, right? Real debuggers set breakpoints on lines of code and on functions, not on some bare memory addresses? Exactly right. But we're still far from there - to set breakpoints like real debuggers we still have to cover symbols and debugging information first, and it will take another part or two in the series to reach these topics. For now, we'll have to do with bare memory addresses.
At this point I really want to digress again, so you have two choices. If it's really interesting for you to know why the address is 0x8048096 and what does it mean, read the next section. If not, and you just want to get on with the breakpoints, you can safely skip it.
Digression - process addresses and entry point
Frankly, 0x8048096 itself doesn't mean much, it's just a few bytes away from the beginning of the text section of the executable. If you look carefully at the dump listing above, you'll see that the text section starts at 0x08048080. This tells the OS to map the text section starting at this address in the virtual address space given to the process. On Linux these addresses can be absolute (i.e. the executable isn't being relocated when it's loaded into memory), because with the virtual memory system each process gets its own chunk of memory and sees the whole 32-bit address space as its own (called "linear" address).
If we examine the ELF [5] header with readelf, we get:
$ readelf -h traced_printer248080 Start of program headers: 52 (bytes into file) Start of section headers: 220 (bytes into file) Flags: 0x0 Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 2 Size of section headers: 40 (bytes) Number of section headers: 4 Section header string table index: 3
Note the "entry point address" section of the header, which also points to 0x8048080. So if we interpret the directions encoded in the ELF file for the OS, it says:
- Map the text section (with given contents) to address 0x8048080
- Start executing at the entry point - address 0x8048080
But still, why 0x8048080? For historic reasons, it turns out. Some googling led me to a few sources that claim that the first 128MB of each process's address space were reserved for the stack. 128MB happens to be 0x8000000, which is where other sections of the executable may start. 0x8048080, in particular, is the default entry point used by the Linux ld linker. This entry point can be modified by passing the -Ttext argument to ld.
To conclude, there's nothing really special in this address and we can freely change it. As long as the ELF executable is properly structured and the entry point address in the header matches the real beginning of the program's code (text section), we're OK.
Setting breakpoints in the debugger with int 3
To set a breakpoint at some target address in the traced process, the debugger does the following:
- Remember the data stored at the target address
- Replace the first byte at the target address with the int 3 instruction
Then, when the debugger asks the OS to run the process (with PTRACE_CONT as we saw in the previous article), the process will run and eventually hit upon the int 3, where it will stop and the OS will send it a signal. This is where the debugger comes in again, receiving a signal that its child (or traced process) was stopped. It can then:
- Replace the int 3 instruction at the target address with the original instruction
- Roll the instruction pointer of the traced process back by one. This is needed because the instruction pointer now points after the int 3, having already executed it.
- Allow the user to interact with the process in some way, since the process is still halted at the desired target address. This is the part where your debugger lets you peek at variable values, the call stack and so on.
- When the user wants to keep running, the debugger will take care of placing the breakpoint back (since it was removed in step 1) at the target address, unless the user asked to cancel the breakpoint.
Let's see how some of these steps are translated into real code. We'll use the debugger "template" presented in part 1 (forking a child process and tracing it). In any case, there's a link to the full source code of this example at the end of the article.
/* Obtain and show child's instruction pointer */ ptrace(PTRACE_GETREGS, child_pid, 0, ®s); procmsg("Child started. EIP = 0x%08x\n", regs.eip); /* Look at the word at the address we're interested in */ unsigned addr = 0x8048096; unsigned data = ptrace(PTRACE_PEEKTEXT, child_pid, (void*)addr, 0); procmsg("Original data at 0x%08x: 0x%08x\n", addr, data);
Here the debugger fetches the instruction pointer from the traced process, as well as examines the word currently present at 0x8048096. When run tracing the assembly program listed in the beginning of the article, this prints:
[13028] Child started. EIP = 0x08048080 [13028] Original data at 0x08048096: 0x000007ba
So far, so good. Next:
/* Write the trap instruction 'int 3' into the address */ unsigned data_with_trap = (data & 0xFFFFFF00) | 0xCC; ptrace(PTRACE_POKETEXT, child_pid, (void*)addr, (void*)data_with_trap); /* See what's there again... */ unsigned readback_data = ptrace(PTRACE_PEEKTEXT, child_pid, (void*)addr, 0); procmsg("After trap, data at 0x%08x: 0x%08x\n", addr, readback_data);
Note how int 3 is inserted at the target address. This prints:
[13028] After trap, data at 0x08048096: 0x000007cc
Again, as expected - 0xba was replaced with 0xcc. The debugger now runs the child and waits for it to halt on the breakpoint:
/* Let the child run to the breakpoint and wait for it to ** reach it */ ptrace(PTRACE_CONT, child_pid, 0, 0); wait(&wait_status); if (WIFSTOPPED(wait_status)) { procmsg("Child got a signal: %s\n", strsignal(WSTOPSIG(wait_status))); } else { perror("wait"); return; } /* See where the child is now */ ptrace(PTRACE_GETREGS, child_pid, 0, ®s); procmsg("Child stopped at EIP = 0x%08x\n", regs.eip);
This prints:
Hello, [13028] Child got a signal: Trace/breakpoint trap [13028] Child stopped at EIP = 0x08048097
Note the "Hello," that was printed before the breakpoint - exactly as we planned. Also note where the child stopped - just after the single-byte trap instruction.
Finally, as was explained earlier, to keep the child running we must do some work. We replace the trap with the original instruction and let the process continue running from it.
/* Remove the breakpoint by restoring the previous data ** at the target address, and unwind the EIP back by 1 to ** let the CPU execute the original instruction that was ** there. */ ptrace(PTRACE_POKETEXT, child_pid, (void*)addr, (void*)data); regs.eip -= 1; ptrace(PTRACE_SETREGS, child_pid, 0, ®s); /* The child can continue running now */ ptrace(PTRACE_CONT, child_pid, 0, 0);
This makes the child print "world!" and exit, just as planned.
Note that we don't restore the breakpoint here. That can be done by executing the original instruction in single-step mode, then placing the trap back and only then do PTRACE_CONT. The debug library demonstrated later in the article implements this.
More on int 3
Now is a good time to come back and examine int 3 and that curious note from Intel's manual. Here it is again:
This one byte form is valuable because it can be used to replace the first byte of any instruction with a breakpoint, including other one byte instructions, without over-writing other code
int instructions on x86 occupy two bytes - 0xcd followed by the interrupt number [6]. int 3 could've been encoded as cd 03, but there's a special single-byte instruction reserved for it - 0xcc.
Why so? Because this allows us to insert a breakpoint without ever overwriting more than one instruction. And this is important. Consider this sample code:
.. some code .. jz foo dec eax foo: call bar .. some code ..
Suppose we want to place a breakpoint on dec eax. This happens to be a single-byte instruction (with the opcode 0x48). Had the replacement breakpoint instruction been longer than 1 byte, we'd be forced to overwrite part of the next instruction (call), which would garble it and probably produce something completely invalid. But what is the branch jz foo was taken? Then, without stopping on dec eax, the CPU would go straight to execute the invalid instruction after it.
Having a special 1-byte encoding for int 3 solves this problem. Since 1 byte is the shortest an instruction can get on x86, we guarantee than only the instruction we want to break on gets changed.
Encapsulating some gory details
Many of the low-level details shown in code samples of the previous section can be easily encapsulated behind a convenient API. I've done some encapsulation into a small utility library called debuglib - its code is available for download at the end of the article. Here I just want to demonstrate an example of its usage, but with a twist. We're going to trace a program written in C.
Tracing a C program
So far, for the sake of simplicity, I focused on assembly language targets. It's time to go one level up and see how we can trace a program written in C.
It turns out things aren't very different - it's just a bit harder to find where to place the breakpoints. Consider this simple program:
#include <stdio.h> void do_stuff() { printf("Hello, "); } int main() { for (int i = 0; i < 4; ++i) do_stuff(); printf("world!\n"); return 0; }
Suppose I want to place a breakpoint at the entrance to do_stuff. I'll use the old friend objdump to disassemble the executable, but there's a lot in it. In particular, looking at the text section is a bit useless since it contains a lot of C runtime initialization code I'm currently not interested in. So let's just look for do_stuff in the dump:
080483e4 <do_stuff>: 80483e4: 55 push %ebp 80483e5: 89 e5 mov %esp,%ebp 80483e7: 83 ec 18 sub $0x18,%esp 80483ea: c7 04 24 f0 84 04 08 movl $0x80484f0,(%esp) 80483f1: e8 22 ff ff ff call 8048318 <puts@plt> 80483f6: c9 leave 80483f7: c3 ret
Alright, so we'll place the breakpoint at 0x080483e4, which is the first instruction of do_stuff. Moreover, since this function is called in a loop, we want to keep stopping at the breakpoint until the loop ends. We're going to use the debuglib library to make this simple. Here's the complete debugger function:
void run_debugger(pid_t child_pid) { procmsg("debugger started\n"); /* Wait for child to stop on its first instruction */ wait(0); procmsg("child now at EIP = 0x%08x\n", get_child_eip(child_pid)); /* Create breakpoint and run to it*/ debug_breakpoint* bp = create_breakpoint(child_pid, (void*)0x080483e4); procmsg("breakpoint created\n"); ptrace(PTRACE_CONT, child_pid, 0, 0); wait(0); /* Loop as long as the child didn't exit */ while (1) { /* The child is stopped at a breakpoint here. Resume its ** execution until it either exits or hits the ** breakpoint again. */ procmsg("child stopped at breakpoint. EIP = 0x%08X\n", get_child_eip(child_pid)); procmsg("resuming\n"); int rc = resume_from_breakpoint(child_pid, bp); if (rc == 0) { procmsg("child exited\n"); break; } else if (rc == 1) { continue; } else { procmsg("unexpected: %d\n", rc); break; } } cleanup_breakpoint(bp); }
Instead of getting our hands dirty modifying EIP and the target process's memory space, we just use create_breakpoint, resume_from_breakpoint and cleanup_breakpoint. Let's see what this prints when tracing the simple C code displayed above:
$ bp_use_lib traced_c_loop [13363] debugger started [13364] target started. will run 'traced_c_loop' [13363] child now at EIP = 0x00a37850 [13363] breakpoint created , world! [13363] child exited
Just as expected!
The code
Here are the complete source code files for this part. In the archive you'll find:
- debuglib.h and debuglib.c - the simple library for encapsulating some of the inner workings of a debugger
- bp_manual.c - the "manual" way of setting breakpoints presented first in this article. Uses the debuglib library for some boilerplate code.
- bp_use_lib.c - uses debuglib for most of its code, as demonstrated in the second code sample for tracing the loop in a C program.
Conclusion and next steps
We've covered how breakpoints are implemented in debuggers. While implementation details vary between OSes, when you're on x86 it's all basically variations on the same theme - substituting int 3 for the instruction where we want the process to stop.
That said, I'm sure some readers, just like me, will be less than excited about specifying raw memory addresses to break on. We'd like to say "break on do_stuff", or even "break on this line in do_stuff" and have the debugger do it. In the next article I'm going to show how it's done.
References
I've found the following resources and articles useful in the preparation of this article:
- How debugger works
- Understanding ELF using readelf and objdump
- Implementing breakpoints on x86 Linux
- NASM manual
- SO discussion of the ELF entry point
- This Hacker News discussion of the first part of the series
- GDB Internals
| http://eli.thegreenplace.net/2011/01/27/how-debuggers-work-part-2-breakpoints | CC-MAIN-2017-13 | refinedweb | 3,231 | 67.99 |
I want to create a wizard in js.
steps :first_step,
:second_step
def show
case step
when :first_step
@r = R.new
when :second_step
end
render_wizard
end
def update
case step
when :first_step
@r = R.new(r_params)
when :second_step
end
render_wizard @r
end
"Missing template controller_step/second_step, application/second_step
with {:locale=>[:en], :formats=>[:html], :variants=>[],
:handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. ".
respond_to do |format|
format.js { render :js => ( render_wizard @r ) }
end
"AbstractController::DoubleRenderError in ...Controller#update"."
respond_to do |format|
format.js { render :js => ( render_wizard @room_types and return ) }
end
<%= form_for(@r, url: wizard_path, method: :put, remote: true) do |f| %>
....
<%= f.submit "Submit", class: "btn btn-default" %>
<% end %>
The
#render_wizard method defined in the
Wicked::Controller::Concerns::RenderRedirect is a wrapper method around the
ActionController::Base#render method. It
accepts a hash of options and passes it down to the controller's regular
#render method.
This is the source code from the Wicked library:
def render_wizard(resource = nil, options = {}) ... if @skip_to ... else render_step wizard_value(step), options end end def render_step(the_step, options = {}) if the_step.nil? || the_step.to_s == Wicked::FINISH_STEP ... else render the_step, options #<-- Here end end
Your code:
respond_to do |format| format.js { render :js => ( render_wizard @r ) } end
is basically doing:
respond_to do |format| format.js { render :js => ( render @r ) } end
which is in fact calling the render method twice.
As it is searching for a
.html template rather than a
.js.erb one, try adding a
formats: 'js' option to the render_wizard method. It should prepend ['js'] to the
:formats=>[:html] we see in the
Missing template error message.
respond_to do |format| format.js { render_wizard(@r, formats: 'js') } end
also, make sure the template's filename follows the rails convention and start with a
_. (ie:
_second_step.js.erb)
About the double render error, you are correct. You must return from the controller
#show or
#update method and prevent further code from calling the
#render method a second time. You seem to have fixed that problem already.
EDIT#1
It seems like you may be able to call this method directly in your controller.. :
def render_step(the_step, options = {}) # Wicked::FINISH_STEP = "wicked_finish" if the_step.nil? || the_step.to_s == Wicked::FINISH_STEP redirect_to_finish_wizard options else render the_step, options end end
I believe
the_step will be the partial's name. I think you should be able to call the
#render_step method from your controller.
You may be able to do:
def show respond_to do |f| f.js do case step when :first_step @r = R.new render_step(step) and return when :second_step ... end end end end | https://codedump.io/share/bHLuf2hvvwRD/1/rails-wicked-wizard-with-javascript | CC-MAIN-2016-44 | refinedweb | 418 | 68.16 |
Futures are part of the official Scala Library and a lot of well-known Scala frameworks and libraries rely on Futures. In this article Stéphane Derosiaux looks into whether Scala Futures are the past?
'We all started with Scala Futures. They bring so much power and their syntax is simple enough. “Concurrency and asynchrony made easy” could be their tagline.
Futures allow us to deal with “values that don’t exist yet”. We can create a pipeline of transformations on top that will be applied when the time comes: when the Future will be fulfilled.
We can execute Futures in parallel, we can also race them. As developers, we often need to deal with concurrent operations. We have several databases, several services: we always wait for some answers asynchronously.
This sort of code does not — should not — exist anymore, RPC-calls-looking-like-local-calls (RMI, CORBA, EJB) are gone:
val result: User = DB.Users.byId(42)
It should be gone, for the simple reason that it’s not possible to get the result instantly from a database or a service: the network is in-between, and the network is unreliable. It should be wrapped into some form of asynchronous effect, such as Future or even better: F[_].
Wrapping something into a Future or an asynchronous effect does not mean the code inside is asynchronous: JDBC is still synchronous and will still block its thread. Maybe JDBC-Next will be out some day.
Presence in the Scala Ecosystem
A lot of well-known Scala frameworks and libraries rely on Futures. Futures are part of the official Scala Library: it’s easy to work with and do not sound exotic to newcomers. No need to import any 3rd party library.
Akka is using Scala Futures all over the place. The ask operator ? returns a Future. akka.pattern.* uses Futures (after to define a timeout to some computations). pipeTo only listens to a Future to send its value to an actor. Same story in Akka Streams: mapAsync only accepts Futures.
Play Framework — based on Akka — also uses Futures where asynchrony is needed: the routes handlers can either be synchronous or return a Future (the ActionBuilder).
Apache Spark uses Futures to deal with async operations on RDDs (collectAsync, countAsync etc.), and with its internal RPC system.
From Future to the future
As you remember, once upon a time, all our repositories were typed like this:
trait ItemsRepository { def getById(id: Int): Future[Option[Item]] def save(item: Item): Future[Unit] }
Soon, Future's limitations became apparent. We started to use alternatives, such as Scalaz Task, Monix Task, cats-effect IO or typeclasses such as Sync[F].
Why is that?
- What do they offer that Futures can’t?
- What do they don’t offer that Futures force us to deal with?
Referential Transparency
As we saw in my previous post, Referential Transparency is a good way to write a robust program. It makes it easy to reason about, and resilient to refactoring mistakes.
Futures are clearly not referentially transparent because they are eager or strict (inverse of lazy), and they memoize their value.
Just typing this dead code (not used after) creates a side-effect (output):
Future(println("hello"))
If the codeblock inside throws an exception, nothing happens, the error is “gone” (because we didn’t “subscribed” to it).
If we use its reference several times:
val f = Future(println("hello")) Future.sequence(List(f, f, f, f))
We only get one side-effect (one “hello”) because it’s the same Future, and Futures memoize their result. Therefore, the computation is done only once.
This clearly goes against referential transparency because if we replace f by its value, we’ll get 4 side-effects (as you expect when reading the code here):
Future.sequence(List(Future(println("hello")), Future(println("hello")), Future(println("hello")), Future(println("hello"))))
“Yeah but it’s stupid, that will never happen to me”. It will happen when you’re going to inline or factor-out some piece of code. With referentially transparent code, you don’t have to think about it: it will just work as expected, the behavior won’t change for sure. Playing with Future is playing with fire.
A Future doesn’t describe an execution, it executes.
Accidental Sequentiality & Consistent Execution
Who never ran into the following mistake?
def getUser(id: Int): Future[User] = ??? def getAds(): Future[List[Ad]] = ??? for { user <- getUser(5) ads <- getAds() bestAds <- findBestAdsForUser(user, ads) } yield bestAds
Our computation is sequential (getAds() being executed in the flatMap of getUser(5)) but getUser(5) and getAds() should be concurrent: they don’t rely on each other, they are independent.
We have 2 solutions, either start them (at least the second one) beforehand:
val allAds = getAds() // the Future starts here for { user <- user ads <- allAds // will rely on memoization bestAds <- findBestAdsForUser(user, ads) } yield bestAds
Or we clearly state the intent that both are independent (better) thanks to Future’s Applicative (provided by cats):
(getUser(5), getAds()).mapN(findBestAdsForUser)
With Task (or IO), the intermediate solution wouldn’t fix our issue (create the Task before), because it’s just declarative (lazy), the computation would not start beforehand. We would need to make our explicit our concurrency, and use the latter form (the Applicative’s).
With Futures, our code acts differently according to where we write our code. We should not expect this behavior.
This differentiated behaviour of Futures is not a “fix” to come help us, instead it is indicative of something (the concurrency). We need to understand how our program works, and have an execution consistent to the code written.
Memoization is a two-edged sword
As we saw, Future memoizes its result. You can ask its result a thousand times, it will always return the same result, cached in its internals.
It can be super useful to cache some HTTP results for instance. You know you can dispatch the same Future here and there, only one call will be made and everything will share its result.
Unfortunately, it’s also a downside and make it non-functional according to the referential transparency:
val f = Future(println("hello")) Await.result(f, Duration.Inf) Await.result(f, Duration.Inf)
This will only print “hello” once. The Future being eager, the computation and side-effect has already been evaluated on the first line. Waiting for its result 0 or N times doesn’t change a thing even if the code “looks like” it will do the execution several times.
When you don’t want memoization, you have no choice, you must create a new reference to cause a new execution. If you have already a reference (to a Task or IO), you can re-execute as many times as you want to provide a new computation (imagine a call to a service that gives the time).
Note that Monix Task provides a way to memoize its result: it’s explicit to the reader and more granular. We can memoize only on successes, to retry on failures.
ExecutionContext is like a cockroach
We can’t talk about Futures without talking about its ExecutionContext: they form a duo (unfortunately).
A Future and most of its functions (map, flatMap, onComplete) must know where to execute, on which thread: this is what an ExecutionContext provides.
Each time we add a transformation or a callback, we must provide an ExecutionContext, it’s part of the implicits:
def onComplete[U](f: Try[T] => U)(implicit executor: ExecutionContext): Unit def foreach[U](f: T => U)(implicit executor: ExecutionContext): Unit def map[S](f: T => S)(implicit executor: ExecutionContext): Future[S] def flatMap[S](f: T => Future[S])(implicit executor: ExecutionContext): Future[S]
If you have a polymorphic trait based on F[_] (à la tagless final), you can’t obviously add '(implicit ec: ExecutionContext)' to all your methods: F[_] is abstract and can be something else than Future, which wouldn’t need any ExecutionContext. Therefore, the implementation would need to add it in its constructor but it’s not a good choice — and no, we must no rely on the global ExecutionContext.
It means the ExecutionContext was decided early on (generally on startup) and therefore is fixed. But callers should be able to decide on which ExecutionContext they want to run your function (like using their own). It’s not the responsability of the callee service to enforce it (exceptions aside).
Moreover, with Futures, you must add this implicit ec: ExecutionContexteverywhere. It propagates into all your codebase because you must follow the functions path: a() calls b() calls c() which needs an ExecutionContext? So you need to add the implicits to a() and b()! How not great is that?
Task and its friends doesn’t need this because they don’t execute anything right away. The ExecutionContext or Scheduler is only provided at the “end of the world” when the program really starts the executions — exception aside when you want to run a computation in a specific context like with executeOn.
It means your functions don’t have to pass any implicit, and your abstractions can stay abstract without any ExecutionContext dependency.
No Traverse typeclass instance
Future.sequence and Future.traverse — equivalent of .map + .sequence — are also functions provided in cats by the Traverse typeclass. T̵a̵s̵k̵ ̵a̵n̵d̵ ̵I̵O̵ ̵b̵o̵t̵h̵ ̵h̵a̵v̵e̵ ̵a̵n̵ ̵i̵n̵s̵t̵a̵n̵c̵e̵s̵ ̵o̵f̵ ̵T̵r̵a̵v̵e̵r̵s̵e̵.̵ Edit: This statement was just wrong. Traverse is not available for IO nor Task. Task provides a custom .sequence() and IO none of them. You can disregard the rest of this paragraph. It was late.
Traverse also provides more generic methods to avoid typing complex chunks of code which could introduce bugs, such as flatTraverse or traverseWithIndexM, and also exposes all the features from its parents: Functor and Foldable typeclasses (fold*, reduce*, partitionEither, and way more).
But because of the Futures peculiarities, it’s not possible to provide a Traverse instance for Future.
You can’t reuse your knowledge provided by these typeclasses — they apply on many things beside asynchronous computations, such as List — and you can’t make your program dependent on those typeclasses while relying on Future, because there is no such instance!
Cancellation
When we race Futures, the losers are not cancelled.
It means the processing (.map, .flatMap) is still going on even when the fastest Future already won, and the result is going to be discarded anyway. The “pipeline” of transformations will get to its end, because there is no such thing as cancellation with Futures — with Twitter’s Futures, there is something called Future Interrupts but it’s really not the same semantic.
Let’s see a Future race in action:
def waitFor(d: Duration): Future[Duration] = Future(Thread.sleep(d.toMillis)) .map(_ => { println(s"in map: $d"); d }) val f = Future.firstCompletedOf(List( waitFor(1.second), waitFor(2.second)) ) val x = Await.result(f, Duration.Inf) println(s"done in $x")
This will print:
in map: 1 second done in 1 second in map: 2 seconds
Just replace the println in the map with a webservice or database call, with a reading operation on a file or anything, and you understand why cancellation matters: you don’t want to process things for nothing.
It’s a common pattern to race several things to only keep the earliest, like a timeout exception, or to provide a fallback.
With Monix Task or cats-effect IO, we have the possibility to short-circuit the executions thanks to cancellation:
// The code is different from the previous one; it's more idiomatic to cats-effect def waitFor[F[_]](d: FiniteDuration) (implicit T: Timer[F], S: Sync[F]): F[Duration] = { for { _ <- T.sleep(d) x <- S.delay { println(s"in flatMap: $d"); d } } yield x } val t = IO.race(waitFor[IO](1.second), waitFor[IO](2.second)) val y = t.unsafeRunSync println(s"done in $y")
This will print:
in flatMap: 1 second done in Left(1 second)
The second execution has not finished: the sleep was cancelled.
Cancellation occurs for each cancellation boundary which can be set between flatMaps with IO.cancelBoundary or by using IO.cancelable to define a custom cancellable IO.
Cancellation needs to know what to do if it’s triggered, it’s not just some throw new CancelException, it’s smarter than this, and we have to write this code (like set a Boolean to False to break a loop, or cancel some thread scheduling).
Cancellation is not only useful when we are racing computations. It’s also important to deal with errors when we process async executions in parallel. We generally want to stop and deal with the error, stopping the other executions and discarding their results such as demonstrated here:
def crash: Future[Duration] = Future.failed(new Exception("boom")) val f = Future.sequence(List(crash, waitFor(1.second))) val x = Try(Await.result(f, Duration.Inf)) println(s"result: $x")
This will print:
result: Failure(java.lang.Exception: boom) in map: 1 second
The second Future was executed despite the first one crashing instantly.
If we do this with IO, the result is different:
def crash[F[_]](implicit F: Sync[F]): F[Duration] = F.raiseError(new Exception("boom")) val t = IO.race(crash2[IO], waitFor2[IO](1.second)) val y = t.attempt.unsafeRunSync println(s"done in $y")
This will print:
done in Left(java.lang.Exception: boom)
Again, the second IO was cancelled.
We see that the IO/Task models are smarter thanks to their cancellation logic. It leads to avoid uncessary processing, which can result in less CPU/Network/Memory used, according to the prevented computations.
Viktor Klang provided a solution for Future’s cancellation relying on Thread’s interruptions.
Performance
If performance matters, then the following tweet says it all.
I didn’t find any recent benchmark (it’s almost been a year since this tweet! cats was 0.4, it’s 1.2 now!) and didn’t try myself (booo). If you have a recent version, feel free to share it, I’ll update this section accordingly.
Conclusion
Scala Futures were a very good trampoline to highest standards provided by 3rd party libraries such as scalaz, cats, and monix.
Still, Futures improved over time (tons of optimizations in 2.12) but they can’t just break their model (and probably do no wish to).
A part of the Scala community seems to stray to the pure functional programming paradigm — with the rise of scalaz-zio, cats, monix, and advanced patterns based on typeclasses. It means Future can’t be of any help here, and this is where Task and IOs shine.
Thanks for all the fish.'
This article was written by Stéphane Derosiaux and posted originally on Medium. | https://www.signifytechnology.com/blog/2018/09/are-scala-futures-the-past-by-stephane-derosiaux | CC-MAIN-2019-13 | refinedweb | 2,476 | 55.64 |
SUSI.AI now has a new action type called RSS. As the name suggests, SUSI is now capable of searching the internet to answer user queries. This web search can be performed either on the client side or the server side. When the web search is to be performed on the client side, it is denoted by websearch action type. When the web search is performed by the server itself, it is denoted by rss action type. The server searches the internet and using RSS feeds, returns an array of objects containing :
- Title
- Description
- Link
- Count
Each object is displayed as a result tile and all the results are rendered as swipeable tiles.
Lets visit SUSI WebChat and try it out.
Query : Google
Response: API response
SUSI WebChat uses the same code abstraction to render websearch and rss results as both are results of websearch, only difference being where the search is being performed i.e client side or server side.
How does the client know that it is a rss action type response?
"actions": [ { "type": "answer", "expression": "I found this on the web:" }, { "type": "rss", "title": "title", "description": "description", "link": "link", "count": 3 } ],
The actions attribute in the JSON API response has information about the action type and the keys to be parsed for title, link and description.
- The type attribute tells the action type is rss.
- The title attribute tells that title for each result is under the key – title for each object in answers[0].data.
- Similarly keys to be parsed for description and link are description and link respectively.
- The count attribute tells the client how many results to display.
We then loop through the objects in answers,data[0] and from each object we extract title, description and link.
let rssKeys = Object.assign({}, data.answers[0].actions[index]); delete rssKeys.type; let count = -1; if(rssKeys.hasOwnProperty('count')){ count = rssKeys.count; delete rssKeys.count; } let rssTiles = getRSSTiles(rssKeys,data.answers[0].data,count);
We use the count attribute and the length of answers[0].data to fix the number of results to be displayed.
// Fetch RSS data export function getRSSTiles(rssKeys,rssData,count){ let parseKeys = Object.keys(rssKeys); let rssTiles = []; let tilesLimit = rssData.length; if(count > -1){ tilesLimit = Math.min(count,rssData.length); } for(var i=0; i<tilesLimit; i++){ let respData = rssData[i]; let tileData = {}; parseKeys.forEach((rssKey,j)=>{ tileData[rssKey] = respData[rssKeys[rssKey]]; }); rssTiles.push(tileData); } return rssTiles; }
We now have our list of objects with the information parsed from the response.We then pass this list to our renderTiles function where each object in the rssTiles array returned from getRSSTiles function is converted into a Paper tile with the title and description and the entire tile is hyperlinked to the given link using Material UI Paper Component and few CSS attributes.
// Draw Tiles for Websearch RSS data export function drawTiles(tilesData){ let resultTiles = tilesData.map((tile,i) => { return( <div key={i}> <MuiThemeProvider> <Paper zDepth={0} <a rel='noopener noreferrer' href={tile.link} {tile.icon && (<div className='tile-img-container'> <img src={tile.icon} </div> )} <div className='tile-text'> <p className='tile-title'> <strong> {processText(tile.title,'websearch-rss')} </strong> </p> {processText(tile.description,'websearch-rss')} </div> </a> </Paper> </MuiThemeProvider> </div> ); }); return resultTiles; }
The tile title and description is processed for HTML special entities and emojis too using the processText function.
case 'websearch-rss':{ let htmlText = entities.decode(text); processedText = <Emojify>{htmlText}</Emojify>; break; }
We now display our result tiles as a carousel like swipeable display using react-slick. We initialise our slider with few default options specifying the swipe speed and the slider UI.
import Slider from 'react-slick'; // Render Websearch RSS tiles export function renderTiles(tiles){ if(tiles.length === 0){ let noResultFound = 'NO Results Found'; return(<center>{noResultFound}</center>); } let resultTiles = drawTiles(tiles); var settings = { speed: 500, slidesToShow: 3, slidesToScroll: 1, swipeToSlide:true, swipe:true, arrows:false }; return( <Slider {...settings}> {resultTiles} </Slider> ); }
We finally add CSS attributes to style our result tile and add overflow for text maintaining standard width for all tiles.We also add some CSS for our carousel display to show multiple tiles instead of one by default. This is done by adding some margin for child components in the slider.
.slick-slide{ margin: 0 10px; } .slick-list{ max-height: 100px; }
We finally have our swipeable display of rss data tiles each tile hyperlinked to the source of the data. When the user clicks on a tile, he is redirected to the link in a new window i.e the entire tile is hyperlinked. And when there are no results to display, we show a `NO Results Found` message.
The complete code can be found at SUSI WebChat Repo. Feel free to contribute
Resources | https://blog.fossasia.org/how-susi-webchat-implements-rss-action-type/ | CC-MAIN-2017-39 | refinedweb | 786 | 58.08 |
The method
nextInt(int bound) of
Random accepts an upper exclusive boundary, i.e. a number that the returned random value must be less than. However, only the
nextInt method accepts a bound;
nextLong,
nextDouble etc. do not.
Random random = new Random(); random.nextInt(1000); // 0 - 999 int number = 10 + random.nextInt(100); // number is in the range of 10 to 109
Starting in Java 1.7, you may also use
ThreadLocalRandom (source). This class provides a thread-safe PRNG (pseudo-random number generator). Note that the
nextInt method of this class accepts both an upper and lower bound.
import java.util.concurrent.ThreadLocalRandom; // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive ThreadLocalRandom.current().nextInt(min, max + 1);
Note that the official documentation states that
nextInt(int bound) can do weird things when
bound is near 230+1 (emphasis added):
The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 2^31 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=2^30+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop terminates is 2.
In other words, specifying a bound will (slightly) decrease the performance of the
nextInt method, and this performance decrease will become more pronounced as the
bound approaches half the max int value. | https://riptutorial.com/java/example/2984/pseudo-random-numbers-in-specific-range | CC-MAIN-2020-50 | refinedweb | 246 | 56.35 |
Acme::Voodoo - Do bad stuff to your objects
use Acme::Voodoo; my $voodoo = Acme::Voodoo->new( 'CGI' ); print ref( $voodoo ); ## prints Acme::Voodoo::Doll_1 print $voodoo->header(); ## same as calling CGI::header() @pins = $voodoo->pins(); ## get a list of methods you can call $voodoo->zombie(); ## make our program sleep for a while ## the next time a method is called $voodoo->kill(); ## or make our program die the next ## time it is called
Voodoo is an Afro-Caribbean religion that mixed practices from the Fon, the Nago, the Ibos, Dahomeans, Congos, Senegalese, Haussars, Caplauous, Mondungues, Madinge, Angolese, Libyans, Ethiopians and the Malgaches. With a bit of Roman Catholicism thrown in for good measure. This melange was brought about by the enforced immigration of African slaves into Haiti during the period of European colonizaltion of Hispaniola. The colonists thought that a divided group of different tribes would be easier to enslave; but little did they know that the tribes had a common thread.
In reality the actual religion is called "Vodun", while "Voodoo" is a largely imaginary religion created by Hollywood movies. Vodun priests can be male (houngan) and female (mambo) and confine their activites to "white" magic. However caplatas (also known as bokors) do practice acts of evil sorcery, which is sometimes referred to "left-handed Vodun".
Acme::Voodoo is mostly "left handed" and somewhat "Hollywood-ish" but can bring a bit of spice to your programs. You can cast fairly simple spells on your program to make it hard to understand, or to make it die a horrible death. If you would like to add a spell please email me a patch. Or send it via astral-projection. Acme::Voodoo is essentially an experiment in symbol tables gone horribly wrong.
Creates a voodoo doll object. You must pass the namespace of your subject. If your subject isn't within spell distance (the class can't be found) an exception will be thrown. Otherwise you get back your doll, an Acme::Voodoo::Doll object.
use Acme::Voodoo; my $doll = Acme::Voodoo->new( 'CGI' ); print $doll->header();
Pass this function your voodoo doll and you'll get back a list of pins you can use on your doll.
my @pins = $doll->pins();
A method to turn your object into a zombie. The next method call on the object will cause your program to go into limbo for an unpredictable amount of time. When it wakes up, it will do what you asked it to do, and will feel fine from then on, having no memory of what happened. If you know how long you want your target to go to sleep for, pass the number of seconds in.
When you kill your doll the next time someone calls a method on it it will cause your program to die a horrible and painful death.
$doll->kill(); $doll->method(); ## arrrrrggggghhhh!!
Ed Summers, <ehs@pobox.com>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Just be sure not to use it for anything important. | http://search.cpan.org/~esummers/Acme-Voodoo-0.3/lib/Acme/Voodoo.pm | CC-MAIN-2015-35 | refinedweb | 512 | 69.62 |
Diving Into .NET Web Development
Many people think of PHP, Ruby on Rails or Python and Django when choosing a language to create a new website or when choosing a language to learn to get that exciting new job. .NET, however, seems to occupy a space somewhat apart from this playground of cool kids. It’s always the last to be picked for team sports; it was shouting “Wassup!” at parties well after 2000; and it has been just plain left out in the cold.
I’m not one of these people. In fact, I’m quite a fan of .NET and have found it great to develop with since moving away from PHP in the early days of my career. With its great tools, large community and broad applicability (mobile, Xbox, desktop and Web) it’s both powerful and fun.
Further Reading on SmashingMag:
- Upcoming Web Design Conferences
- Women In Web Design: Group Interview
- Server-Side Rendering With React, Node And Express
- An Introduction To Full-Stack JavaScript fee graduate)..
Servers And Hosting
The Microsoft tax comes back to bite us here. But it doesn’t amount to a huge difference in cost. For example, for a VPS with the UK hosting provider Memset, a Windows box is £4 per month more than a Linux one. And the Microsoft website lists other hosts. Of course, you could go with Linux hosting, get yourself a VPS and configure mod_mono for your website.
What will hurt your wallet is licensing standard editions of SQL server. With this, you’ll have to balance the pros and cons of tight integration with the rest of the Microsoft ecosystem. You may, for example, go with the half-and-half approach to save on costs if you aren’t eligible for licensing discounts or if you are not happy with the restrictions put on SQL Express (such as the number of processors, RAM, etc).
A Brief Interlude
Is Mono Really an Option?
Mono has been around for a long time, but Microsoft doesn’t support it in the same way that it supports its own platform. Additionally it is usually slightly behind the C# developments coming out of Microsoft because the team has to catch up. The Mono website lists the areas of compatibility between the two. As you can see, the amount of coverage is large.
Finding shared hosts that provide for Mono might be hard, so you could find yourself configuring it on a VPS manually.
Actual Coding?
This is where we really get into some of the myths surrounding .NET. In my experience, many Web developers have a very negative perception it:
- Bloated markup,
- Lack of control over element IDs,
- Large base 64-encoded form elements,
- One form to rule them all,
- An odd paradigm that mirrors Windows development.
However, many of these issues actually apply to ASP.NET Web forms, which, although joined only recently by ASP.NET MVC (and even more recently by the Web API in MVC4), was never the only platform for serving Web pages using the ASP.NET base libraries. Not only are there mini frameworks out there, but you could use “Web forms” and just implement some of your HTML output and templates in another way; for example, with XSLT. Or you could even stick with Web forms but use libraries, such as the CSS control adapters, or restrict yourself to repeaters as opposed to grid views, etc. In fact, with the relatively recent additions to WebForms, we are seeing efforts to address these markup concerns.
This may not mean a lot to you if you haven’t used those systems, and I don’t want to get into it too much. The bloated markup was a sign of over-reliance on “controls”, where the final HTML was effectively hidden from the developer, and extras such as
viewstate were added to mask the stateless nature of the Web. The paradigm itself was quite different from “normal Web development,” with a very desktop-style event-based approach: server-side
button_click events, etc. This was useful for Windows developers who were migrating, but it often made Web developers, including me, balk.
The demo below uses an ASP.NET MVC project, but be aware that some of those old prejudices against using the Microsoft stack could be a more narrow dislike of old Web forms, rather than of C# or .NET generally.
Finally, The Example
Rather than patronize you with a step-by-step guide to installing tools using a GUI (the Web platform installer), I’ve created a sample project that you can access via GitHub. There is no data access (that topic could cover a whole series of articles). The aim is to give you a taste of ASP.NET pages, to show your range of options, and to provide a look at the code layout and tools so that you can try things out for yourself.
Tooling Up Your Development Machine
The easiest way is to get your hands on the following:
- Windows
- The Web platform installer
- Install “Visual Web Developer 2010 Express” or a Visual Studio 2010 trial (note that there are different Expresses, such as an Express for Phone).
- Install “ASP.NET MVC 3 (Visual Studio 2010).”
- If you want to run the IronPython demo, then you will also need to install IronPython
- If you want to play with the F# examples (and you are using Express, rather than a trial or standard edition Visual Studio), then you will need these:
- Visual Studio 2010 Shell
- The most recent F# CTP
Pull the project from the demo page and open it in your newly installed Visual Studio IDE. You should see something like this:
The DotNetDev project in Visual Web Developer Express
The DotNetDev project open in Visual Studio Standard
The only difference between the two is that I’ve used a feature of the paid for Visual Studio to add “Solution” folders for readability.
If you want to see the demo code running, I’ve put a copy of it on my server. As you’ll see, the demo pages include additional notes and highlighted code sections to explain the inner workings.
DotNetDev C# MVC example running in Chrome
Although the code looks like a lot here, the examples are extremely simple. In fact, each Web project simply outputs a classic “Hello world” phrase. However, each project uses either a different language or framework for the task. Hopefully, this should give you some insight into the options available to you.
If you want to immediately run any of the examples, simply right-click on the project that you want to run and choose
Debug → Start new instance. Visual Studio will launch the website in your default browser, powering the code with the built-in Web server that comes bundled with Visual Studio (you will also see this little server running in your system tray).
Notes On The Examples
ASP.NET MVC C# and VB (Two Separate Projects)
These two projects show the most well-known and most used methods of website creation in the .NET framework.
The following are the two key areas in the non-database-driven ASP.NET MVC (C# code shown):
1. Routes (Global.asax)
routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Message", action = "Index", id = UrlParameter.Optional } // Parameter defaults );
This is the initial entry point of the website. With some simple pattern matching of URL strings, we can transpose a request to an instance of a controller and an action method upon that controller. Additional parameters relate directly to those required by the method. For example,
{controller}/{action}/{id} will work for
/messages/edit/1 (i.e. message controller → edit action → sending 1 as the ID parameter to the method) or
products/index (i.e. products controller → index action).
2. Controllers (MessageController.cs)
public class MessageController : Controller { public ActionResult Index() { return View(new Message { Text = "Hello C# ASP.NET MVC World!" }); } }
The MessageController is an IController class instantiated by the ASP.NET engine per request when the above route is matched. A method matching the action name will be called.
3. View Models (Message.cs)
public class Message { public string Text { get; set; } }
Although passing data to a view via a dictionary (the ViewBag) is possible, it is generally considered a better practice to package up the data that is required by a particular view into a “View Model,” used as a transfer object between the model and template.
4. Views (index.cshtml)
@model Message <h2>Dot Net Dev</h2> @Model.Text
The templating engine used in these examples is known as Razor. The approach of Razor is to have minimal impact on the code. The
@ symbol is used to denote the beginning of code. If followed by a view model variable, it will be outputted to the HTML.
F
open System open System.Web.Mvc open DotNetDev.Mvc.FSharp.ViewModels [<HandleError>] type MessageController() = inherit Controller() member x.Index() = x.ViewData.Model <- new Message "Hello F# ASP.NET MVC World!" x.View()
The F# example shows a slightly different take on the .NET framework. In this case, the functional F# language (often used in the financial sector) is used to define the routes, controllers and models in a class library project. To be fair, the example used here is simple enough (as is my knowledge of F#) that the code is still reasonably imperative.
Also, note that the F# example shows how F# and C# can be used together, allowing you to, if appropriate and useful, use libraries of each in the other.
One point to note if you are trying to run this example via Web Developer Express is that F# library projects are not supported. However, you can use the also free VS2010 Shell and F# CTP to view the source, compile it and then run the Web project (DotNetDev.Mvc.FSharp.Web) from Express itself using that compiled library.
IronPython
class MessageController(Controller) : def __init__(self): self.ActionInvoker = DynamicActionInvoker(self) def Index(self): return self.View("index", Message("Hello IronPython ASP.NET MVC World!"))
The IronPython example shows how the DLR can be used to execute Python code from within a .NET application. The PythonControllers.py file contains all of the Python code needed to do this. Again, as with F#, multiple languages can work together in a .NET project.
Experienced .NET developers might be interested to look at the implementation of the DynamicActionInvoker that I’m using, which allows the use of dynamic controllers to serve the request (where traditional reflection to find the controller method would fail).
C# Using the Nancy Framework
The final example shows that we don’t need to use Microsoft’s framework(s) to render a website using C#. Here, I’m using the minimalist Nancy framework (inspired by Ruby’s Sinatra), one of a number of open-source .NET Web frameworks.
Almost all of the Nancy example is contained within the following code snippet:
public MessageModule() : base("/") { Get["/"] = x => { dynamic model = new Message { Text = "Hello Nancy World!" }; return View["message_index.cshtml", model]; }; }
Here, we can see the route pattern being defined and matched to a method in the same line, using a C# lambda (or inline anonymous function) assigned to a dictionary in the message module. This means that when a
GET request comes in for
/, the function body gets executed, and all it does is create a Message model, assign it to a dynamic variable and return it with the view’s name.
An Aside
The Nancy example also shows another useful feature of .NET. If you are used to tools such as PEAR, then you will be aware of the concept of package management. Essentially, using
[project] right click → Manage NuGet Packages from Visual Studio, you will be able to search online through a myriad of open-source and free libraries to use in your projects. In this case, I’ve used Andreas Hakansson et al’s Nancy Web framework.
Some Context (Headscape).
Please do run the code, play with it, check out the full demo (with additional notes on how this stuff all works), and let me know what you think.
Resources
- DotNetDev The running demo
- DotNetDev on GitHub The source code
- Microsoft Web Platform Installer The tools
- Microsoft BizSpark The licenses
- IronPython
- The Mono Project
(al) (km) (jc) | https://www.smashingmagazine.com/2012/07/dive-net-web-development/ | CC-MAIN-2021-31 | refinedweb | 2,058 | 61.87 |
Unexpected behavior of @jit and @boost
Recently I tested transonic with this simple code:
transonic_test.py
import numpy as np from transonic import jit,boost #transonic def norming(float[]) @boost def norming(np_array): norm_array = np.linalg.norm(np_array, axis=1) return norm_array
I use this command to compile it ahead-of-time:
transonic transonic_test.py -af "-march=native -DUSE_XSIMD -Ofast"
which ran successfully. However, when I execute the following program
transonic_test_main.py
from transonic_test import * from timeit import default_timer as timer start_1 = timer() for i in range(1000): in_arr = np.random.rand(10000, 3) norm_arr = norming(in_arr) end_1 = timer() print("time spent are {}".format(end_1 - start_1))
with python, the output shows:
DEBUG Using rich for tracking progress. WARNING Pythran file does not seem to be up-to-date: <module '__pythran__.transonic_test_4f3187f787722cc89a00775cc0002503' from '/Users/jw598/Desktop/high_entropy_ alloy/__pythran__/transonic_test_4f3187f787722cc89a00775cc0002503.cpython-37m-darwin.so'> func: norming time spent are 0.3765912619999999
with the timing almost the same as pure python. This problem is identical to the one reported here:
My system configuration is:
OS: MacOS Catalina 10.15.7
gcc: 10.2.0
python: 3.7.7
pythran: 0.9.8.post2
transonic: 0.4.7.post0
Thanks a lot!
Jingyang Wang
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information | https://foss.heptapod.net/fluiddyn/transonic/-/issues/40 | CC-MAIN-2021-43 | refinedweb | 219 | 53.78 |
Ruby on Rails || React Developer
Before any exposition could be made concerning rails errors and their causes, it is of great importance to know what ruby on rails is all about.
Ruby on Rails is an open source full-stack web application framework written in Ruby. It follows the popular MVC framework model and is known for its "convention over configuration" approach to application development. In the process of developing ruby on rails applications, there are occurrences of errors that have been taken note of.
By grouping errors according to fingerprinting, errors made in projects are being detected and collected with the help of the rollbar and the top 10 errors made by developers have been as well detected based on the frequency of occurrence of each error.
Therefore, from a close observation on thousands of ruby on rails project by developers, below are the top 10 errors that developers commit in their development scheme.
The first error we're examining is the ActionController::RoutingError. This kind of error occur when a user has requested a URL that doesn’t exist in his/her application. This error might occur because an incorrect link is pointing at your application or on the other hand pointing from within your application. It could also be caused by your application being bot tested for common weaknesses.
ActionController::RoutingError (No route matches [GET] "/wp-admin"):
Whenever you experience or come across this type of error, it most commonly occur due the application being used and not by errant users. If you deploy your application to Heroku or any other platform that doesn't permit you serving static files, you might therefore have your CSS and JavaScript not being able to load. If this is the case, the errors will appear like this:
ActionController::RoutingError (No route matches [GET] "/assets/application-eff78fd93759795a7be3aa21209b0bd2.css"):
This error could therefore be fixed by adding a line to your application's
as written below:
config/environments/production.rb
Rails.application.configure do config.public_file_server.enabled = true end
You might also decide not to go by logging 404 errors caused by
but instead set a catch on all routes and serve the 404 yourself. If you're interested in doing this, then you add the line written below at the bottom of your
ActionController::RoutingError
file as suggested by Lograge project:
config/routes.rb
Rails.application.routes.draw do # all your other routes match '*unmatched', to: 'application#route_not_found', via: :all end
Be sure to use this method only when you're sure that knowing 404 errors is important to you.
2. NoMethodError: undefined method '[]' for nil:NilClass
Sometimes, when parsing and extracting data from a JSON API or a CSV file, or when trying to get data from nested parameters in a controller action, errors do occur due to nil or missing object when you are using square bracket notation to read a property from an object.
You can fix this error by performing a nil check on each parameter and more efficiently, there is an alternative way to access nested elements in hashes, arrays and event objects like
.
ActionController::Parameters
We know that Ruby 2.3, hashes, arrays and
have the dig method. and dig helps to create a path to an object that is to be retrieved. Therefore, if in the process, nil is returned, then dig returns nil without throwing a NoMethodError.have the dig method. and dig helps to create a path to an object that is to be retrieved. Therefore, if in the process, nil is returned, then dig returns nil without throwing a NoMethodError.
ActionController::Parameters
3. ActionController::InvalidAuthenticityToken
Although there might be other reasons why you're experiencing this error on your application, it commonly occur due to the fact that an attacker is targeting the user of your site but the rail security measures are keeping you safe. In a case where POST, PUT, PATCH or DELETE is missing or has an incorrect CSRF token, then the error is said to be in place. Careful measures are needed to be taken since this error type is one which deals with your application's security.
You therefore can turn off your CSRF protection but sometimes, you expect to receive incoming posts request to certain URLs in your application. Therefore you can turn off CSRF protection but ensure that you are whistling the end point you know don't need the protection since you wouldn't want to block them (the third parties) on CSRF basis. You can accomplish this by skipping the authentication.
4. Net::ReadTimeout
When it takes ruby longer time to read data from a socket than the Read_Timeout value, then the.
Net::ReadTimeout
5. ActiveRecord::RecordNotUnique: PG::UniqueViolation
Right in your application, there is a certain database table that has a unique index on one or more field, this error would definitely occur if a transaction that violate the database is sent to it. This particular error message is therefore basically for PostgreSQL databases, but the ActiveRecord adapters for MySQL and SQLite will throw similar errors.
If the errors are caused by a race condition, that may be because a user has submitted a form twice by mistake. We can try to mitigate that issue with a bit of JavaScript to disable the submit button after the first click. You start by introducing something like this:
const forms = document.querySelectorAll('form'); Array.from(forms).forEach((form) => { form.addEventListener('submit', (event) => { const buttons = form.querySelectorAll('button, input[type=submit]') Array.from(buttons).forEach((button) => { button.setAttribute('disabled', 'disabled'); }); }); });
6. NoMethodError: undefined method 'id' for nil:NilClass
Unlike the error type explained earlier in number 2, these errors arises when validation fails, it (the error) usually sneaks up around the create action for an object with a relation. This error come in place when you call
from the create action, the
render :new
variable wasn't set.variable wasn't set.
@courseinstance
You therefore need to ensure that all the objects the new template needs are initialized in the create action. You can fix this problem by updating the create action to look like this;
def create @course_application = CourseApplication.new(course_application_params) if @course_application.save redirect_to @course_application, notice: 'Application submitted' else @course = Course.find(params[:course_id]) render :new end end
7. ActionController::ParameterMissing
Among of the rails strong parameters is this error. If you are building an application to be used via a web front end and you have built a form to correctly post the user parameters to this action, then a missing user parameter probably means someone is messing with your application. In this case, it's more likely that a 400 Bad Request would be best to be responded with. It usually does not occur or manifest as a 500 error.
The full error might look like this:
ActionController::ParameterMissing: param is missing or the value is empty: user
8. ActionView::Template::Error: undefined local variable or method
Error in this manner occur when a variable or method you believe or expect to exist does not. Among the top 10 commonly made errors that we're discussing, this is the only ActionView error. This instill that the less work the views have to do to render templates, the better as lesser works doesn't seem to have much errors.
9. ActionController::UnknownFormat
Simply speaking, this particular error occur due to the carelessness of users and not the application. Taken for instance, in a case whereby you built an application of which actions responds with HTML template and someone requests the JSON version of the page, the error tends to surface. You can therefore build your rails applications to respond to regular HTML requests and more API-like JSON requests in the same controller. By doing this, you define the formats you wish to respond to and any formats that is not in line with it will still bring about ActionController::UnknownFormat error thereby returning a 406 status.
10. StandardError: An error has occurred, this and all later migrations
canceled
Even though Standard error should be the parent errors to these errors we've been talking about but in reality, it is an error that only happened during a database migration. One of the reasons why you experience this error might be that your migrations may have gotten out of sync with your actual production database and in this case for instance, you will have to go dig around to find out what the problem is and fix it. If you want to add or calculate some data for all objects in a table, then data migration might seem to be a good option.
Take for instance, if you want to add a full name field to a user model that included their first and last name (not a likely change, but good enough for a simple example), your migration might seem like this:
class AddFullNameToUser < ActiveRecord::Migration def up add_column :users, :full_name, :string User.find_each do |user| user.full_name = "#{user.first_name} #{user.last_name}" user.save! end end def down remove_column :users, :full_name end end
Conclusively, the most popular rail errors can come from anywhere within the application. Even though these errors in a way serves as protection to our application, it is therefore unwise not to try get these errors caught and get them stamped out. It would help you detect and fix the problem as an engineer or product manager before users lodge the complains themselves.
Create your free account to unlock your custom reading experience. | https://hackernoon.com/top-10-most-common-ruby-on-rails-errors-and-their-causes-nmm3u7w | CC-MAIN-2020-50 | refinedweb | 1,586 | 50.06 |
Kind-polymorphic
Typeable
The page describes an improved implementation of the
Typeable class, using polymorphic kinds. Technically it is straightforward, but it represents a non-backward-compatible change to a widely used library, so we need to make a plan for the transition.
Relevant tickets we could thereby fix: #5391, #5863.
Open question: what are the corresponding changes to
Data.Data? See #4896,
The current
Typeable class
The current
Typeable class is:
class Typeable (a :: *) where typeOf :: a -> TypeRep
Because it is mono-kinded we also have
class Typeable1 (f :: *->*) where typeOf1 :: f a -> TypeRep
and so on up to
Typeable7. It's a mess, and we cannot make
Typeable at all for
type constructors with higher kinds like
Foo :: (* -> *) -> *
The new
Typeable class
Having polymorphic kinds lets us say this:
data Proxy t = Proxy class Typeable t where typeRep :: Proxy t -> TypeRep
Notice that
Typeableand
Proxyhave polymorphic kinds:
Proxy :: forall k. k -> * Typeable :: forall k. k -> Constraint
- The method is called
typeReprather than
typeOf
- One reason for the name change is that the argument is not a value of the type
t, but a value of type
(Proxy t). We have to do this because
tmay have any kind, so we can't say
typeOf :: t -> TypeRep
Now we can give give kind-specific instances:
instance Typeable Int where typeRep _ = ... instance Typeable [] where typeRep _ = ... instance (Typeable a, Typeable b) => Typeable (a b) where typeRep _ = ...
A use of
deriving( Typeable ) for a type constructor
T would always generate
instance Typable T where typeRep _ = ....
i.e. an instance of
T itself, not applied to anything.
Aside
Iavor suggested:
class Typeable (a :: k) where typeRep :: TTypeRep a newtype TTypeRep a = TR TypeRep
Is this perhaps better?
A change-over plan
In GHC 7.6:
- Rename
Data.Typeableto
Data.OldTypeableand deprecate the whole module.
- Define a new library
Data.Typeablewith the new definitions in them.
- Include in
Data.Typeableold methods for backward compatibility, but deprecate them:
typeOf :: forall a. Typeable a => a -> TypeRep typeOf _ = typeRep (Proxy :: Proxy a) typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep typeOf1 _ = typeRep (Proxy :: Proxy t)
- Make
deriving( Typeable )work with whatever
Typeableclass is in scope. So what it does will be determined by whether you say
import Data.Typeableor
import Data.OldTypeable.
I think that means that old programs will continue to work in GHC 7.6, provided
- You did not mention
Typeable1etc explicitly
- You used
deriving( Typeable )to write instances.
In GHC 7.8:
- Remove
Data.OldTypeable | https://ghc.haskell.org/trac/ghc/wiki/GhcKinds/PolyTypeable?version=6 | CC-MAIN-2017-09 | refinedweb | 418 | 66.03 |
I’m currently writing a test utility to simulate multiple clients hitting a server. There’s a simple UI that shows what’s going on, but the interesting and useful part are the client objects all running side-by-side without interfering with each other.
This is accomplished by running each client in its own application domain. When the user initiates a client action from the UI, remoting is used to communicate with the client object in the appropriate app domain.
Everything was working great, and I was pleased with my simulator. It’s certainly easier to run (and debug!) 10 simulators in a single test utility than having to fire up 10 separate instances of the utility app.
However, after a few minutes when I again initiated a client action from my UI, I got the following dreadful error:
After staring at this for a few seconds, I recalled reading the chapter on app domains in the book C# 3.0 in a Nutshell. The problem is that remoting objects are leased, and if a leasing interval is left unspecified, the .NET runtime drops the object after about 5 minutes.
One solution is to have your remoting object (i.e. the object that descends from MarshalByRefObject) override the InitializeLifetimeService method and return null. This tells the CLR to keep the object around for as long as the consumer needs it.
Here’s what the code looks like:
public class MyTestClient : MarshalByRefObject, IMyTestClient { public override object InitializeLifetimeService() { // Tell the runtime to keep the object around return null; }
// etc.
There are other ways to better control the object’s lease, but for my purposes this works great since the consumer of the remoting objects are in the default app domain and are alive for the duration of the utility.
I’m sure there are better discussions of this on MSDN and blogs, but if you encounter the above error, this is one way to solve it.
Hope this helps. | https://larryparkerdotnet.wordpress.com/2009/08/11/keeping-remoting-objects-alive/ | CC-MAIN-2018-39 | refinedweb | 328 | 62.07 |
Note: This was initially posted at. There’s been quite a bit of discussion recently about the use of hash-bang URIs following their adoption by Gawker, and the ensuing downtime of that site. Gawker have redesigned their sites, including lifehacker and various others, such that all URIs look like
http://{domain}#!{path-to-content} — the
#! is the hash-bang. The home page on the domain serves up a static HTML page that pulls in Javascript that interprets the
path-to-content and requests that content through AJAX, which it then slots into the page. The sites all suffered an outage when, for whatever reason, the Javascript couldn’t load: without working Javascript you couldn’t actually view any of the content on the site. This provoked a massive cry of #FAIL (or perhaps that should be #!FAIL) and a lot of puns along the lines of making a hash of a website and it going bang. For analysis and opinions on both sides, see: Breaking the Web with hash-bangs by Mike Davies Broken Links by Tim Bray Hash, Bang, Wallop by Ben Ward Hash-bang boom by Tom Gibara Thoughts on the Hashbang by Ben Cherry Nathan’s comments on www-tag While all this has been going on, the TAG at the W3C have been drafting a document on Repurposing the Hash Sign for the New Web (originally named Usage Patterns For Client-Side URI parameters in April 2009) which takes a rather wider view than just the hash-bang issue, and on which they are seeking comments. All matters of design involve weighing different choices against some criteria that you decide on implicitly or explicitly: there is no single right way of doing things on the web. Here, I explore the choices that are available to web developers around hash URIs and discuss how to mitigate the negative aspects of adopting the hash-bang pattern.
Background
The semantics of hash URIs have changed over time. Look back at RFC 1738: Uniform Resource Locators (URL) from December 1994 and fragments are hardly mentioned; when they are, they are termed “fragment/anchor identifiers”, reflecting their original use which was to jump to an anchor within an HTML page (indicated by an
` element with aname` attribute; those were the days). Skip to RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax from August 1998 and fragment identifiers have their own section, where it. At this point, the fragment identifier: is not part of the URI should be interpreted in different ways based on the mime type of the representation you get when you retrieve the URI is only meaningful when the URI is actually retrieved and you know the mime type of the representation Forward to RFC 3986: Uniform Resource Identifier (URI): Generic Syntax from January 2005 and fragment identifiers are defined as part of the URI itself: breaks away from the tight coupling between a fragment identifier and a representation retrieved from the web and purposefully allows the use of hash URIs to define abstract or real-world things, addressing TAG Issue 37: Definition of abstract components with namespace names and frag ids and supporting the use of hash URIs in the semantic web. Around the same time, we have the growth of AJAX, where a single page interface is used to access a wide set of content which is dynamically retrieved using Javascript. The AJAX experience could be frustrating for end users, because the back button no longer worked (to let them go back to previous states of their interface) and they couldn’t bookmark or share state. And so applications started to use hash URIs to track AJAX state (that article is from June 2005, if you’re following the timeline). And so we get to hash-bangs. These were proposed by Google in October 2009 as a mechanism to distinguish between cases where hash URIs are being used as anchor identifiers, to describe views, or to identify real-world things, and those cases where they are being used to capture important AJAX state. What Google proposed is for pages where the content of the page is determined by a fragment identifier and some Javascript to also* be accessible by combining the base URI with a query parameter (
_escaped_fragment_={fragment}). To distinguish this use of hash URIs from the more mundane kinds, Google proposed starting the fragment identifier
#!(hash-bang). Hash-bang URIs are therefore associated with the practice of transcluding content into a wrapper page. To summarise, hash URIs are now being used in three distinct ways: 1. to identify parts of a retrieved document 2. to identify an abstract or real-world thing (that the document says something about) 3. to capture the state of client-side web applications Hash-bang URIs are a particular form of the third of these. By using them, the website indicates that the page uses client-side transclusion to give the true content of the page. If it follows Google’s proposal, the website also commits to making that content available through an equivalent base URI with a
_escaped_fragment_parameter.
Hash-bang URIs in practice
Let’s have a look at how hash-bang URIs are used in a couple of sites.
Lifehacker
First, we’ll look at lifehacker, which is one of Gawker’s sites whose switch to hash-bangs triggered the recent spate of comments. What happens if I link to the article? The exact response to this request seems to depend on some cookies (it didn’t work the first time I accessed it in Firefox, having pasted the link from another browser). If it works as expected, in a browser that supports Javascript, the browser gets the page at the base URI, which includes (amongst a lot of other things) a script that
POSTs to a request with the data: op=ajax_post refId=5770791 formToken=d26bd943151005152e6e0991764e6c09 The response to this
POST is a 53kB JSON document that contains a bit of metadata about the post and then its escaped HTML content. This gets inserted into the page by the script, to display the post. As this isn’t a
GETtable resource, I’ve attached this file to this post so you can see what it looks like. (Honestly, I could hardly bring myself to describe this: a
POST to get some data? a
.php URL? query parameter set to
ajax_post? massive amounts of escaped HTML in a JSON response? Geesh. Anyway, focus… hash-bang URIs…) A browser that doesn’t support Javascript simply gets the base URI and is none the wiser about the actual content that was linked to. What about the
_escaped_fragment_ equivalent URI,? If you request this, you get back an
200 OK response which is an HTML page with the content embedded in it. It looks just the same as the original page with the embedded content. What if you make up some rubbish URI, which in normal circumstances you would expect to give a
404 Not Found response? Naturally, a request to the base URI of is always going to give a
200 OK response, although if you try you get page furniture with no content in the page. A request to results in a
301 Moved Peramently to the hash-bang URI rather than the
404 Not Found that we’d want.
Now let’s look at Twitter. What happens if I link to the tweet? Although it’s not indicated in the
Vary header, Twitter determines what to do about any requests to this hashless URI based on whether I’m logged in or not (based on a cookie). If I am logged on, I get the new home page. This home page
GETs (through various iframes and Javascript obfuscation) several small JSON files through Twitter’s API:: the details of the tweet: details about retweets *: details about the twitter user @unhosted, who was mentioned in the tweet This JSON gets converted into HTML and embedded within the page using Javascript. All the links within the page are to hash-bang URIs and there is no way of identifying the hashless URI (unless you know the very simple pattern that you can simply remove it to get a static page). If I’m not logged on but am using a browser that understands Javascript, the browser GETs; the script in the returned page picks out the fragment identifier and redirects (using Javascript) to. If, on the other hand, I’m using curl or a browser without Javascript activated, I just get the home page and have no idea that the original hash-bang URI was supposed to give me anything different. The response to the hashless URI also varies based on whether I’m logged in or not. If I am, the response is a
302 Found to the hash-bang URI. If I’m not, for example using curl, Twitter just returns a normal HTML page that contains information about the tweet that I’ve just requested. Finally, if I request the
_escaped_fragment_ version of the hash-bang URI the result is a
301 Moved Permanently redirection to the hashless URI which can be retrieved as above. Requesting a status that doesn’t exist such as in the browser results in a page that at least tells you the content doesn’t exist. Requesting the equivalent
_escaped_fragment_ URI redirects to the hashless URI. Requesting this results in a
404 Not Found result as you would expect.
Advantages of Hash URIs
Why are these sites using hash-bang URIs? Well, hash URIs in general have four features which make them useful to client-side applications: they provide addresses for application states; they give caching (and therefore performance) boosts; they enable web applications to draw data from separate servers; and they may have SEO benefits.
Addressing
Interacting with the web is all about moving from one state to another, through clicking on links, submitting forms, and otherwise taking action on a page. Backend databases on web servers, cookies, and other forms of local storage provide methods of capturing application state, but on the web we’ve found that having addresses for states is essential for a whole bunch of things that we find useful: being able to use the back button to return to previous states being able to bookmark states that we want to return to in the future being able to share states with other people by linking to them On the web, the only addressing method that meets these goals is the URI. Addresses that involve more than a URI, such as “search with the keyword X and click on the third link” or “access with cookie X set to Y” or “access with the HTTP header X set to Y” simply don’t work. You can’t bookmark them or link to them or put them on the side of a bus. Application state is complex and multi-faceted. As a web developer, you have to work out which parts of the application state need to be addressable through URIs, which can be stored on the client and which on a server. They can be classified into four rough categories; states that are associated with: 1. having particular content in the page, such as having a particular thread open in a webmail application 2. viewing a particular part of the content, such as a particular message within a thread that is being shown in the page 3. having a particular view of the content, such as which folders in a navigational folder list are collapsed or expanded 4. a user-interface feature, such as whether a drop-down menu is open or closed States that have different content almost certainly need to have different URIs so that it’s possible to link to that content (the web being nothing without links). At the other extreme, it’s very unlikely that the state of a drop-down menu would need to be captured at all. In between is a large grey area, where a web developer might decide not to capture state at all, to capture it in the client, in the server, or to make it addressable by giving it a URI. If a web developer chooses to make a state addressable through a URI, they again have choices to make about which part of the URI to use: should different states have different domains? different paths? different query parameters? different fragment identifiers? Hash URIs make states addressable that developers might otherwise leave unaddressable. To give some examples, on legislation.gov.uk we have decided to: use the path to indicate a particular piece of content (eg which section of an item of legislation you want to look at), for example
/ukpga/1985/67/section/6 use query parameters for particular views on that content (eg whether you want to see the timeline associated with the section or not), for example
/ukpga/1985/67/section/6?view=timeline&timeline=true use fragment identifiers to jump to subsections, for example
/ukpga/1985/67/section/6#section-6-2 * also use fragment identifiers for enhanced views (eg when viewing a section after a text search)
/ukpga/1985/67/section/6#text%3Dschool%20bus The last of these states would probably have gone un-addressed if we couldn’t use a hash URI for it. The only changes that it makes to the normal page are currently to the links to other legislation content, so that you can go (back) to a highlighted table of contents (though we hope to expand it to provide in-section highlighting). Given that we rely heavily on caching to provide the performance that we want and that there’s an infinite variety of free-text search terms, it’s simply not worth the performance cost of having a separate base URI for those views.
Caching and Parallelisation
Fragment identifiers are currently the only part of a URI that can be changed without causing a browser to refresh the page (though see the note below). Moving to a different base URI — changing its domain, path or query — means making a new request on the server. Having a new request for a small change in state makes for greater load on the server and a worse user experience due both to the latency inherent in making new requests and the large amount of repeated material that has to be sent across the wire.
Note: HTML5 introduces
pushState()and
changeState()methods in its history API that enable a script to add new URIs to the browser’s history without the browser actually navigating to that page. This is new functionality, at time of writing only supported in Chrome, Safari and Firefox (and not completely in any of them) and unlikely to be included in IE9. When this functionality is more widely adopted, it will be possible to change state to a new base URI without causing a page load. When a change of state involves simply viewing a different part of existing content, or viewing it in a different way, a hash URI is often a reasonable solution. It supports addressability without requiring an extra request. Things become fuzzier when the same base URI is used to support different content, where transclusion is used. In these cases, the page that you get when you request the base URI itself gets content from the server as one or more separate AJAX requests based on the fragment identifier. Whether this ends up giving better performance depends on a variety of factors, such as: How large are the static portions of the page (served directly) compared to the dynamic parts (served using AJAX)? If the majority of the content is static as a user moves through the site, you’re going to benefit from only loading the dynamic parts as state changes. Can different portions of the page be requested in parallel? These days, making many small requests may lead to better performance than one large one. * Can the different portions of the page be cached locally or in a CDN? You can make best use of caches if the rapidly changing parts of a page are requested separately from the slowly changing parts.
Distributed Applications
Hash URIs can also be very useful in distributed web applications, where the code that is used to provide an interface pulls in data from a separate, unconnected source. Simple examples are mashups that use data provided by different sources, requested using AJAX, and combine that data to create a new visualisation. But more advanced applications are beginning to emerge, particularly as a reaction to silo sites such as Google and Facebook, which lock us in to their applications by controlling our data. From the unhosted manifesto:
To be unhosted, a website’s code will need to be very ajaxy first, so that all the servers do is store and serve json data. No server-side processing. This is because we need to switch from transport-layer encryption to client-side payload encryption (we no longer necessarily trust the server we’re talking to). From within the app’s source code, that should run entirely in JavaScript and HTML5, json-objects can be stored, retrieved, sent, and received. The user will have the same experience (we even managed to avoid needing a plugin), but the website is unhosted in the sense that the servers you talk to only see encrypted data and don’t even know which application you are running. The aim of unhosted is to separate application code from user data. This divides servers (at least functionally) into those that store and make available user data, and those that host applications and any supporting code, images and so on. The important feature of these sites is that user data never passes through the web application’s server. This frees users to move to different applications without losing their data. This doesn’t necessarily stop the application server from doing any processing, including URI-based processing; it is only that the processing cannot be based on user data — the content of the site. Since this content is going to be accessed through AJAX anyway, there’s little motivation for unhosted applications to use anything other than local storage and hash URIs to encode state.
SEO
A final reason for using hash URIs that I’ve seen cited is that it increases the page rank for the base URI, because as far as a search engine is concerned, more links will point to the same base URI (even if in fact they are pointing to a different hash URI). Of course this doesn’t apply to hash-bang URIs, since the point of them is precisely to enable search engines to distinguish between (and access content from) URIs whose base URI is the same.
Disadvantages of Hash URIs
So hash-bangs can give a performance improvement (and hence a usability improvement), and enable us to build new kinds of web applications. So what are the arguments against using them?
Restricted Access
The main disadvantages of using hash URIs generally to support AJAX state arise due to them having to be interpreted by Javascript. This immediately causes problems for: users who have chosen to turn off Javascript because: they have bandwidth limitations they have security concerns they want a calmer browser experience clients that don’t support Javascript at all such as: search engines screen scrapers clients that have buggy Javascript implementations that you might not have accounted for such as: older browsers some mobile clients The most recent statistic I could find, about access to the Yahoo home page indicates that up to 2% of access is from users without Javascript (they excluded search engines). According to a recent survey, about the same percentage of screen reader users have Javascript turned off. This is a low percentage, but if you have large numbers of visitors it adds up. The site that I care most about, legislation.gov.uk, has over 60,000 human visitors a day, which means that about 1,200 of them will be visiting without Javascript. If our content were completely inaccessible to them we’d be inconveniencing a large number of users.
Brittleness
Depending on hash-bang URIs to serve content is also brittle, as Gawker found. If the Javascript that interprets the fragment identifier is temporarily inaccessible or unable to run in a particular browser, any portions of a page that rely on Javascript also become inaccessible.
Replacing HTTP
There are other, less obvious, impacts which occur when you use a hash-bang URI. The URI held in the HTTP Referer header “MUST NOT include a fragment”. As Mike Davies noted, this prevents such URIs from showing up in server logs, and stops people from working out which of your pages are linking to theirs. (Of course, this might be a good thing in some circumstances; there might be aspects of the state of a page that you’d rather a referenced server not know about.) You should also consider the impact on the future proofing of your site. When a server knows the entirety of a URI, it can use HTTP mechanisms to indicate when pages have moved, gone, or never existed. With hash URIs, if you change the URIs you use on your site, the Javascript that interprets the fragment identifier needs to be able to recognise and support any redirections, missing, or never existing pages. The HTTP status code for the wrapper page will always be
200 OK, but be meaningless. Even if your site structure doesn’t change, if you use hash-bang URIs as your primary set of URIs, you’re likely to find it harder to make a change back to using hashless URIs in the future. Again, you will be reliant in perpetuity on Javascript routing to decipher the hash-bang URI and redirect it to a hashless URI.
Lack of Differentiation
A final factor is that fragment identifiers can become overcrowded with state information. In a purely hash-URI-based site, what if you wanted to jump to a particular place within particular content, shown with a particular view? The hash URI has to encode all three of these pieces of information. Once you start using hash-bang URIs, there is no way to indicate within the URI (for search engines, for example) that a particular piece of the URI can be ignored when checking for equivalence. With normal hash URIs, there is an assumption that the fragment identifier can basically be ignored; with hash-bang URIs that is no longer true.
Good Practice
Having looked at the advantages and disadvantages, I would echo what seems to be the general sentiment around traditional server-based websites that use hash-bang URIs: pages that give different content should have different base URIs, not just different fragment identifiers. In particular, if you’re serving large amounts of document-oriented content through hash-bang URIs, consider swapping things around and having hashless URIs for the content that then transclude in the large headers, footers and side bars that form the static part of your site. However, if you are running a server-based, data-driven web application and your primary goal is a smooth user experience, it’s understandable why you might want to offer hash URIs for your pages to the 98% of people who can benefit from it, even for transcluded content. In these cases I’d argue that you should practice progressive enhancement: 1. support hashless URIs which do not simply redirect to a hash URI, and design your site around those 2. use hash-bang URIs as suggested by Google rather than simple hash URIs 3. provide an easy way to get the sharable, hashless URI for a particular page when it is accessed with a hash-bang URI 4. use hashless URIs within links; these can be overridden with onclick listeners for those people with Javascript; using the hashless URI ensures that ‘Copy Link Location’ will give a sharable URI 5. use the HTML5 history API where you can to add or replace the relevant hashless URI in the browser history as state changes 6. ensure that only those visitors that both have Javascript enabled and do not have support for HTML5’s history API have access to the hash-bang URIs by using Javascript to, for example: redirect to a hash-bang URI rewrite URIs within pages to hash-bang URIs * attach onclick URIs to links 7. support the
_escaped_fragment_ query parameter, the result of which should be a redirection to the appropriate hashless URI This is roughly what Twitter has done, except that it doesn’t make it easy to get the hashless URI from a page or from links within the page. Of course the mapping in Twitter’s case is the straight-forward removal of the
#! from the URI, but as a human it’s frustrating to have to do this by hand. The above measures ensure that your site will remain as accessible as possible to all users and provides a clear migration path as the HTML5 history API gains acceptance. The slight disadvantage is that encouraging people to use hashless URIs for links means that you you can no longer depend quite so much on caching as the first page that people access in a session might be any page (whereas with a pure hash-bang scheme everyone goes to the same initial page). Distributed, client-based websites can take the same measures — the application’s server can send back the same HTML page regardless of the URI used to access it; Javascript can pull information from a URI’s path as easily as it can from a fragment identifier. The biggest difficulty is supporting the static page through the
_escaped_fragment_ convention without passing user data through the application server. I suspect we might find a third class of service arise: trusted third-party proxies using headless browsers to construct static versions of pages without storing either data or application logic. Time will tell.
The Deeper Questions
There are some deeper issues here regarding web architecture. In the traditional web, there is a one-to-one correspondence between the representation of a resource that you get in response to a request from a server, and the content that you see on the page (or a search engine retrieves). With a traditional hash URI for a fragment, the HTTP headers you retrieve for the page are applicable to the hash URI as well. In a web application that uses transclusion, this is not the case.
Note: It’s also impossible to get metadata about hash URIs used for real-world or abstract things using HTTP; in these cases, the metadata about the thing can only be retrieved through interpreting the data within the page (eg an RDF document). Whereas with the
303 See Otherpattern for publishing linked data, it’s possible to use a
404 Not Foundresponse to indicate a thing that does not exist, there is no equivalent with hash URIs. Perhaps this is what lies at the root of my feeling of unease about them. With hash-bang URIs, there are in fact three (or more) URIs in play: the hash-bang URI (which identifies a wrapper page with particular content transcluded within it), a base URI (which identifies the wrapper HTML page) and one or more content URIs (against which AJAX requests are made to retrieve the relevant content). Requests to the base URI and the content URIs provide us with HTTP status codes and headers that describe those particular representations. The only way of discovering similar metadata about the hash-bang URI itself is through the
_escaped_fragment_query parameter convention which maps the hash-bang URI into a hashless URI that can be requested. Does this matter? Do hash-bang URIs “break the web”? Well, to me, “breaking the web” is about breaking the implicit socio-technical contract that we enter into when we publish websites. At the social level, sites break the web when they withdraw support for URIs that are widely referenced elsewhere, hide content behind register- or pay-walls, or discriminate against those who suffer from disabilities or low bandwidth. At the technical level, it’s when sites lie in HTTP. It’s when they serve up pages with the title “Not Found” with the HTTP status code
200 OK. It’s when they serve non-well-formed HTML as
application/xhtml+xml. These things matter because we base our own behaviour on the contract being kept. If we cannot trust major websites to continue to support the URIs that they have coined, how can we link to them? If we cannot trust websites to provide accurate metadata about the content that they serve, how can we write applications that cache or display or otherwise use that information? On their own, pages that use Javascript-based transclusion break both the social side (in that they limit access to those with Javascript) and the technical side (in that they cannot properly use HTTP) of the contract. But contracts do get rewritten over time. The web is constantly evolving and we have to revise the contract as new behaviours and new technologies gain adoption. The
_escaped_fragment_convention gives a life line: a method of programmatically discovering how to access the version of a page without Javascript, and to discover metadata about it through HTTP. It is not a pretty pattern (I would much prefer that the server returned a header containing a URI template that described how to create the hashless equivalent of a hash-bang URI, and to have some rules about the parsing of a hash-bang fragment identifier so that it could include other fragments identifiers) but it has the benefit of adoption. In short, hash-bang URIs are an important pattern that will be around for several years because they offer many benefits compared to their alternatives, and because HTML5’s history API is still a little way off general support. Rather than banging the drum against hash-bang URIs, we need to try to make them work as well as they can by: berating sites that use plain hash URIs for transcluded content encouraging sites that use hash-bang URIs to follow some good practices such as those I outlined above * encouraging applications, such as browsers and search engines, to automatically map hash-bang URIs into the
_escaped_fragment_pattern when they do not have Javascript available We also need to keep a close eye on emerging patterns in distributed web applications to ensure that these efforts are supported in the standards on which the web is built.
I think it would be better if this was done in the HTML rather than scripts. For example…
foo
bar
Your browser does not support hashbangs.
Of course, this wouldn’t work for more complicated things. There’s probably a better way of doing it.
Another issue with hash uri’s is it breaks the refresh button. It’s frustrating to wonder why this page isn’t updating until you realize there’s a hash at the end of the uri
I’m a website hosting company [redacted] and I see people buying domain names with hash’s in the URL’s for just one purpose. To get good ranking and spam customers with there google ads or affiliate program. They are just filling google with junk websites. I would love to see them go away.
First of all, thanks for linking the Single Page Interface Manifesto
I like most of your article, it is one of the best articles in this subject, said this, I don’t agree with some of your “Disadvantages” of hash based URIs:
* Restricted Access aka “don’t work when JavaScript is disabled.
Take a look to this example, is a complex and real world web site, it is SPI and also works with JS disabled:
It uses a Java web framework which makes very easy “dual web sites” (SPI and page based in the same time), anyway some ideas can be ported to other frameworks.
* Brittleness
It was a Gawker JavaScript bug, we’re accustomed to see half-working web sites with tons of JS bugs, yes in a SPI centric world we must be more careful because it can fully break your site, it was just a bug, when the bug is fixed end of the problem.
* Replacing HTTP
No, you’re not replacing HTTP, you’re just leveraging the web to something beyond a “linked collection of scientific documents”, the web is being used these days for things very different to the original purpose of web as it was born in CERN.
Currently, for me, is so familiar as
I just need to fix bookmarking when JS is disabled, to fix this problem I need the hash sent to the server to return the right initial content, when I get this “minor” problem fixed we can achieve the SPI utopia. | http://www.w3.org/blog/TAG/2011/05/12/hash_uris/ | CC-MAIN-2015-40 | refinedweb | 5,509 | 53.44 |
CodePlexProject Hosting for Open Source Software
Hi,
I am unable to attach the debugger to a running python 3.2 process. When I do the same with python 2.6 I can attach ok.
My setup:
- Run a script sitting in a sleep loop printing a message ( python 3.2.2150.1013 )
- PVTS 1.1.50508
- Attach to running process python.exe
- Script window shows:
Fatal Python error: take_gil: NULL tstate
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
- A popup then appears:
A debugger is attached to python.exe but not configured to debug this unhandled exception. To debug this exception, detach the current debugger.
Failed to attach debugger: timeout while attaching
Any suggestions?
Martin
btw Thanks for PVTS I think it is a great addition to VS2010!
I managed to find a workaround by removing the call to PyEval_InitThreads() in PyDebugAttachx86.dll (~ln900). The target needs to be running Python code for a successful attach. I have posted this in case there are others who wish to debug with
3.2.....
// if (!threadsInited()) {
// if(*curPythonThread == nullptr) {
// // no threads are currently running, it is safe to initialize multi threading.
// initThreads();
// releaseLock();
// }else if(!addedPendingCall) {
// someone holds the GIL but no one is actively adding any pending calls. We can pend our call
// and initialize threads.
addPendingCall(&AttachCallback, initThreads);
addedPendingCall = true;
}
}
I found a very simple workaround. If multi-threading has been initialized on the main thread then the attach works fine. This can be achieved by starting a dummy thread that starts and ends straight away...
from threading import Thread
Thread(target=str).start()
Thanks for the report and the proposed fix... I haven't had a chance to look at it yet, but will soon. I'm going to go ahead and open a bug based upon this so it doesn't get lost.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://pytools.codeplex.com/discussions/396011 | CC-MAIN-2017-34 | refinedweb | 357 | 77.43 |
I have killed many, many hours now trying to make icons appear for Tabbed Pages on iOS. According to all of the forum and blog posts I've seen this is supposed to be super simple.
In fact my page is exactly this simple:
public class MainPage : TabbedPage { public MainPage () { Page page = new Page { Title = "Title", Icon = "clock.png" }; this.Children.Add (page); } }
The tab shows up, the "title" shows up, the icon never does.
The PNG is in the Resources folder of the iOS project and the build action is set to BundleResource.
I've tried:
There is either some secret sauce to this or a bug ... would appreciate any suggestions.
Thanks,
Michael
Yeah, we had problems with this too. I ended up making a custom renderer for this.
This also solved the problem of specifying a selected image for the tabs in the case where simple tinting didn't suffice.
Thank you so much Geoff, your code fixed the issue for me straight away. I really appreciate it.
No problem! We're all in this together.
How about the Toolbar item? Is it the same as TabbedRenderer?
I am new to xamarin and I have been stuck on this similar issue for a long time. I have given coloured PNG images has icons for a button but in my android app it shows as an icon with white color only. The layout of the button is there but no color, only white. How to fix this in android..? | https://forums.xamarin.com/discussion/32406/tabbedpage-icons | CC-MAIN-2021-21 | refinedweb | 250 | 83.86 |
Original vs Existing value on DatagridCode Girl Jun 20, 2012 12:01 PM
I have a datagrid which in some columns I have itemeditors with combo boxes and datefields and other columns I just have an editable datafield. But since the fields are bound to an instance of a value object when someone changes the value, it is changed in the instance as well. Is there a property that keeps track of the original value before the value was modified? Is there a modified property to tell me if a value has changed. Or do I need to create some kind of focus function to save values in variables? What is the thinking for flex?
1. Re: Original vs Existing value on Datagriddrkstr_1 Jun 20, 2012 3:26 PM (in response to Code Girl)1 person found this helpful
I usually handle this in the underlying data model class. There are also the DataGrid itemEditBegin, itemEditBeginning, and itemEditEnd events.
2. Re: Original vs Existing value on DatagridCode Girl Jun 21, 2012 12:21 PM (in response to drkstr_1)
the underlying array is automatically changed as soon as it is changed in the datagrid since the data is bound. On the Item edit, is this row based or an individual column for a row? I have seen three other options but seemed kinda dirty. The change event for the datagrid. But this only fires when someone changes rows. It does not fire on initial load or if someone removes an item and the next item is selected. I forget what the other two were but one of them was used with AS2. Will look into the Collection events you just meantioned.
3. Re: Original vs Existing value on DatagridCode Girl Jun 21, 2012 12:24 PM (in response to drkstr_1)
found an article about itemeditbegin and exactly what I was trying to accomplish
4. Re: Original vs Existing value on DatagridCode Girl Jun 21, 2012 12:41 PM (in response to Code Girl)
According to the article, Flex does not have a built in way of determining a previous value. Too bad. Hopefully there are no draw backs to the method suggested in the article.
5. Re: Original vs Existing value on DatagridCode Girl Jun 21, 2012 1:27 PM (in response to Code Girl)
Bummer, this did not fix my issue. The above suggestion only works if only one column is being addressed. but in my case, Each row contains a value based upon a category. So, if the category changes then you need to change the value from the old category and add to the new. If the value changes then you subtract the old and add the new. If both changes then you remove the old value out of the old category and then add the new value to the new category. So, this solution does not work. The bummer part is now the Adobe employees will ignore this issue because there are posts to it. I guess I will have to start a new discussion.
6. Re: Original vs Existing value on DatagridCode Girl Jun 21, 2012 1:51 PM (in response to Code Girl)
My Bad.
since my tmpObject was not a value object, I forgot to instantiate the object and that is why it didnt work. So the solution above does solve my problem. Though not as clean as I would like but clean enough.
7. Re: Original vs Existing value on Datagriddrkstr_1 Jun 21, 2012 2:00 PM (in response to Code Girl)
IMHO, the clean solution would be to handle this in the data model (your value object class).
Something along these lines:
public class MyModel
{
private var _dataChanged:Boolean;
public function get dataChanged():Boolean
{
return _dataChanged;
}
private var _someProperty:String;
public function get someProperty():String
{
return _someProperty;
}
public function set someProperty(value:String):void
{
if(_someProperty == value)
return;
_someProperty = value;
_dataChanged = true;
//and maybe dispatch some event, or hook up binding, etc.
}
}
This would allow you to perform logic when the values are edited (like storing the old values for a roll back).
8. Re: Original vs Existing value on Datagridtinylion_uk Jun 21, 2012 2:04 PM (in response to drkstr_1)
That’s exactly what I do
9. Re: Original vs Existing value on DatagridCode Girl Jun 21, 2012 2:32 PM (in response to tinylion_uk)
One day, I need to learn this aspect of Flash builder. But, I am currently using a web service Java Bean and flash builder is building my value objects for me through the wsdl. So, if I were to modify the class and import when I make a change to the web service then my changes would be lost. But thanks for the suggestion.
10. Re: Original vs Existing value on Datagriddrkstr_1 Jun 21, 2012 3:20 PM (in response to Code Girl)
The auto generated classes are set up so you can extend them into full blown "models" (a value object with business logic). Only the base classes will be replaced when they are generated.
11. Re: Original vs Existing value on DatagridCode Girl Jun 25, 2012 12:22 PM (in response to drkstr_1)
Sounds like something I need to learn. Would you have any examples?
12. Re: Original vs Existing value on Datagriddrkstr_1 Jun 26, 2012 2:47 PM (in response to Code Girl)1 person found this helpful
I dug this out of an old project. Both BoardModel and _Super_BoardModel (not shown) were generated by the Flex data service wizard. I added changes to the BoardModel class after it was generated to give it a bit of business logic. If I were to change the model and regenerate the classes, only _Super_BoardModel will be replaced, while my edits to BoardModel would stay intact.
Keep in mind of course, that if you make changes to the model that affect a property you are extending, you will need to make the update manually in your extended class as well.
public class BoardModel extends _Super_BoardModel { /** * DO NOT MODIFY THIS STATIC INITIALIZER - IT IS NECESSARY * FOR PROPERLY SETTING UP THE REMOTE CLASS ALIAS FOR THIS CLASS * **/ /** * Calling this static function will initialize RemoteClass aliases * for this value object as well as all of the value objects corresponding * to entities associated to this value object's entity. */ public static function _initRemoteClassAlias():void { _Super_BoardModel.model_internal::initRemoteClassAliasSingle(com. t8.models.BoardModel); _Super_BoardModel.model_internal::initRemoteClassAliasAllRelated(); } model_internal static function initRemoteClassAliasSingleChild():void { _Super_BoardModel.model_internal::initRemoteClassAliasSingle(com. t8.models.BoardModel); } { _Super_BoardModel.model_internal::initRemoteClassAliasSingle(com. t8.models.BoardModel); } //---------------------------------------------------------- // // // Class Properties // // //---------------------------------------------------------- //-------------------------------------- // Public Properties //-------------------------------------- override public function set isTwin(value:Boolean):void { super.isTwin = value; //if this is a twin, make sure tail length matches running length if(value && this.tailLength != this.noseLength) { this.tailLength = this.noseLength; } } /** * END OF DO NOT MODIFY SECTION * **/ //////////////////////////////////////////// //////////////////////////////////////////// //// //// --== Public Vars ==-- //// //////////////////////////////////////////// //////////////////////////////////////////// override public function set length(value:int):void { super.length = value; updateRunningLength(); } public function get noseBottom():Point { return new Point(this.noseBottomX, this.noseBottomY); } override public function set noseLength(value:int):void { super.noseLength = value; if(this.isTwin) { super.tailLength = value; } updateRunningLength(); } public function get noseTop():Point { return new Point(this.noseTopX, this.noseTopY); } public function get tailBottom():Point { return new Point(this.tailBottomX, this.tailBottomY); } override public function set tailLength(value:int):void { super.tailLength = value; //tail cannot be longer then nose if(this.isTwin || value > this.noseLength) { super.noseLength = value; } updateRunningLength(); } public function get tailTop():Point { return new Point(this.tailTopX, this.tailTopY); } //////////////////////////////////////////// //////////////////////////////////////////// //// //// --== Internal Methods ==-- //// //////////////////////////////////////////// //////////////////////////////////////////// protected function updateRunningLength():void { this.runningLength = this.length - this.noseLength - this.tailLength; } }
13. Re: Original vs Existing value on DatagridCode Girl Jun 28, 2012 11:43 AM (in response to drkstr_1)
Duh. about as obvious as it gets. Funny how when I think Flash, Java seems to fade away. hehehehhe Thank You. | https://forums.adobe.com/thread/1026659 | CC-MAIN-2017-51 | refinedweb | 1,287 | 53.92 |
Everything you want to know about Visual Studio ALM and Farming
Brian Harry is a Microsoft Technical Fellow working as the Product Unit Manager for Team Foundation Server. Learn more about Brian.
More videos »
I just got back from TechEd. I had a great time and met some terrific people. This is the first TechEd where the conference has been split across 2 weeks - the first for developers, the second for IT.
This TechEd has a first for me. I got to do one of the big demos in big keynote with Bill - his last big keynote as full time chairman at Microsoft. One of the things I learned in this exercise is the amount of work that goes into putting this together. The work on the demo, the rehearsals, getting everyone to agree on the talking points, all of the back stage logistics. I'd estimate I spent days preparing for my little 7 minute appearance. It was fun though :)
In my mind (admittedly biased), the demo was terrific. That's not to say my delivery was particularly amazing but rather the demo itself was very good and the technologies we were showing are just amazing. The demo I did basically highlighted two things - the new direction we are headed in architecture tools and modeling and the work we are doing on DBPro extensibility along with the extension IBM is building that enables Visual Studio Team System for Database Professionals to give you the same great experience against a DB2 database that you can get against a SQL server database.
The architecture tools we are building are so unbelievably exciting to me that I can't stand it. I'm wishing I'd have had these tools years ago. I can tell you for certain that we could have shaved months off of the development of TFS over the past few years if we had had them.
The thing that has me the most excited is a new feature called a layer diagram. This layer diagram allows you to design the logical layering of your application and specify the dependencies you intend to have. For example, you wouldn't want your client to have a dependency on you data layer in a 3 tier app. You wouldn't want your server business logic taking a dependency on something in the Windows.Forms assembly, etc.
Once you have this logical layering, you can associate the layers with specific assemblies, namespaces or classes in your actual application. Now, the magic happens. VSTS can parse/reverse engineer your code to determine the "actual" dependencies in your application. Having done this, it can compare the actual to the "desired" as specified in the layer diagram and let you know about any problems you have. Going even further, you can configure a checkin policy to validate this on every single checkin. This way you can prevent people from checking in spaghetti architecture in the first place.
It's very hard to communicate an architecture to everyone on the team. It's even harder to prevent them from accidentally violating the architecture. These tools are a huge leap forward in ensuring that you end up with the architecture you designed.
On top of this cool new layer diagram and validation is another feature called the "Architecture Explorer". It is a very handy tool for visualizing the architecture your code implements today. It allows you to graphically browse through your application and its dependencies and understand them. As you update your code, you can see the Architecture Explorer diagrams change.
All of this (and more) represent a pretty big shift in our approach to the VSTS Architecture SKU towards tools that are applicable to a broader set of problem domains and compelling to a larger constituency of users. It catapults the architecture SKU from a moderately interesting overall value to one the the most exciting things in Team System. I can't wait for Rosario to become "go-live dogfoodable" so that we can use this new stuff in our daily jobs.
Brian | http://blogs.msdn.com/b/bharry/archive/2008/06/05/teched-2008-keynote.aspx | CC-MAIN-2015-32 | refinedweb | 677 | 61.77 |
image
##Overview
A Dart library to encode and decode various image formats.
The library has no reliance on
dart:io, so it can be used for both server and
web applications. The image library currently supports the following
formats:
- PNG
- JPG
- TGA
Decoding Only (for now): - WebP
##Samples
Load a WebP image, resize it, and save it as a png:
import 'dart:io' as Io; import 'package:image/image.dart'; void main() { // Read a jpeg image from file. Image image = readWebP(new Io.File('test.webp').readAsBytesSync()); // Resize the image to a 120x? thumbnail (maintaining the aspect ratio). Image thumbnail = copyResize(image, 120); // Save the thumbnail as a PNG. new Io.File('thumbnail.png') ..writeAsBytesSync(writePng(thumbnail)); } | https://www.dartdocs.org/documentation/image/1.1.6/index.html | CC-MAIN-2017-30 | refinedweb | 117 | 58.69 |
Standard Answers
As of December 2011, this topic has been archived. As a result, it is no longer actively maintained. For more information, see Archived Content. For information, recommendations, and guidance regarding the current version of Internet Explorer, see Internet Explorer Developer Center.
By Jay Allen, Mark Davis, Heidi Housten, and Tosh Meston
Microsoft Corporation
October 4, 2002
There are so many standards and developments to keep up with and it's our job to keep you informed of them when it comes to Web development. This month a reader asks about MathML. Did you even know it existed? If you did, then maybe you'd like to join our crack team of savvy writers!
We have a heap of different questions so there is bound to be at least one, and hopefully more, that gives you something interesting to think about in your next project. Don't forget to peek in the archives.
Contents
Formulaic Answers—MathML and Internet Explorer
Giving Your Name and Other Properties—Excel: filenames and properties
Formulaic Answers
Dear Web Team:
I would like to know to what degree does Internet Explorer support MathML?
Thanks,
Albert Mungin
The Web Team replies:
We're glad you asked about this topic, Albert. Like so many people at Microsoft and in our industry at large, the Web Team members were at one time or another big-time math geeks, so a marriage between Math and XML is an exciting and interesting topic certainly worthy of a few paragraphs.
MathML or Mathematical Markup Language is an effort to describe mathematical expression using XML syntax. The goals of MathML are to separate the math content from its presentation and to describe the mathematical expression such that math software tools can evaluate the expression and perform computations on it.
Describing mathematics on computing systems is as old as computing systems themselves. It was natural at first to use a linear format to describe a math expression, such as (a^2 + b^2 = c^2). Soon however, people started inventing ways to typeset these formulas so they could be displayed or printed in a more familiar format. One such system was TeX, which became popular in academic circles and remains so today. Another was SGML standard ISO 12083. While these languages were excellent at presenting math expression, there was a need to mathematically describe an expression such that it could be parsed and evaluated. Certain mathematical software packages like Wolfram Research's Mathematica had been dealing with this problem for years and had developed a system for expressing math so that the expression was typeset and also computable. With the explosion in popularity of the Web and XML in the 90s, it was proposed that the XML standard be used to describe math so that browsers could display math expressions and the data could be interchanged with math software products for evaluation. MathML was born.
The present standard is MathML 2.0, and has reached W3C recommendation status. MathML contains tags for presentation in browsers and content tags to unambiguously describe the meaning of the math expression.
While Internet Explorer does not natively display MathML content, there exist several third-party ActiveX® controls or DHTML Behaviors that specialize in the presentation of MathML. One such program is MathPlayer by Design Science Inc. Another is techexplorer from IBM. Another option for displaying MathML content in a Web browser is to include the MathML in an XHTML document and specify an accompanying XSLT stylesheet provided by the W3C, which transforms it into nicely formatted HTML.
Here are a few examples of formulas as they are represented in presentation and then as content in MathML.
First, here is the Pythagorean theorem represented linearly:
a^2 + b^2 = c^2
And in Presentation MathML, it looks like this:
<math xmlns=''> <msup> <mi>a</mi> <mn>2</mn> </msup> <mo>+</mo> <msup> <mi>b</mi> <mn>2</mn> </msup> <mo>=</mo> <msup> <mi>c</mi> <mn>2</mn> </msup> </math>
And in Content MathML, it looks like this:
<math xmlns=''> <apply> <eq/> <apply> <plus/> <apply> <power/> <ci>a</ci> <cn type='integer'>2</cn> </apply> <apply> <power/> <ci>b</ci> <cn type='integer'>2</cn> </apply> </apply> <apply> <power/> <ci>c</ci> <cn type='integer'>2</cn> </apply> </apply> </math>
Next, here is the equation representing gravitational force:
F = G*m1*m2 / r^2
In Presentation MathML, it is:
<math xmlns=''> <mi>F</mi> <mo>=</mo> <mfrac> <mrow> <mi>G</mi> <mo></mo> <mi>m1</mi> <mo></mo> <mi>m2</mi> </mrow> <msup> <mi>r</mi> <mn>2</mn> </msup> </mfrac> </math>
And in Content MathML, it is:
<math xmlns=''> <apply> <eq/> <ci>F</ci> <apply> <times/> <ci>G</ci> <ci>m1</ci> <ci>m2</ci> <apply> <power/> <apply> <power/> <ci>r</ci> <cn type='integer'>2</cn> </apply> <cn type='integer'>-1</cn> </apply> </apply> </apply> </math>
We have listed the Presentation and Content MathML separately, but they can be combined into a single
<math> node so that they can be copied and pasted from applications that require presentation MathML or those that need the content MathML.
Other efforts to describe elements of chemistry and music in XML are also being developed and information is available on the Web.
Giving Your Name and Other Properties
Dear Web Team:
We use Response.ContentType, Response.Write and Response.BinaryWrite frequently on our intranet pages to generate download files from database information. A good example is the contacts sheet that provides a link for the user to click that generates a vCard file containing the contact information for the user they are viewing.
The problem with this approach is that the .asp file (genvcf.asp) is the filename that is "presented" to the browser when downloading the file. Can we control the file name of the response object? (in the above example the Name of the contact would be a good choice...)
Phil Revill
The Web Team replies:
Since you didn't include a little sample for us to work with, we'll use a sample we've used before but with some new information we discovered. This example generates an Excel file in HTML. This makes much less work for the server because it means that there is no need to instantiate and automate Excel on the server. We won't explain much about the main code, just the bits that are new. If you want the basics, read Turning the Tables section in the July 2000 column. However, the answer to you question is to look at the content-disposition line.
The cool new stuff for this example is how to set the document properties for an Excel file when creating it with HTML—the ones you get when you choose properties under the file menu option. When you read the following sample, look for things like how we tell Excel how to display the date in the spreadsheet, what filename to use for the file, and how we specify the office document properties.
<%@ language=vbscript %> <% response.buffer = true response. <HTML xmlns: <HEAD> <TITLE>an Excel page</TITLE> <!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Subject>An experiment with HTML in Excel</o:Subject> <o:Author>auto-generated</o:Author> <o:Keywords>HTML</o:Keywords> <o:Description>Blah blah blah</o:Description> <o:Created><%= now %></o:Created> <o:Category>Experiments</o:Category> <o:Company>My Company</o:Company> </o:DocumentProperties> </XML><![endif]--> <STYLE> .xl25 { WHITE-SPACE: normal; mso-number-format: "mmm\ d,\ yyyy" } .head { BACKGROUND: #ccccff; COLOR: green} </STYLE> </HEAD> <BODY> <TABLE WIDTH=260> <TR><TD CLASS=head COLSPAN=5 ALIGN=center><B>Our Data</B></TD></TR> <TR><TD CLASS=xl25>5/10/2002</TD> <% for i = 1 to 4 response.write "<TD WIDTH=40>" response.write i + i response.write "</TD>" next %> <TR> <TD COLSPAN=4><B>total</B></TD> <TD><B>=sum(B2:E2)</B></TD> </TR> </TABLE> </BODY> </HTML> <% response.flush response.end %>
First of all, when it comes to properties, notice that we establish a namespace in the
<HTML> tag so that we can reference the office xml DTD. Also, notice that the title of the document is not stored with the other document properties. It is extracted straight from the html document title. Finally, we specify the date format by using a style sheet declaration. Look closely at style .xl25. If you want to know more about how to format information or what else you can do, experiment with saving an Excel file as html. There are a lot of extra tags that Excel uses so it can take a while to find what you are looking for. This is a great way to dynamically generate Excel files without trying to use the middle step of saving an Excel file on the hard disk, and because it's HTML and not a full Excel file, it makes life easier for any of your viewers who are still using modems.
Web Team in Short
Single Spacing in Editable DIVs
Q: Henry Lyons asks, "I am using content-editable DIVs on an HTML form, and when I hit the <Enter> key while inside the DIV, it automatically begins a new paragraph. If I hit Shift-<Enter> I get a single line break. How can I change the behavior so that when I hit <Enter> I get a single line break instead of a new paragraph?"
A: You can force single-spacing when you hit return in a content-editable element by seeding it with an inner DIV like so:
<DIV CONTENTEDITABLE="true" STYLE="border:1px solid"><DIV></DIV></DIV>
Smarten Up Those Tables
Q: Jeremy wants to know how MSDN got the HTML tables at the XML Web Services Developer Center( looking so good.
A: Those table look good enough to eat off, don't they? You could achieve this effect by using a graphic as the table background, but this is an inflexible solution and the user will be downloading more bits. Looking at the HTML, you can see that this effect was generated by specifying the Internet Explorer gradient effect on the table cell. This and other Internet Explorer multimedia filters and transitions are available as of Internet Explorer 4.0. The gradient effect is one of the available procedural surfaces, which are displayed behind the content of an HTML object. The gradient effect specifies the start and end color, as well as the gradient type (1=horizontal; 2=vertical). The following example uses both types of gradient to produce a diagonal gradient effect.
<HTML> <BODY> <TABLE STYLE="FILTER:PROGID:DXIMAGETRANSFORM.MICROSOFT.GRADIENT(GRADIENTTYPE=1, STARTCOLORSTR='#00B4CCE5', ENDCOLORSTR='#A0B4CCE5') PROGID:DXIMAGETRANSFORM.MICROSOFT.GRADIENT(GRADIENTTYPE=0, STARTCOLORSTR='#00B4CCE5', ENDCOLORSTR='#50B4CCE5' );"> > </TABLE> </BODY> </HTML>
Please see Visual Filters and Transitions Reference for more information.
Learn to Love Your Inner HTML
Q: Marcus is wondering why the
£ entity in his HTML is shown as a pound character when displaying the contents of the innerHTML property, as demonstrated by the following HTML:
<HTML> <BODY ONLOAD="alert('HTML: '+document.body.innerHTML);"> <B>£</B> </BODY> </HTML>
A: The Dynamic HTML innerHTML property provides a way of getting and setting the HTML content on a Web page. The value returned by innerHTML reflects the HTML stored by Internet Explorer and will exhibit some differences from the original HTML content. The difference that you've noticed is that all HTML character entities are resolved. An HTML character entity provides a way to represent a character that is outside of the ASCII range that HTML/HTTP supports. Internet Explorer resolves each entity and stores the character in memory, and this is what you get when you access the contents of innerHTML.
Why does Internet Explorer change the HTML content provided by the user? For one thing, HTML is a fairly loose definition that allows a Web author to omit certain end tags and not worry about case sensitivity. This is fine for the author, but once you begin to represent the HTML content as an object model, this needs to be an exact science. The following list includes some of the differences you will see in your innerHTML:
- Character entities are resolved
- Missing end tags (e.g. </LI>) are inserted
- Attribute order is different
- CSS attributes are converted to upper-case
Use the Source, Luke!
Q: Marcus is probably wondering how to get the actual HTML source for a Web page.
A: The easiest way to do this is to use the Internet Explorer download default behavior. The following example demonstrates how to use the download behavior to display the HTML for the current Web page. Once you have access to the original HTML, you can use a script and regular expression to parse the information you require. Please see the download behavior reference page for more information.
<HTML> <HEAD> <SCRIPT LANGUAGE="JScript"> function init() { download.startDownload(location.href,onDownloadDone); } function onDownloadDone(contents) { download.innerText = contents; } </SCRIPT> </HEAD> <BODY ONLOAD="init()"> <DIV ID="download" STYLE="behavior:url(#default#download)"></DIV> <B>£</B> </BODY> </HTML>
Home Is Where Your Assembly Is
Q: A reader wants to know how to install an assembly into the Global Assembly Cache (GAC) that was downloaded from the Internet in a Windows Forms application.
A: This functionality is part of the new Fusion installation and DLL management technology. The Fusion APIs are currently undocumented and have no officially supported managed wrappers. However, if you look in the FrameworkSDK directory of your Visual Studio .NET installation, and look in the subdirectory Samples\Technologies\Interop\Advanced\comreg, you'll find a file named fusioninstall.cs that provides Interop declarations for all of the key Fusion methods, including InstallAssembly(). You can download the assembly to your local drive using the DownloadFile() method of the System.Net.WebClient class.
Note that none of this will be possible from a .NET component running under Internet Explorer unless users grant your component permissions to access unmanaged assemblies.
Framing Your Events
Q: François complemented us on what we wrote about cross-frame events and also wants to know how to catch the onkeypress event from an IFRAME this way:
<SCRIPT> ifToto.document.onkeypress = getPressEvent; function getPressEvent() { // this code is executed when I press keys in the iframe, but // I can't get the event, keyCode, and so : iCode = window.event.keyCode; // generates the error : 'window.event' is null or is not an object } </SCRIPT> <IFRAME ID="ifToto"></IFRAME>
A: Know your object model. Know your object model. Know your object model! You are catching an event from your frame, but you are asking the current window object about its event object rather than the iframe's event object. Try changing the one line to:
iCode = ifToto.window.event.keyCode;
In Living Color
Q: Rajiv noticed our reference to the dialoghelper object in our last column, but wasn't sure how to use the color part of it.
A: It is a little confusing because the choosecolor dialog returns a decimal number and we are used to using hexadecimal numbers to specify colors in HTML pages. There is no need to change the return value from the dialog into a hexadecimal. When you set a property, you use the # to specify a hexadecimal value (#FF00CC). Usually, we use names when we don't use the #, but it turns out if you leave out the # and put in a decimal, it just works.
Here is a little sample:
<HTML> <HEAD> <TITLE>choose your color</TITLE> <SCRIPT> function callcolor() { var myresult; myresult = dlghelper.choosecolordlg() document.bgcolor = myresult } </SCRIPT> </HEAD> <BODY> <OBJECT ID=dlghelper </OBJECT> <BUTTON ONCLICK="callcolor()">use color dialog</BUTTON> </BODY> </HTML>.
Tosh Meston is a Web developer on the Outlook Web Access team. He comes to Microsoft with a background in physics and spends his free time reading and perfecting his three-point shot on the basketball court. | http://msdn.microsoft.com/en-us/library/bb250508(v=vs.85).aspx | CC-MAIN-2013-20 | refinedweb | 2,635 | 52.09 |
Randon address listsJobs
...private per item set on the calendar. 3. This would need to permissions by the event or person running it to allow different people to help in different areas. 4. This would need lists that people could sign up to for volunteering. 5. This would need and area to see who is following the person or event. 6. This would need an endorsement area to see the spreadsheet is including (company name, website, service and pricing)
I need a full list with no duplicates or subdomains. I only need the information from Moz .. ind for at se URL] or [log ind for at se URL]!
T...least 21 pics can be inserted and push down the section just above the footer. The sidebars should also be able to expand down The sidebars (left and right) should include lists (navigation) that can be sorted, but this (sorting) is not necessary for this phase. The text under the pics should be around 20 words that can be linked to other pages.
...achieve things. Examples of functional support provided: Confluence users have a need to create a reserved namespace in Confluence documents and create a report document that lists all documents that have mention of the reserved namespace string. Essentially: process descriptions are documented in Confluence. Their steps have listing of all roles who participate
...in many sprints, where the first release is expected to deliver a basic version with authentication against Active Directory (Azure B2C AD), four sections with basic object lists and their detail pages (OData APIs; data read-only), and profile page with some settings (OData APIs; data read-write). We have already developed the backend APIs that are
..
I want to receive promotional emails from a large list of 3rd party retailers. I have much more information on this in a spreadsheet on the first Sheet. The task should be completed in less than 6 hours. My total budget is $20 [log ind for at se URL]
The p...rates for each. Buyers must have a history of the contracted services and leave a qualification and rating (scale to be defined). Define discount categories from drop-down lists by agreements. The page should consider embedding section to charge sellers and that they pay an automated subscription (PayU, Paypal or anyone with charge to card)
Non-Landing / non-store / non-catalog / non-business / non-st...linking 2-step authorization 2 - [optional] Snapping in via social networks (FaceBook and others) 3 - Medium complexity of back-end functional 4 - Simple design 5 - Working with lists and online data sorting More while discussing One-time project Full transfer of the project to our hands else will bear the cost later. b...
I am a teacher in a College. We require a web application to display exam time tables, accept student registration and fees, deliver hall tickets or admit cards, generate lists of appearing students with photographs, upload and print question papers, process results
... - Contents production (writers). Please write what you have
We...calls or visit supplier physical store if needed and negotiate the prices. We need detailed supplier contact info including physical address, contact person, email, phone number, whatsapp number. Suppliers price lists including: wholesale and retail price for each item and variation. Minimum wholesale order quantity or order value. Shipping cost.
...language and other details ( country wise/ region wise). With Google font integration • Worldwide use, Mobile No. save with country code, • Creating and saving contact group lists. • Multimedia messaging. • Re-seller Add his campaign name with total history like date, timing, payment, matter. • Guaranteed delivery with delivery reports, & also display | https://www.dk.freelancer.com/work/randon-address-lists/ | CC-MAIN-2019-09 | refinedweb | 601 | 55.84 |
tornado.locks – Synchronization primitives¶
New in version 4.2.
Coordinate coroutines with synchronization primitives analogous to those the standard library provides to threads.
Warning
Note that these primitives are not actually thread-safe and cannot be used in place of those from the standard library)
I'll wait right here About to notify Done notifying I'm done waiting
waittakes an optional
timeoutargument, which is either an absolute timestamp:
io_loop = IOLoop.current() # Wait up to 1 second for a notification. yield condition.wait(timeout=io_loop.time() + 1)
…or a
datetime.timedeltafor a timeout relative to the current time:
# Wait up to 1 second. yield condition.wait(timeout=datetime.timedelta(seconds=1))
The method raises
tornado.gen.TimeoutErrorif there’s no notification before the deadline.
wait(timeout=None))
Waiting for event About to set the event Not waiting this time Done
set()[source]¶
Set the internal flag to
True. All waiters are awakened.
Calling
waitonce the flag is set will not block.
wait(timeout=None)[source]¶
Block until the internal flag is true.
Returns a Future, which raises
tornado.gen.TimeoutErrorafter a timeout.
Semaphore¶
- class
tornado.locks.
Semaphore(valueis a context manager, so
workercould)
Changed in version 4.3: Added
async withsupport in Python 3.5.
acquire(timeout=None)[source]¶
Decrement the counter. Returns a Future.
Block if the counter is zero and wait for a
release. The Future raises
TimeoutErrorafter the deadline.
BoundedSemaphore¶
- class
tornado.locks.
BoundedSemaphore(value.
acquire(timeout=None)¶
Decrement the counter. Returns a Future.
Block if the counter is zero and wait for a
release. The Future raises
TimeoutErrorafter the deadline.
Lock¶
- class
tornado.locks.
Lock[source]¶
A lock for coroutines.
A Lock begins unlocked, and
acquirelocks it immediately. While it is locked, a coroutine that yields
acquirewaits until another coroutine calls
release.
Releasing an unlocked lock raises
RuntimeError.
acquiresupports the context manager protocol in all Python versions:
>>> from tornado import gen, locks >>> lock = locks.Lock() >>> >>> @gen.coroutine ... def f(): ... with (yield lock.acquire()): ... # Do something holding the lock. ... pass ... ... # Now the lock is released.
In Python 3.5,
Lockalso supports the async context manager protocol. Note that in this case there is no
acquire, because
async withincludes both the
yieldand the
acquire(just as it does with
threading.Lock):
>>> async def f(): ... async with lock: ... # Do something holding the lock. ... pass ... ... # Now the lock is released.
Changed in version 4.3: Added
async withsupport in Python 3.5.
acquire(timeout=None)[source]¶
Attempt to lock. Returns a Future.
Returns a Future, which raises
tornado.gen.TimeoutErrorafter a timeout.
release()[source]¶
Unlock.
The first coroutine in line waiting for
acquiregets the lock.
If not locked, raise a
RuntimeError. | https://www.tornadoweb.org/en/branch4.5/locks.html | CC-MAIN-2022-27 | refinedweb | 441 | 55.2 |
Tutorials > C++ > Structures
Structures allow you to specify a data type that consists of a number of pieces of data.
This is useful to describe a single entity that is represented by a more than one variable.
Structures are defined using the struct keyword.
They can be defined in two ways. One way is to specify a structure as follows :
struct struct name
{ data types and statements };
This structure can now be used to create a number of variables in your program.
Another way of defining a structure is as follows :
struct { data types and statements }
struct_name;
This way of defining a structure creates only one variable named struct_name.
You cannot create more than one variable using this structure.
Contents of main.cpp :
#include <iostream>
#include <stdlib.h>
using namespace std;
Below we create a structure to hold information on a Player. Such
items include the name, health, mana and strength of the player. A flag is also used to
determine if he/she is alive. The way this structure has been created allows for
multiple Player variables to be created.
struct Player
{
char *name;
int health;
int mana;
int strength;
bool dead;
};
Below we create a World structure. As there is only one
world, we create the struct with the name after the contents of the structure.
This creates only one variable with the name World.
struct
{
int numPlayers;
int maxPlayers;
} World;
int main()
{
A Player variable can now be created like any other
normal variable.
Player player1;
Variables that are part of the structure can be accessed using the dot(.) operator.
A . must be placed after the variable which must then be followed by the variable
that you are wanting to access. The variables can therefore be initialized as shown below.
The values of these variables can be retrieved in the same way.
player1.name = "Fred";
player1.health = 100;
player1.dead = false;
cout << player1.name << " : "
<< player1.health << endl;
Another player is created below. Another way of initializing a structure is shown
below. After declaring the variable, an equals sign can be placed follwed by curly
brackets( {} ). The value of each variable can then be initialized by placing their values
in the order as shown in the structure definition separated by commas.
Player player2 = {
"Sally",
75,
50,
10,
false
};
cout << player2.name << " : "
<< player2.health << endl;
The code below shows how the World can be accessed straight
away. This is the only variable of this type.
World.numPlayers = 2;
World.maxPlayers = 5;
cout << World.numPlayers <<
" of " << World.maxPlayers
<< endl;
system("pause");
return 0;
}
You should now be able to create simple structs. More
advanced features of structs will appear in the next
tutorial.
Please let me know of any comments you may have : Contact Me
Back to Top
Read the Disclaimer | http://www.zeuscmd.com/tutorials/cplusplus/27-Structures.php | crawl-001 | refinedweb | 461 | 67.65 |
30 August 2012 07:15 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The No.1 unit will be shut for about three weeks for catalyst change while the No.2 unit will be off line for about a week for maintenance.
The company was running both the units at full capacity to build up inventory to maintain supply to their downstream plasticizer plants and domestic market during the shutdown period, the source added.
The company was keeping its 40,000 tonne/year No 3 PA unit off line since September last year due to narrow spread between feedstock orthoxylene (OX) and PA prices, the source said.
The price gap between PA and OX stood at $5-10/tonne (€4-8/tonne) based on prices assessed in the week ended 24 August, according to ICIS data.
PA was assessed at $1,395-1,420/tonne CFR (cost and freight) China Main Port (CMP), while OX stood at $1,390-1,410/tonne
The company has no plans to restart the No.3 unit with the current OX and PA price spread, | http://www.icis.com/Articles/2012/08/30/9591093/s-korea-oci-plans-pa-units-shutdown-for-maintenance-by.html | CC-MAIN-2014-52 | refinedweb | 180 | 70.33 |
dinclusion 1.0.0
Simple file inclusion in D programs.
To use this package, put the following dependency into your project's dependencies section:
dinclusion
Simple file inclusion in D programs.
How to use
To create a inclusion-file with utility dinclusion run the following command at a command prompt:
dinclusion file1 file2 ... fileN
After the command, the utility will create appropriate files with names file1.di, file2.di etc.
The use in the project.
For use in the project file, edit the D interface files and replace dinclusion inserts with your names for variable in this inserts.
After editing, add command
import file1, file2, ..., fileN; in import section of your project and compile project with following command:
dmd your_d_project file1.di file2.di .. fileN.di
- Registered by Oleg Baharev
- 1.0.0 released 3 years ago
- aquaratixc/dinclusion
- ESL-1.0
- Authors:
-
- Dependencies:
- none
- Versions:
- Show all 2 versions
- Download Stats:
0 downloads today
0 downloads this week
0 downloads this month
88 downloads total
- Score:
- 0.7
- Short URL:
- dinclusion.dub.pm | http://code.dlang.org/packages/dinclusion | CC-MAIN-2018-34 | refinedweb | 174 | 58.18 |
function expandFiles(directoriesPatternsOrFiles)
15 August 2019 0 comments Javascript
I'm working on a CLI in Node. What the CLI does it that it takes one set of
.json files, compute some stuff, and spits out a different set of
.json files. But what it does is not important. I wanted the CLI to feel flexible and powerful but also quite forgiving. And if you typo something, it should bubble up an error rather than redirecting it to something like
console.error("not a valid file!").
Basically, you use it like this:
node index.js /some/directory # or node index.js /some/directory /some/other/directory # or node index.js /some/directory/specificfile.json # or node index.js /some/directory/specificfile.json /some/directory/otherfile.json # or node index.js "/some/directory/*.json" # or node index.js "/some/directory/**/*.json"
(Note that when typing patterns in the shell you have quote them, otherwise the shell will do the expansion for you)
Or, any combination of all of these:
node index.js "/some/directory/**/*.json" /other/directory /some/specific/file.json
Whatever you use, with patterns, in particular, it has to make the final list of found files distinct and ordered by the order of the initial arguments.
Here's what I came up with:
import fs from "fs"; import path from "path"; // import glob from "glob"; /** Given an array of "things" return all distinct .json files. * * Note that these "things" can be a directory, a file path, or a * pattern. * Only if each thing is a directory do we search for *.json files * in there recursively. */ function expandFiles(directoriesPatternsOrFiles) { function findFiles(directory) { const found = glob.sync(path.join(directory, "*.json")); fs.readdirSync(directory, { withFileTypes: true }) .filter(dirent => dirent.isDirectory()) .map(dirent => path.join(directory, dirent.name)) .map(findFiles) .forEach(files => found.push(...files)); return found; } const filePaths = []; directoriesPatternsOrFiles.forEach(thing => { let files = []; if (thing.includes("*")) { // It's a pattern! files = glob.sync(thing); } else { const lstat = fs.lstatSync(thing); if (lstat.isDirectory()) { files = findFiles(thing); } else if (lstat.isFile()) { files = [thing]; } else { throw new Error(`${thing} is neither file nor directory`); } } files.forEach(p => filePaths.includes(p) || filePaths.push(p)); }); return filePaths; }
This is where I'm bracing myself for comments that either point out something obvious that Node experts know or some awesome
npm package that already does this but better.
If you have a typo, you get an error thrown that looks something like this:
Error: ENOENT: no such file or directory, lstat 'mydirectorrry'
(assuming
mydirectory exists but
mydirectorrry is a typo) | https://api.minimalcss.app/p2 | CC-MAIN-2019-43 | refinedweb | 424 | 51.44 |
It works (prints "Correct!" and exits) if I type in '1' and press enter. However, when I type in 'apples' (for example, or any other fruit) it doesn't work and the loop repeats asking "Enter a fruit:".
It obviously works when i replace
- Code: Select all
if fru in [fruits, '1']
- Code: Select all
if fru in fruits or fru=='1'
Here is my code -
- Code: Select all
from sys import exit
fruits = ['apples','oranges','bananas','mangos','strawberries']
def checkfruit():
fru = raw_input("Enter a fruit: ")
if fru in [fruits, '1']:
print "Correct!"
exit(0)
else:
checkfruit()
checkfruit()
Any help would be appreciated! I couldn't find "in" anywhere in Python docs, or maybe I didn't check them correctly. Just started with python yesterday hehe. | http://www.python-forum.org/viewtopic.php?p=1616 | CC-MAIN-2016-40 | refinedweb | 126 | 71.55 |
Forum talk:THIS IS SPARTA!!
From Uncyclopedia, the content-free encyclopedia
OH GOD, I don't even like Spongebob, but that "NO THIS IS PATRICK" thing is hillarious. Roman Dog Bird 23:28, 15 August 2007 (UTC)
- You should watch the show. It's far more intelligent than its simple cartoon nature would suggest. It's the Canterbury tales of toons, but with a pineapple under the sea. Lastly, look at the top left corner of this very screen. Sir Modusoperandi Boinc! 23:49, 15 August 2007 (UTC)
- Yeah, thank goodness they removed the tab. I hate people that talk in this namespace. – Sir Skullthumper, MD (criticize • writings • SU&W) 20:06 Aug 18, 2007
- But it's like a cool hidden secret inside the forums. One stop among many for the adventurous Uncyclopedian. +Boomer 22:34, 18 August 2007 (UTC)
- So now, instead of a tab, we have a link in parenthesis. The difference being... – Sir Skullthumper, MD (criticize • writings • SU&W) 01:14 Aug 20, 2007
- The tab was prettier. People tend to click pretty things. I am Boomer.Speak to the Boomsta. Seriously.Do it. 14:21, 20 August 2007 (UTC) | http://uncyclopedia.wikia.com/wiki/Forum_talk:THIS_IS_SPARTA!! | CC-MAIN-2015-18 | refinedweb | 194 | 78.35 |
Vibrate module
if possible I would like to request
vibratemodule - would be nice for games etc.
It's relatively easy to trigger a simple vibration using
ctypes, but there's no API to control the duration, intensity etc.
import ctypes import time c = ctypes.CDLL(None) def vibrate(): p = c.AudioServicesPlaySystemSound p.restype, p.argtypes = None, [ctypes.c_int32] vibrate_id = 0x00000fff p(vibrate_id) if __name__ == '__main__': for i in xrange(3): vibrate() time.sleep(0.5)
Sweet! That's perfect for my use case.
- Webmaster4o
Is this now easier with
objc_util?
Pure c calls are basically the same with or without objc. Since the vibrate api is pure c, and not part of an objc class, the code would be the same.
- Webmaster4o
Ok, just wondering. Thanks.
@omz Thank you for your Vibrate module.
The process went successfully when done according to your instructions.
At a time such as when you are on the phone and the alarm goes off, can it vibrate for a long time?
Objective-C seems to write in this way. | https://forum.omz-software.com/topic/2093/vibrate-module | CC-MAIN-2018-51 | refinedweb | 174 | 77.64 |
One,
For example.asp. every time a new page is created. where the unique content for each individual web page is located. and see how changes to a master page are immediately reflected in its content pages.0 and Visual Studio 2005 with the introduction of master pages. and right of every page . We discuss how master pages work.net might look like. We will look at using nested master pages in a future tutorial. There are a variety of techniques for creating web pages with a consistent look and feel.as well as a ContentPlaceHolder in the middle-left.NET version 2. Note: The core concepts and functionality of master pages has not changed since ASP. Prior to ASP. Consequently. The ContentPlaceHolder control simply denotes a position in the master page's control hierarchy where custom content can be injected by a content page. page developers often placed common markup in User Controls and then added these User Controls to each and every page. For starters. Such copying and pasting operations are ripe for error as you may accidentally copy only a subset of the shared markup into a new page. and so on. And to top it off. This inaugural tutorial starts with a look at master page basics. but allowed for easier site-wide modifications because when updating the common markup only the User Controls needed to be modified.x applications . but this approach has a number of downsides.the markup at the top. Learn how to specify a content page's master page at runtime.NET version 2. bottom. look at creating a master page and associated content pages using Visual Web Developer. These tutorials are geared to be concise and provide step-by-step instructions with plenty of screen shots to walk you through the process visually. Unfortunately. Visual Studio . Figure 2 shows what the master page for www. this approach makes replacing the existing site-wide appearance with a new one a real pain because every single page in the site must be edited in order to use the new look and feel. The shortcomings of using User Controls were addressed in ASP. This approach required that the page developer remember to manually add the User Controls to every new page.net have their own unique content. As we will see in Step 1. a feature that was lacking in Visual Studio 2005.asp. A master page is a special type of ASP. while each tutorial or forum post on www. Get Started. these regions are defined by ContentPlaceHolder controls.NET 1. Visual Studio 2008 offers design-time support for nested master pages. However. A naive approach is to simply copy and paste the common layout markup into all web pages. you must remember to copy and paste the shared content into the page.0.NET 2002 and 2003 . page developers using this approach did not enjoy a WYSIWYG design-time environment.0. Let's get started! Understanding How Master Pages Work Building a website with a consistent site-wide page layout requires that each web page emit common formatting markup in addition to its custom content. . each of these pages also render a series of common <div> elements that display the top-level section links: Home. Each tutorial is available in C# and Visual Basic versions and includes a download of the complete code used. and Other advanced master page topics.NET version 2. Learn.the versions of Visual Studio used to create ASP. Note that the master page defines the common site-wide layout .NET page that defines both the site-wide markup and the regions where associated content pages define their custom markup.rendered User Controls in the Design view as gray boxes.
Figure 02: A Master Page Defines the Site-Wide Layout and the Regions Editable on a Content Page-byContent Page Basis Once a master page has been defined it can be bound to new ASP. When the content page is visited through a browser the ASP. the content page emits both the common markup defined in its master page outside of the ContentPlaceHolder controls and the page-specific markup defined within its own Content controls.called content pages .NET pages through the tick of a checkbox.include a Content control for each of the master page's ContentPlaceHolder controls. This combined control hierarchy is rendered and the resulting HTML is returned to the end user's browser. These ASP.NET pages . Consequently. Figure 3 illustrates this concept. .NET engine creates the master page's control hierarchy and injects the content page's control hierarchy into the appropriate places.
5 with Microsoft's free version of Visual Studio 2008. Visual Web Developer 2008.the concepts discussed in these tutorials work equally well with ASP. the ASP.NET 3.Figure 03: The Requested Page's Markup is Fused into the Master Page (Click to view full-size image) Now that we have discussed how master pages work.5.NET 3. If you have not yet upgraded to ASP. don't worry .NET website we build throughout this tutorial series will be created using ASP. some demo .0 and Visual Studio 2005. Note: In order to reach the widest possible audience. However.NET 2. let's take a look at creating a master page and associated content pages using Visual Web Developer.
5specific namespaces in the using statements in ASP.5-specific features are used. Figure 06: The Master Page Defines the Markup for the Top.5-specific markup from Web. the other content is defined in the master page and therefore consistent across all content pages. if you have yet to install .NET 3.config file that includes 3.5's Web.NET" icon.config. which results in a Web.master master page so that it contains the following declarative markup: <%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.cs" Inherits="Site" %> .master's default declarative markup to create a site layout where all pages share: a common header. You will also need to remove the usingstatements that reference 3. Long story short.NET pages' code-behind classes.5-specific configuration elements and references to 3. a left column with navigation.master.5 on your computer then the downloadable web application will not work without first removing the 3. when 3.5. Do keep in mind that the demo applications available for download from each tutorial target the .config File for more information on this topic. start by updating the Site.5-specific namespaces. Creating a Simple Site Layout Let's expand Site.NET Framework version 3. and a footer that displays the "Powered by Microsoft ASP.5. See Dissecting ASP.0.aspx). The red circled region in Figure 6 is specific to the page being visited (Default. and Bottom Portions (Click to view fullsize image) To achieve the site layout shown in Figure 6. Left.NET Version 3.applications may use features new to the . news and other site-wide content. I include a note that discusses how to implement similar functionality in version 2. Figure 6 shows the end result of the master page when one of its content pages is viewed through a browser.NET Framework version 3.
and footerContent <div>s are used to display the page's content.w3. In addition to adding these <div> elements.org/TR/xhtml1/DTD/xhtml1-transitional. These various rules define the look and feel of each <div> element noted above. the left column. respectively.w3.0 Transitional//EN" "!" /> </div> </form> </body> </html> The master page's layout is defined using a series of <div> HTML elements.css. The formatting and layout rules for these assorted <div> elements is spelled out in the Cascading Stylesheet (CSS)file Styles. while the mainContent. which is specified via a <link> element in the master page's <head> element.gif" alt="Powered by ASP.NET" icon. I also renamed the ID property of the primary ContentPlaceHolder control from ContentPlaceHolder1 to MainContent.org/1999/xhtml"> . and the "Powered by Microsoft ASP. which displays the "Master Pages Tutorials" text and link. leftContent. The topContent <div> contains the markup that appears at the top of each page.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. the topContent <div> element. has its formatting rules specified in Styles.css as follows: #topContent { . For example.dtd"> <html xmlns=".
Right-click on the project name in Solution Explorer and choose the Add New Item option.NET pages that are bound to the master page.NET Design Start Kit Templates that integrate into the New Web Site dialog box in Visual Studio. and then check the "Select master page" checkbox as shown in Figure 7. . For more on CSS. we are ready to start creating ASP.text-align: right." One of my favorite ones is OpenDesigns. font-weight: bold.to medium-sized companies. Similarly. others hired a competent graphics designer. } If you are following along at your computer.master master page. Let's add a new ASP.Google returned more than six million results for the search term "free website templates. font-size: x-large. Select the Web Form template.aspx. background-color: #600. After selecting the Web Content Form template and clicking Add. As you can tell by Figure 6. the same Select a Master Page dialog box shown in Figure 8 will appear.org. Some of my clients had an existing site layout they wanted to use.NET website using the Web Application Project model instead of the Web Site Project model you will not see the "Select master page" checkbox in the Add New Item dialog box shown in Figure 7. tasking a programmer to design a website's layout is usually as wise as having your accountant perform open-heart surgery while your doctor does your taxes. Creating a Master Page Using an Existing Design Template Over the years I've built a number of ASP.NET web applications for small. To create a content page when using the Web Application Project model you must choose the Web Content Form template instead of the Web Form template. Note: A discussion of CSS and web page formatting is beyond the scope of this article.css file to your project.com.css to see the effects of different formatting rules. you will need to download this tutorial's accompanying code and add the Styles. you will also need to create a folder named Images and copy the "Powered by Microsoft ASP. A few entrusted me to design the website layout. enter the name About.NET" icon from the downloaded demo website to your project. Such pages are referred to as content pages.NET page to the project and bind it to the Site. Doing so will display the Select a Master Page dialog box (see Figure 8) from where you can choose the master page to use. text-decoration: none. Once you find a website template you like. Fortunately. there are innumerous websites that offer free HTML design templates . Step 2: Creating Associated Content Pages With the master page created. color: White. check out the CSS Tutorials at W3Schools. padding: 10px. add the CSS files and images to your website project and integrate the template's HTML into your master page. Note: If you created your ASP. height: 50px. Note: Microsoft also offers a number of free ASP. I also encourage you to download this tutorial's accompanying code and play with the CSS settings in Styles.
master Master Page (Click to view full-size image) As the following declarative markup shows.master" AutoEventWireup="true" CodeFile="About. <%@ Page . a new content page contains a @Page directive that points back to its master page and a Content control for each of the master page's ContentPlaceHolder controls.aspx.
Because the master page has two ContentPlaceHolder controls . Figure 9 shows the About.master. it is grayed out and cannot be modified. . Note that while the master page content is visible.aspx content page when viewed through Visual Web Developer's Design view. editable. this content page is bound to ~/Site. your content page's declarative markup will differ slightly from the markup shown above. I entered an "About the Author" heading and a couple of paragraphs of text. you can create the content page's interface by adding Web controls through the Source or Design views. visit the About. Each Content control references a particular ContentPlaceHolder via itsContentPlaceHolderID property. The Content controls corresponding to the master page's ContentPlaceHolders are. As you can see in Figure 10.head and MainContent . The ASP. After creating this interface. the ASP.</asp:Content> <asp:Content </asp:Content> Note: In the "Creating a Simple Site Layout" section in Step 1 I renamed ContentPlaceHolder1 to MainContent.aspx page through a browser. too. Figure 09: The Content Page's Design View Displays Both the Page-Specific and Master Page Contents (Click view full-size image) to Adding Markup and Web Controls to the Content Page Take a moment to create some content for the About. however. And just like with any other ASP.Visual Web Developer generated two Content controls. As the above markup shows. Namely.aspx page. When rendering a content page. Where master pages shine over previous site-wide template techniques is with their design-time support.NET engine must fuse the page's Content controls with its master page's ContentPlaceHolder controls.NET page. but feel free to add Web controls.NET engine determines the content page's master page from the @Pagedirective's MasterPageFile attribute. the second Content control's ContentPlaceHolderIDwill reflect the ID of the corresponding ContentPlaceHolder control in your master page. If you did not rename this ContentPlaceHolder control's ID in the same way.
To bind a master page to an existing ASP. Unfortunately. Note that there are no frames or any other specialized techniques for displaying two different web pages in a single window. view the HTML received by the browser by going to the View menu and choosing Source. 3.aspx and DataSample. and the Web Form. pointing it to the appropriate master page.NET page's @Page directive.NET page likely contains markup that's already expressed by the master page.NET page to a master page is not as easy. the <html> element.NET page's existing content into the appropriate Content controls. converting an existing ASP. fused HTML. Binding a Master Page to an Existing ASP. The end user's browser is then sent the resulting.aspx to use the Master Page" section details these steps. For step-by-step instructions on this process along with screen shots. Selectively cut and paste the ASP. To verify this.Figure 10: Visit the About.NET Page As we saw in this step. 2. I say "selectively" here because the ASP. such as the DOCTYPE. adding a new content page to an ASP. The "Update Default. Add the MasterPageFile attribute to the ASP.NET page you need to perform the following steps: 1.NET web application is as easy as checking the "Select master page" checkbox and picking the master page. .aspx Page Through a Browser (Click to view full-size image) It is important to understand that the requested content page and its associated master page are fused and rendered as a whole entirely on the web server. check out Scott Guthrie's Using Master Pages and Site Navigation tutorial. Add Content controls for each of the ContentPlaceHolders in the master page.
Therefore. you can delete Default.ToString("dddd.NET pages to this master page.Because it is much easier to create new content pages than it is to convert existing ASP.NET pages into content pages. } The above code sets the Label's Text property to the current date and time formatted as the day of the week. Step 3: Updating the Master Page's Markup One of the primary benefits of master pages is that a single master page may be used to define the overall layout for numerous pages on the site. you can update the master page later. As Figure 11 shows. Bind all new ASP. Alternatively.Text = DateTime.Now. . updating the site's look and feel requires updating a single file . MMMM dd"). but this time checking the "Select master page" checkbox.the master page.NET website add a master page to the site. <div id="leftContent"> <p> <asp:Label</asp:Label> </p> <h3>Lessons</h3> <ul> <li>TODO</li> </ul> <h3>News</h3> <ul> <li>TODO</li> </ul> </div> Next.aspx and then re-add it. the resulting markup is immediately updated to include the change to the master page. EventArgs e) { DateDisplay. and the two-digit day (see Figure 11). Don't worry if the initial master page is very simple or plain. Add a Label named DateDisplay to the leftContent <div>. Visual Web Developer adds a Default. the name of the month. let's update our master page to include the current date in at the top of the left column. revisit one of your content pages.aspx. create a Page_Load event handler for the master page and add the following code: protected void Page_Load(object sender.NET application. To illustrate this behavior. I recommend that whenever you create a new ASP. Note: When creating a new ASP. With this change.NET page into a content page.aspx page that isn't bound to a master page. If you want to practice converting an existing ASP. go ahead and do so with Default.
Figure 11: The Changes to the Master Page are Reflected When Viewing the a Content Page (Click view full-size image) to . | https://www.scribd.com/document/246100832/Template | CC-MAIN-2018-43 | refinedweb | 2,933 | 60.72 |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
I have scriptrunner in Jira 6.2 and a Workflow with several steps and subtasks. In each phase of the workflow, I need a validation if the previous subtasks (2-5 per phase) are closed or resolved before moving on to the next step. The Next step button should always be visible, but an exception shall be thrown and the transition stopped.
I tried using the example condition “All sub-tasks must be resolved” in simple scripted validator, but i guess this wont work out. I cannot use this script on validation page, or?
Thanks for any hints.
now i finally found a way to check and validate against open subtasks:
import com.atlassian.jira.ComponentManager import com.atlassian.jira.issue.Issue import org.apache.log4j.Category import com.atlassian.jira.config.SubTaskManager Collection subTasks = issue.getSubTasks() if (issue.getSubTasks().status.contains ("1")){ return false } else return true
the status "open" alway has the value 1
Hey Alex,
if it doesn't work probably your workflow doesn't resolve issues and just set them in the next status (closed, done etc).
when this is the case set a condition in your sub-workflow that the issue must have a resolution to bet closed and set a screen with resolution in this transition as well.
Hope this is your problem- because it's easy to fix.
Have a nice day and provide feedback if this was your problem.
@Alex Alex I think you missunderstood the function. Yes you can set it as a validator / condition - BUT it doesn't check if your issues are closed. Maybe closed isn't the last status in your workflow so it's not that good hint. It just check if tickets are resolved - not the status. Resolved means that the issue got a resolution (field). This can be fixed, won't fix, done, can't reproduce etc. And this is what the condition checks - resolution is Not empty.
Hi Simon, thank you for detailed explanation. i now understand the function underneath. I will have a deeper look into that, until i find a solution for my notification-validation problem.
Hi Simon, thank you for your quick answer! i'm not quite sure if i understand you correctly. there is an exapmle in script-runner plugin when creating a condition: all subtasks must be closed.
that is exactly what i need, but also with a workflow-warning poping up. And this warning, i assume, is only possible in validators-section when configure a transition.
therefor i'd like to create my own script in add parameters to validator -> simple scripted validator -> condition:
import com.atlassian.jira.issue.Issue import org.apache.log4j.Category import com.opensymphony.workflow.InvalidInputException SubTaskManager subTaskManager = ComponentManager.getInstance().getSubTaskManager(); Collection subTasks = issue.getSubTasks() if (subTaskManager.subTasksEnabled && !subTasks.empty) { subTasks.each { if (!(it.resolution > 0)) passesCondition = false } }
So when one of my subtasks is at status open, throw exception - else proceed.
sorry if this is completly wrong thinking - i'm newby to Jira-world
ok now i set my subtask workflow to automatically set the resolution to completed when closing. so for my validation, the code above should return a false statement and the exception sall be thrown if one or more resolutions aren't set. but somehow it always return true. i cannot access log or have any option for debugging.
so, nobody used some kind of notifications? is there any other possibility to warn a user if subtasks aren't closed before proceeding?
Can't mention you - cause to your username :( Wrote an explanation. | https://community.atlassian.com/t5/Jira-questions/scriptrunner-validation-if-subtaks-all-resolved/qaq-p/40087 | CC-MAIN-2018-30 | refinedweb | 615 | 51.04 |
Mesa 19.1.0-devel (git b46b661)
Whoops, looks like 18.2 does it too. Is this just the driver grabbing a chunk of working memory? In a small 4GB system it looks like a lot.
I see no leak in my code but the system memory continues to be chewed up such that swap space is used.
Created attachment 143980 [details]
a complete program that illustrates the issues
The attached code and libraries illustrate two issues:
[1] The strange behavior of the memory used -- the program itself has no leak
[2] Nasty artifacts that appear as an image is rendered.
Neither of these issues exist on a similar Linux system with an Nvidia GPU and driver.
I have boiled my code down to a minimum build-able set including my GLSL loader.
Thank you for working so hard on this issue. The FBO blitting turns out to be a red herring.
My fragment shader is 'odd' in that is has large switch statement. This has caused the linking time to be rather long as reported in bug #91857
and, to my surprise, it also causes the artifacts I reported here and in bug #93676
I created a sample application that illustrates the problem. I'm afraid it will be troublesome to build but it is possible to reproduce the artifacts in it.
The fragment shader's case statement has a #if ... #endif section that will enable/disable the artifact problem.
*** Bug 93676. | https://bugs.freedesktop.org/show_bug.cgi?format=multiple&id=110424 | CC-MAIN-2020-29 | refinedweb | 243 | 72.46 |
8.2.
calendar — General calendar-related functions¶
Source code: Lib/calendar.py
This. For related
functionality, see also the
datetime and
time modules.
Most of these functions and classes rely on the
datetime module which
uses an idealized calendar, the current Gregorian calendar extended
in both directions. This matches the definition of the “proleptic Gregorian”
calendar in Dershowitz and Reingold’s book “Calendrical Calculations”, where
it’s the base calendar for all computations.
- class
calendar.
Calendar(firstweekday=0)¶
Creates a
Calendarobject. firstweekday is an integer specifying the first day of the week.
0is Monday (the default),
6is Sunday.
A
Calendarobject provides several methods that can be used for preparing the calendar data for formatting. This class doesn’t do any formatting itself. This is the job of subclasses.
Calendarinstances have the following methods:
iterweekdays()¶
Return an iterator for the week day numbers that will be used for one week. The first value from the iterator will be the same as the value of the
firstweekdayproperty.
itermonthdates(year, month)¶
Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as
datetime.dateobjects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.
itermonthdays2(year, month)¶
Return an iterator for the month month in the year year similar to
itermonthdates(). Days returned will be tuples consisting of a day number and a week day number.
itermonthdays(year, month)¶
Return an iterator for the month month in the year year similar to
itermonthdates(). Days returned will simply be day numbers.
monthdatescalendar(year, month)¶
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven
datetime.dateobjects.
monthdays2calendar(year, month)¶
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.
monthdayscalendar(year, month)¶
Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.
yeardatescalendar(year, width=3)¶
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are
datetime.dateobjects.
yeardays2calendar(year, width=3)¶
Return the data for the specified year ready for formatting (similar to
yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.
yeardayscalendar(year, width=3)¶
Return the data for the specified year ready for formatting (similar to
yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.
- class
calendar.
TextCalendar(firstweekday=0)¶
This class can be used to generate plain text calendars.
TextCalendarinstances have the following methods:
formatmonth(theyear, themonth, w=0, l=0)¶
Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the
setfirstweekday()method.
prmonth(theyear, themonth, w=0, l=0)¶
Print a month’s calendar as returned by
formatmonth().
formatyear(theyear, w=2, l=1, c=6, m=3)¶
Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the
setfirstweekday()method. The earliest year for which a calendar can be generated is platform-dependent.
pryear(theyear, w=2, l=1, c=6, m=3)¶
Print the calendar for an entire year as returned by
formatyear().
- class
calendar.
HTMLCalendar(firstweekday=0)¶
This class can be used to generate HTML calendars.
HTMLCalendarinstances have the following methods:
formatmonth(theyear, themonth, withyear=True)¶
Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.
formatyear(theyear, width=3)¶
Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.
formatyearpage(theyear, width=3, css='calendar.css', encoding=None)¶
Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used.
Nonecan be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).
- class
calendar.
LocaleTextCalendar(firstweekday=0, locale=None)¶
This subclass of
TextCalendarcan be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.
- class
calendar.
LocaleHTMLCalendar(firstweekday=0, locale=None)¶
This subclass of
HTMLCalendarcan be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.
Note
The
formatweekday() and
formatmonthname() methods of these two
classes temporarily change the current locale to the given locale. Because
the current locale is a process-wide setting, they are not thread-safe.
For simple text calendars this module provides the following functions.
calendar.
setfirstweekday(weekday)¶
Sets the weekday (
0is Monday,
6is Sunday) to start each week. The values
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY, and
SUNDAYare provided for convenience. For example, to set the first weekday to Sunday:
import calendar calendar.setfirstweekday(calendar.SUNDAY)
calendar.
leapdays(y1, y2)¶
Returns the number of leap years in the range from y1 to y2 (exclusive), where y1 and y2 are years.
This function works for ranges spanning a century change.
calendar.
weekday(year, month, day)¶
Returns the day of the week (
0is Monday) for year (
1970–...), month (
1–
12), day (
1–
31).
calendar.
weekheader(n)¶
Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday.
calendar.
monthrange(year, month)¶
Returns weekday of first day of the month and number of days in month, for the specified year and month.
calendar.
monthcalendar(year, month)¶
Returns a matrix representing a month’s calendar. Each row represents a week; days outside of the month a represented by zeros. Each week begins with Monday unless set by
setfirstweekday().
calendar.
month(theyear, themonth, w=0, l=0)¶
Returns a month’s calendar in a multi-line string using the
formatmonth()of the
TextCalendarclass.
calendar.
prcal(year, w=0, l=0, c=6, m=3)¶
Prints the calendar for an entire year as returned by
calendar().
calendar.
calendar(year, w=2, l=1, c=6, m=3)¶
Returns a 3-column calendar for an entire year as a multi-line string using the
formatyear()of the
TextCalendarclass.
calendar.
timegm(tuple)¶
An unrelated but handy function that takes a time tuple such as returned by the
gmtime()function in the
timemodule, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact,
time.gmtime()and
timegm()are each others’ inverse.
The
calendar module exports the following data attributes:
calendar.
month_name¶
An array that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and
month_name[0]is the empty string. | https://docs.python.org/3/library/calendar.html?highlight=calendar | CC-MAIN-2017-04 | refinedweb | 1,305 | 57.57 |
is there some kind of magic function i can use to set a variable equal to the time of the day?
if so, how would i use this function?
This is a discussion on time function question within the C++ Programming forums, part of the General Programming Boards category; is there some kind of magic function i can use to set a variable equal to the time of the ...
is there some kind of magic function i can use to set a variable equal to the time of the day?
if so, how would i use this function?
"uh uh uh, you didn't say the magic word"
-Jurassic Park
#include <time.h>
time_t now;
time_t *pNow;
now = time(pNow);
the system time is stored in the variable now and in the pointer pNow. You could use now or pnow alone if desired. Unfortunately time_t and time_t * are not convenient formats so you can convert them like this:
char sNow[30] = ctime(pnow);
tm tNow = localtime(pnow);
the char string returned by ctime() is something like:
Mon Dec 31, 2001
and tm is a struct something like this:
struct tm
{
int tm_month;
int tm_day;
int tm_year;
int day_of_week;
//etc.
}
Exact formats, prototypes, definitions, etc. should be available in the help section of your compiler.
could the above code be modified to tell me the time of the day according to the internal clock on the comp?
"uh uh uh, you didn't say the magic word"
-Jurassic Park
I guess what im asking is....
How could i manipulate the variable holding the day of the week, month, day and time that the variable is holding into just time?
Last edited by heat511; 01-03-2002 at 11:23 AM.
"uh uh uh, you didn't say the magic word"
-Jurassic Park
Originally posted by Unregistered
#include <time.h>
time_t now;
time_t *pNow;
now = time(pNow);
Woah, is that an uninatialized pointer there? It looks like its pointing to nowhere, but then you pass it to the time function, which fills it in, so your filling up some random memory. Not cool has a reference for all the time functions
The localtime function returns a struct that has a bunch of info
info here from
struct tm
{
int tm_sec; // the number of elapsed seconds in the minute
int tm_min; // the number of elapsed minutes in the hour
int tm_hour; // the number of elapsed hours in the day (0-23)
int tm_mday; / /the number of elapsed days in the month (1-31)
int tm_mon; // the number of elapsed months in the year (0-11)
int tm_year; //the numbers of elapsed years since 1900
int tm_wday; // the number of elapsed days in the week since Sunday (0-6)
int tm_yday; //the number of the elapsed days in the year (0-365)
int tm_isdst; // equals 1 if daylight savings is in effect, zero if not, -1 if unknown
};
You're right, using unitialize pointers can be problematic. But it's not as ominus as you make it sound. The code snippet you refer to is no different than this:
int num = 1;
int * pNum;
pNum = #
Used with respect unitialized pointers are not going to blow up or anything.
To refer to certain members of a struct, but not all, you can use the dot or arrow operators. Using the dot operator it goes something like ths:
//using snippet from first post:
cout << tNow.tm_hour << ':' << tNow.tm_min << ':' << tNow.tm_sec << endl;
leave out the colons if you wish. Manipulate tm structs as you need to to use whatever display format you want. | http://cboard.cprogramming.com/cplusplus-programming/8071-time-function-question.html | CC-MAIN-2014-52 | refinedweb | 596 | 73.61 |
Judging the amount of time required to execute a given task in a development process is nearly impossible. Executing the task on the actual target machine, however, lets you actively monitor how long each task takes. Then you simply measure the execution time and change the cursor to an hourglass when necessary. Fortunately, most tasks for which you typically display the hourglass cursor are executed during the processing of user interface (UI) events. Placing code within the stream of UI events enables you to measure processing times and automate the hourglass as desired.
The solution
By extending the capabilities of Java's UI event dispatch queue, you can easily insert your own timing mechanism into the UI events stream. The event queue distributes every UI event that occurs in an application. By replacing the standard event queue with your own, you can intercept every event passing through the queue. Your queue can then measure the time it takes to process each event and change the cursor if needed.
In this article, I will provide the full source code to accomplish this tip. But first, let's examine the solution in more detail. You first create an event queue class that extends the standard
java.awt.EventQueue class. The new event queue contains a special timer thread for measuring the processing time for each event. It starts the timer before dispatching an event. Then, if the event is not processed within your predetermined time limit, the timer thread changes the cursor to an hourglass. After processing is complete, the queue changes the cursor back to the default cursor if necessary.
Below you will find the implementation of the
dispatchEvent() method for the new event queue.
14: protected void dispatchEvent(AWTEvent event) { 15: waitTimer.startTimer(event.getSource()); 16: try { 17: super.dispatchEvent(event); 18: } 19: finally { 20: waitTimer.stopTimer(); 21: } 22: }
All UI events go through the
EventQueue.dispatchEvent() method. This method delivers the events to the correct UI components, which then process the events. As you can see, the queue overrides the default behavior of
dispatchEvent() and wraps the standard functionality of the
EventQueue class in your timing routines.
Line 15 notifies your timing thread that an event is about to be dispatched so that it will begin measuring the event's execution time. Note that you are passing the event's source -- the object to which this event will eventually be delivered. If the timing thread determines that the event is taking too long to process, it will need to know the event's source to determine which
java.awt.Window's cursor should be changed to the hourglass.
Line 20 stops the timer and, if necessary, changes the cursor back to the default cursor. A
try-
finally block wraps the event dispatch because the
stopTimer() method must be executed regardless of whether an exception is thrown during event processing.
The
startTimer() method is very straightforward. It simply stores a reference to the event's source and notifies the timer thread.
29: synchronized void startTimer(Object source) { 30: this.source = source; 31: notify(); 32: }
Analyzing the timer thread
Now look at the implementation of the
run()
method for the timer thread, the real workhorse of the thread. First note that the entire
run()
method is synchronized, as are both the
startTimer()
and
stopTimer()
methods. This synchronization prevents multithreading race conditions by letting the
startTimer()
or
stopTimer()
methods execute only when the
run()
method enters either of the two
wait()
statements to release the monitor. After the timing thread starts, it waits indefinitely at line 47 to be notified and awakened by the
startTimer()
method.
46: //wait for notification from startTimer() 47: wait();
After receiving notification from the
startTimer() method, the timing thread pauses again at the next statement.
49: //wait for event processing to reach the threshold, or 50: //interruption from stopTimer() 51: wait(delay);
Here, the thread waits for the specified length of time to pass. Once it reaches this statement, there are only two possible paths of execution. The event currently being dispatched by your event queue may return from processing and interrupt the thread, at which point an
InterruptedException will be thrown and will force the thread to wrap around to the top of the loop and wait for the next event. However, if processing takes longer than your specified delay period, your timer thread will awaken on its own and continue executing the following code.));
Here, you first determine whether the source is a
java.awt.Component or a
java.awt.MenuComponent, both of which indicate that you can eventually locate a
java.awt.Window whose cursor you need to change. Note that you must handle a
java.awt.MenuComponent as a special case because it does not extend
java.awt.Component like the other UI classes in the AWT (Abstract Windowing Toolkit) package. Then a Swing utility method locates the window that contains the source component. Once you have that parent window, you can change that window's cursor to an hourglass. You can call the
Component.setCursor() method outside the normal event-dispatch thread because, as a quick perusal of the
java.awt.Component source code will reveal,
setCursor() is a synchronized method.
You may notice that this timing thread waits until the last moment before trying to find the source object's parent window. Although it may seem reasonable to find the parent within the
startTimer() method, this particular implementation enjoys a performance advantage. Hundreds of events can flow through your queue if you simply move the mouse cursor around a window, so you want to introduce as little processing overhead as possible from your event queue. You can accomplish this by performing extra processing only when absolutely necessary, including finding the source object's parent window. In your timer thread, you need to find the parent window only if the specified delay passes and you are forced to display the hourglass cursor.
Meanwhile, back in your event queue, processing of the dispatched event will eventually be completed (hopefully!), at which point the
stopTimer() method will be invoked.
34: synchronized void stopTimer() { 35: if (parent == null) 36: interrupt(); 37: else { 38: parent.setCursor(null); 39: parent = null; 40: } 41: }
If the parent instance variable for your timer thread is still null, then you can be certain that the timer has not yet changed the cursor to an hourglass. In this situation, you are required to interrupt only the timer thread, which will throw an
InterruptedException within the thread. Execution of the
run() method will then immediately drop to the catch block near the bottom of the loop, at which point it will loop back to the
wait() statement and wait for notification of the next event.
Now, to use your queue, you just need to replace the standard event queue with an instance of the special
WaitCursorEventQueue, which can be accomplished with the following few lines of code.
EventQueue waitQueue = new WaitCursorEventQueue(500); Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
Part of the trick to this tip is choosing the duration after which the hourglass should appear. The delay should be long enough that the hourglass will not appear for most events processed within the UI thread, but it should be short enough so that the user perceives near-immediate feedback when a more intensive task begins processing. In moderate usability testing, a delay in the range of about 500 milliseconds, as shown above, appears to work quite well.
Full code listing
Below is the complete source code for
WaitCursorEventQueue.java.
1: import java.awt.*; 2: import java.awt.event.*; 3: import javax.swing.SwingUtilities; 4: 5: public class WaitCursorEventQueue extends EventQueue { 6: 7: public WaitCursorEventQueue(int delay) { 8: this.delay = delay; 9: waitTimer = new WaitCursorTimer(); 10: waitTimer.setDaemon(true); 11: waitTimer.start(); 12: } 13: 14: protected void dispatchEvent(AWTEvent event) { 15: waitTimer.startTimer(event.getSource()); 16: try { 17: super.dispatchEvent(event); 18: } 19: finally { 20: waitTimer.stopTimer(); 21: } 22: } 23: 24: private int delay; 25: private WaitCursorTimer waitTimer; 26: 27: private class WaitCursorTimer extends Thread { 28: 29: synchronized void startTimer(Object source) { 30: this.source = source; 31: notify(); 32: } 33: 34: synchronized void stopTimer() { 35: if (parent == null) 36: interrupt(); 37: else { 38: parent.setCursor(null); 39: parent = null; 40: } 41: } 42: 43: public synchronized void run() { 44: while (true) { 45: try { 46: //wait for notification from startTimer() 47: wait(); 48: 49: //wait for event processing to reach the threshold, or 50: //interruption from stopTimer() 51: wait(delay); 52:)); 67: } 68: catch (InterruptedException ie) { } 69: } 70: } 71: 72: private Object source; 73: private Component parent; 74: } 75: }
Potential setbacks
You should be aware of a few caveats. If your application manually changes the cursor for an entire window, especially while processing UI events, the new event queue will likely cause unexpected results, such as changing the cursor you specified back to the default. This tip will also not work in an applet in the Java Virtual Machines included with currently available Web browsers because of the applet's reliance on JDK 1.2 features. Using Sun's Java plug-in provides the necessary JDK 1.2 compliance, but
Toolkit.getSystemEventQueue()
is a security-checked method so this tip precludes the use of unsigned applets. It should also be noted that a few third-party tools modify the event queue and could possibly interfere with the operation of the
WaitCursorEventQueue
. With a few minor enhancements, the
WaitCursorEventQueue
could even let you disable the hourglass automation at will or for selected event types.
The implementation I've provided offers a simple solution adequate for many applications and, I hope, gives an understandable explanation of Java's event queue processing. Maybe you will never have to think about that hourglass again.
Learn more about this topic
- Browse JDK 1.2 documentation for further information about the Java event queue
- To submit a Java Tip | http://www.javaworld.com/article/2077590/learn-java/java-tip-87--automate-the-hourglass-cursor.html | CC-MAIN-2017-26 | refinedweb | 1,647 | 62.88 |
Base class for all multiple-valued fields. More...
#include <Inventor/fields/SoMField.h>
Base class for all multiple-valued fields.
Each class derived from SoMField begins with an SoMF prefix and contains a dynamic array of values of a particular type. Each has a setValues() method that is passed an array of values of the correct type; these values are copied into the array in the field, making extra room in the array if necessary.
The start and num parameters to this method indicate the starting array index to copy into and the number of values to copy.
The getValues() method for a multiple-value field returns a read-only array of values in the field.
In addition, the indexing operator "[ ]" is overloaded to return the i 'th value in the array; because it returns a const reference, it can be used only to get values, not to set them.
Methods are provided for getting the number of values in the field, inserting space for new values in the middle, and deleting values.
There are other methods that allow you to set only one value of several in the field and to set the field to contain one and only one value.
Two other methods can be used to make several changes to a multiple-value field without the overhead of copying values into and out of the fields. The startEditing() method returns the internal array of values in the field. It can be used to change (but not add or remove) any values in the array. The finishEditing() method indicates that the editing is done and notifies any sensors or engines that may be connected to the field.
SoMFields are written to file as a series of values separated by commas, all enclosed in square brackets. If the field has no values (getNum() returns zero), then only the square brackets ("[ ]") are written. The last value may optionally be followed by a comma. Each field subtype defines how the values are written; for example, a field whose values are integers might be written as:
[ 1, 2, 3, 4 ]
or:
[ 1, 2, 3, 4, ]
Deletes num values beginning at index start (index start through start + num -1 will be deleted, and any leftover values will be moved down to fill in the gap created).
A num of -1 means delete all values from start to the last value in the field; getNum() will return start as the number of values in the field after this operation ( deleteValues(0, -1) empties the field ). However if num is greater than or equal to the number of values in the field, start is ignored and all values are deleted.
If the field's values are stored in an user data array and if the number of values to delete is not zero, a new array is allocated and the user data array is no longer used.
Return the type identifier for this field class.
Reimplemented from SoField.
Reimplemented in SoMFDataMeasure, SoMFKernel2i32, SoMFKernel3i32, SoMFBitMask, SoMFBool, SoMFBufferObject, SoMFColor, SoMFColorRGBA, SoMFDouble, SoMFEngine, SoMFEnum, SoMFFieldContainer, SoMFFilePathString, SoMFFloat, SoMFImage, SoMFInstanceParameter, SoMFInt32, SoMFInt64, SoMFMatrix, SoMFName, SoMFNode, SoMFPath, SoMFPlane, SoMFRotation, SoMFShort, SoMFString, SoMFTime, SoMFUByte, SoMFUInt32, SoMFUniformShaderParameter, SoMFUShort, SoMFVec2d, SoMFVec2f, SoMFVec2FilePathString, SoMFVec2i32, SoMFVec2s, SoMFVec2String, SoMFVec3d, SoMFVec3f, SoMFVec3i32, SoMFVec3s, SoMFVec4b, SoMFVec4f, SoMFVec4i32, SoMFVec4s, SoMFVec4ub, SoMFVec4ui32, and SoMFVec4us.
Returns the number of values currently in the field.
Inserts space for num values at index start .
Index start through start + num -1 will be moved up to make room. For example, to make room for 7 new values at the beginning of the field call insertSpace(0, 7) . If field's values are stored in an user data array and if the number of values to insert is not zero, a new array is allocated and the user's one is no more used.
This is equivalent to the set() method of SoField, but operates on only one value.
See the SoField methods for details. If field's values are stored in an user data array and if specified index is greater than this array's length, a new array is allocated and the user's one is no more used.
Forces this field to have exactly num values, inserting or deleting values as necessary.
If field's values are stored in an user data array and if specified number of values is different from this array's length, a new array is allocated and the user's one is no more used. | https://developer.openinventor.com/refmans/latest/RefManCpp/class_so_m_field.html | CC-MAIN-2021-25 | refinedweb | 738 | 57.81 |
Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication
How To: Store an Encrypted Connection String in the Registry: Applications may choose to store encrypted data such as connection strings and account credentials in the Windows registry. This How To shows you how to store and retrieve encrypted strings in the registry. (7 printed pages)
Contents."
Notes
- The connection string, initialization vector and key used for encryption will be stored in the registry as named values beneath the following registry key.
HKEY_LOCAL_MACHINE\Software\TestApplication
- The initialization vector and key must be stored in order to allow the connection string to be decrypted.
Summary of Steps
This How To includes the following steps:
- Step 1. Store the Encrypted Data in the Registry
- Step 2. Create an ASP.NET Web Application
Step 1. Store the Encrypted Data in the Registry
This procedure creates a Windows application that will be used to encrypt a sample database string and store it in the registry.
To store the encrypted data in the registry
- Start Visual Studio .NET and create a new C# Windows project called EncryptionTestApp.
- Add an assembly reference to the Encryption.dll assembly.
To create this assembly, you must perform the steps described in How To: Create an Encryption Library in .NET 1.1 in the Reference section of this guide.
- Add the following using statements to the top of Form1.cs beneath the existing using statements.
using Encryption; using System.Text; using Microsoft.Win32;
- Add the controls in Table 1 to Form1 and arrange them as illustrated in Figure 1.
Table 1. EncryptionTestApp controls
Figure 1. Encryption Test Harness dialog box
- Set the Text property of txtConnectionString to
"Server=local; database=pubs; uid=Bob; pwd=Password"
- Set the Text property of txtKey to
.
- Set the Text property of Form1 to
"Encryption Test Harness"
- Double-click the Encrypt button to create a button click event handler and add the following code to the event handler. "); }
- Return to Form1 in Designer mode and double-click the Decrypt button to create a button click event handler.
- Add the following code to the Decrypt button event handler."); }
- Return to Form1 in Designer mode and double-click the Write Registry Data button to create a button click event handler.
- Add the following code to the event handler.
//");
- Run the application, and then click Encrypt.
The encrypted connection string is displayed in the Encrypted String field.
- Click Decrypt.
The original string is displayed in the Decrypted String field.
- Click Write Registry Data.
- In the message box, click OK.
- Run regedit.exe and view the contents of the following key.
HKLM\Software\TestApplication
Confirm that encoded values are present for the connectionString, initVector and key named values.
- Close regedit and the test harness application.
Step 2. Create an ASP.NET Web
- Create a new Visual C# ASP.NET Web Application called EncryptionWebApp.
- Add an assembly reference to the Encryption.dll assembly.
To create this assembly, you must perform the steps described in How To: Create an Encryption Library in .NET 1.1 in the Reference section of this guide.
- Open Webform1.aspx.cs and add the following using statements at the top of the file beneath the existing using statements.
using Encryption; using System.Text; using Microsoft.Win32;
- Add the controls listed in Table 2 to WebForm1.aspx.
Table 2: WebForm1.aspx controls
- Double-click the Get Connection String button to create a button click event handler.
- Add the following code to the event handler.);
- On the Build menu, click Build Solution.
- Right-click Webform1.aspx in Solution Explorer, and then click View in Browser.
- Click Get Connection String.
The encrypted and decrypted connection strings are displayed on the Web form.
Additional Resources
For more information, see How To: Create an Encryption Library in the Reference section of this guide. | http://msdn.microsoft.com/en-us/library/ff649224.aspx | CC-MAIN-2014-10 | refinedweb | 632 | 60.21 |
This article shows how to implement an Enigma like cryptography using C#. This kind of cryptography system was used until the 70's. The most famous use of it was by the German army during the WWII. The breaking of this code led the allies to victory. This cryptography method can still be secure enough for use in non critical systems. If the Germans would have used the method with care, maybe the allies would not have discovered their secrets.
The reader might be interested in some general information about Enigma. These links could help you:
This code is a complete program that shows the inner workings of such a machine. If the user wants to understand more about the Enigma machine, then he/she would need to Google for more information. This code shows how simple it is to emulate such complicate wirings as those of the Enigma machine, using a modern programming language.
The machine has at least three rotors, each one having the alphabet written on it. The rotors has a visible part which consists of the alphabet and a part that has other letters which are linked to the first one by wires. The three rotors are arranged one after the other from right to left. The rotor is not static.
This kind of machine was a combination of electrical and mechanical cryptography system. Basically, when the user of the machine pressed a key, the current would go to the first rotor to the letter corresponding to that key (let's say 'A'). The wirings of the wheel would lead to an output letter from the first rotor with a different value, let's say 'D', this impulse would then go to the second rotor, and the same thing would happen there, and in the third rotor. From there, the impulse would go to a last wheel - that is named the 'reflector'. This wheel (rotor) is the only non rotating wheel. The impulse would go to this wheel and from here it would return to the third rotor, and make its way backwards. From the first rotor, the current would illuminate a LED under a panel. This would be the encrypted letter.
This is not all. At each key press, the first rotor would rotate with one position so that the output letter would not be the same when you press the same key twice. The second rotor would rotate one position once at every 28 rotations of the first rotor, and the third one once every 28 rotations of the second rotor. As I've said earlier, the reflector is the only static rotor. On some models, the second and third rotor would rotate more than once at every 28 rotations of the previous rotor.
To decrypt the data, you just had to set the rotors at the exact initial position as the rotors on the machine that produced that output and then type in the encrypted data.
There were several rotors and they could be changed. To complicate things even more, the military version had a front panel with letters were you could interconnect two letters so that each time a letter would occur, it would be replaced with the other one. To show this kind of complicated inner workings, the following C# code would suffice:
//encrypt the data in the upper text box, and put the result in the lower one //this code is taking the data in one text box //and puts the crypted/decrypted result //in another one. void Button1Click(object sender, System.EventArgs e) { char[] chIn = txtInit.Text.ToUpper().ToCharArray(); txtFinal.Text = ""; for(int i=0;i<chIn.Length;i++){ //we only use the upper letters if(chIn[i]>=65 && chIn[i]<=90){ rr.Move(); rr.PutDataIn(chIn[i]); txtFinal.AppendText(""+rr.GetDataOut()); } } }
You can see that we only use the upper letters. That's because the existence of punctuation and spaces would help in the decryption of the message.
I've also created a rotor class which practically represents one rotor of the enigma machine. In this class, we have the methods
Move which moves the rotor one position and the
PutDataIn which emulates the sending of the electric signal to the first rotor. As you can see, we only send the data to the first rotor, which will send the data further down the chain.
Here is the code for this class:
using System; using System.Text; using System.Windows.Forms; namespace Enigma { public class Rotor { private string layout; private byte offset; private Rotor previous, next; private Label lbl; private char cIn = '\0', notchPos; public Rotor(string layout,Label lbl,char notchPos) { this.layout = layout; this.previous = previous; this.next = next; this.lbl = lbl; this.notchPos = notchPos; offset = 0; } public string GetLayout(){ return layout; } public void SetNextRotor(Rotor next){ this.next = next; } public void SetPreviousRotor(Rotor previous){ this.previous = previous; } public char GetInverseCharAt(string ch){ int pos = layout.IndexOf(ch); if(offset>pos){ pos = 26 - (offset-pos); }else{ pos = pos - offset; } if(previous!=null){ pos = (pos+previous.GetOffset())%26; } return (char)(65+pos); } public int GetOffset(){ return offset; } public char GetNotchPos(){ return notchPos; } public void ResetOffset(){ offset = 0; } public bool HasNext(){ return next!=null; } public bool HasPrevious(){ return previous!=null; } public void Move(){ if(next==null){ return; } offset++; if(offset==26){ offset = 0; } if(next!=null && (offset+65) == ((notchPos-65)%26)+66){ next.Move(); } lbl.Text = ""+((char)(65+offset)); } public void MoveBack(){ if(offset==0){ offset = 26; } offset--; lbl.Text = ""+((char)(65+offset)); } public void PutDataIn(char s){ cIn = s; char c = s; c = (char)(((c - 65) + offset) % 26 + 65); if(next!=null){ c = layout.Substring((c-65),1).ToCharArray()[0]; if((((c-65)+(-offset))%26 + 65)>=65){ c = (char)(((c-65)+(-offset))%26 + 65); }else{ c = (char)(((c-65)+(26+(-offset)))%26 + 65); } next.PutDataIn(c); } } public char GetDataOut(){ char c = '\0'; if(next!=null){ c = next.GetDataOut(); c = GetInverseCharAt(""+c); }else{ //only in the reflector case c = layout.Substring((cIn-65),1).ToCharArray()[0]; c = (char)(((c - 65) + previous.offset)%26+65); } return c; } } }
Although it seems peculiar, the older the cryptographic algorithm, the safer it is. This is because it means that people have tested it and they did not found any way in. Maybe in a later article, I will show you how to implement an instant messenger that uses this cryptography technique.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/security/enigma_emulator.aspx | crawl-002 | refinedweb | 1,066 | 65.83 |
Format String Syntax¶
Formatting functions such as fmt::format() and fmt::print() use the same format string syntax described in this section. ::= "{" [
arg_id] [":"
format_spec] "}" arg_id ::=
integer|
identifierinteger ::=
digit+ digit ::= "0"..."9" identifier ::=
id_start
id_continue* id_start ::= "a"..."z" | "A"..."Z" | "_" id_continue ::=
id_start|
digit
In less formal terms, the replacement field can start with an arg_id
that specifies the argument whose value is to be formatted and inserted into
the output instead of the replacement field.
The arg_id is optionally followed by a format_spec, which is preceded
by a colon
':'. These specify a non-default format for the replacement value.
See also the Format Specification Mini-Language section.
If the numerical arg_ids in a format string are 0, 1, 2, ... in sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be automatically inserted in that order.
Named arguments can be referred to by their names or indices.
Some simple format string examples:
"First, thou shalt count to {0}" // References the first argument "Bring me a {}" // Implicitly references the first argument "From {} to {}" // Same as "From {0} to {1}" in certain positions within it. These nested replacement fields can contain only an argument id; format specifications are not allowed. This allows the formatting of a value to be dynamically specified.
See the Format Examples section for some examples.
Format Specification Mini-Language¶
“Format specifications” are used within replacement fields contained within a format string to define how individual values are presented (see Format String Syntax). Each formattable type may define how the format specification is to be interpreted.
Most built-in types implement the following options for format specifications, although some of the formatting options are only supported by the numeric types.
The general form of a standard format specifier is:
format_spec ::= [[
fill]
align][
sign]["#"]["0"][
width]["."
precision][
type] fill ::= <a character other than '{' or '}'> align ::= "<" | ">" | "^" sign ::= "+" | "-" | " " width ::=
integer| "{" [
arg_id] "}" precision ::=
integer| "{" [
arg_id] "}" type ::=
int_type| "a" | "A" | "c" | "e" | "E" | "f" | "F" | "g" | "G" | "L" | "p" | "s" int_type ::= "b" | "B" | "d" | "o" | "x" | "X"
The fill character can be any Unicode code point other than
'{' or
'}'. and floating-point types.
For integers, when binary, octal, or hexadecimal output is used, this
option adds the prefix respective
"0b" (
"0B"),
"0", or
"0x" (
"0X") to the output value. Whether the prefix is
lower-case or upper-case is determined by the case of the type
specifier, for example, the prefix
"0x" is used for the type
'x'
and
"0X" is used for
'X'. For floating-point numbers.
width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content.
Preceding the width field by a zero (
'0') character enables sign-aware
zero-padding for numeric types. It forces the padding to be placed after the
sign or base (if any) but before the digits. This is used for printing fields in
the form ‘+000000120’. This option is only valid for numeric types and it has no
effect on formatting of infinity and NaN.,
character, Boolean, and pointer values.
Finally, the type determines how the data should be presented.
The available string presentation types are:
The available character presentation types are:
The available integer presentation types are:
Integer presentation types can also be used with character and Boolean values.
Boolean values are formatted using textual representation, either
true or
false, if the presentation type is not specified.
The available presentation types for floating-point values are:
The available presentation types for pointers are:
Format Examples¶
This section contains examples of the format syntax and comparison with the printf formatting.
In most of the cases the syntax is similar to the printf formatting, with the
addition of the
{} and with
: used instead of
%.
For example,
"%03.2f" can be translated to
"{:03.2f}".
The new format syntax also supports new and different options, shown in the following examples.
Accessing arguments by position:
fmt::format("{0}, {1}, {2}", 'a', 'b', 'c'); // Result: "a, b, c" fmt::format("{}, {}, {}", 'a', 'b', 'c'); // Result: "a, b, c" fmt::format("{2}, {1}, {0}", 'a', 'b', 'c'); // Result: "c, b, a" fmt::format("{0}{1}{0}", "abra", "cad"); // arguments' indices can be repeated // Result: "abracadabra"
Aligning the text and specifying a width:
fmt::format("{:<30}", "left aligned"); // Result: "left aligned " fmt::format("{:>30}", "right aligned"); // Result: " right aligned" fmt::format("{:^30}", "centered"); // Result: " centered " fmt::format("{:*^30}", "centered"); // use '*' as a fill char // Result: "***********centered***********"
Dynamic width:
fmt::format("{:<{}}", "left aligned", 30); // Result: "left aligned "
Dynamic precision:
fmt::format("{:.{}f}", 3.14, 1); // Result: "3.1"
Replacing
%+f,
%-f, and
% f and specifying a sign:
fmt::format("{:+f}; {:+f}", 3.14, -3.14); // show it always // Result: "+3.140000; -3.140000" fmt::format("{: f}; {: f}", 3.14, -3.14); // show a space for positive numbers // Result: " 3.140000; -3.140000" fmt::format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}' // Result: "3.140000; -3.140000"
Replacing
%x and
%o and converting the value to different bases:
fmt::format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); // Result: "int: 42; hex: 2a; oct: 52; bin: 101010" // with 0x or 0 or 0b as prefix: fmt::format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42); // Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010"
Padded hex byte with prefix and always prints both hex characters:
fmt::format("{:#04x}", 0); // Result: "0x00"
Box drawing using Unicode fill:
fmt::print( "┌{0:─^{2}}┐\n" "│{1: ^{2}}│\n" "└{0:─^{2}}┘\n", "", "Hello, world!", 20);
prints:
┌────────────────────┐ │ Hello, world! │ └────────────────────┘
Using type-specific formatting:
#include <fmt/chrono.h> auto t = tm(); t.tm_year = 2010 - 1900; t.tm_mon = 6; t.tm_mday = 4; t.tm_hour = 12; t.tm_min = 15; t.tm_sec = 58; fmt::print("{:%Y-%m-%d %H:%M:%S}", t); // Prints: 2010-08-04 12:15:58
Using the comma as a thousands separator:
#include <fmt/locale.h> auto s = fmt::format(std::locale("en_US.UTF-8"), "{:L}", 1234567890); // s == "1,234,567,890" | https://fmt.dev/7.1.2/syntax.html | CC-MAIN-2021-25 | refinedweb | 1,006 | 56.05 |
Travel Insurance by an old RV'er
Why I Spend the Winter in Mexico
Travel Health Insurance
The first important rule of traveling away from your home territory, is do not leave without travel health insurance. If you are employed or otherwise a member of a group health plan, HMO, PPO, you need to check your policies to see if they will provide coverage during your trip.
The wording in most policies is that they will cover you to travel away from home and back and the policy must be effective before you leave. It is difficult to arrange for coverage once you are away from your home jurisdiction. An example, you have an annual policy with coverage for 30 days. You travel for 30 days in the U.S, but extend your stay an additional 90 days in Mexico. Then you decide you should buy more coverage to travel back to your home country, Canada. Good luck, because there are travel insurance companies out there who will sell you policies, but if you read the fine print, they only cover you when you leave from your home country. If you top up or extend your coverage before the 30 days are up, no problem. .
Travel Coverage is Only for Unforeseen Medical Problems:
Travel health insurance policies usually only pay expenses for unforeseen unanticipated medical problems or emergencies. A typical example of how they work is as follows:
You have a bad chest cold so you visit a clinic on your vacation out of country. The doctor prescribes medication and you seem to improve. If two weeks later, you develop pneumonia, it will NOT be covered by your policy. Another example, you have chest pains so go to an emergency clinic. They do numerous tests and decide you must have had a bad case of gas. If a week later you have a heart attack, it will probably NOT be covered. There is usually a time frame allowed after an illness for you to return home, most policies allow about 72 hours. Please don’t ever delay seeking treatment for any condition. Your health isn’t worth that risk: however, you need to consider the risks of continuing your vacation after any medical incident.
Verification and Pre-existing Conditions:
Many policies require very little information from you when initially issued. That does not mean that you will automatically be covered. Insurance companies will verify your medical history when you submit a claim. They will contact your family doctor to check for any pre-existing conditions.
Be sure to ask your doctor about all your medical test results, there may be a conditon that your doctor considered unimportant at the time, but the insurer may treat as a pre-existing. It doesn't matter that you didn't know about it.
Occasionally insurance policies have wording that if all pre-existing conditions are not disclosed they can void the policy entirely. Preferred wording is that they will disallow payment only for illness related to a pre-existing or unstable conditon.
If you have an annual travel insurance plan, you will need receipts to verify your departure date from your home province or state such as gas, airline and hotel receipts. It is up to you to ensure that you meet the qualifications for coverage.
If you seek medical treatment for any symptoms, and the symptoms abate without treatment, the insurance companies may also view the incident as a pre-existing condition. There are some policies with wording that any investigations of a symptom, regardless of the test results may be considered pre-existing.
Annual Travel Policies:
A word about annual travel policies. I have an annual policy and in order maintain coverage I must satisfy all the pre-exisiting conditon requirements every time I use it. If a policy states that your condition must be stable for the three months prior to a trip, that means no medical treatment or changes to symptoms or medication. That means every trip.
Notification Requirements:
As a general rule most insurers require notification when you seek medical treatment and often have preferred medical care providers. Most provide 1-800 numbers and other numbers for various countries. I have seen policies with onerous notification requirements. For instance, ambulance coverage only available if you phone a 1-800 number. If you need an ambulance, you may not have time or the ability to communicate with your insurer. Do not assume that the company will reimburse you for ambulance costs, if you were unable to notify them as required by the contract.
As a seasoned RV’er I have looked at many travel health insurance policies. Travel health polices generally provide the following coverages:
Generally included:
- Emergency hospital
- Emergency medical
- Meals and accommodations (certain instances and to set limits)
- Transportation of family or friend plus incidental costs depending on special circumstances and to set limits
- Return of traveling companion
- Return of vehicle or watercraft (certain instances and to set limits)
- Pet return (to set limits)
- Return of Deceased
- Accidental dental (certain instances and to set limits)
- Dental emergencies under certain instances
- Emergency transportation (air transport usually is pre-approved by insurer)
- Attendent (certain instances)
- Transport of patient back to his home country for further treatment (at the insurer’s discretion and expense)
- Return to original trip destination (certain instances and to set limits)
Generally excluded:
- Pre-existing conditions or unstable conditions as defined by your policy
- Elective procedures
- Cosmetic procedures
- Traveling against physicians advice
- Injuries from participating in dangerous sports
- Injuries due to metal illness
- Injuries or illness due to use of alcohol, drugs and etc.
- Treatment for continuation of illness/accident which could be reasonably delayed until return home
- Acts of terrorism or war
These are only a few of the possible exclusions. You must always read the fine print on your policy.
Payment for Services:
Whenever possible, do not negotiate with a hospital business manager. I have heard of cases where business managers have tried to bully patients into paying large cash deposits up front. Your insurance company is better able to negotiate fees with hospitals and medical care providers. Occasionally hospital business managers will try to obtain more than the amount your insurer will pay for the procedure. When cash payments for medical services are required, you will need to apply to your insurer for reimbursement.
It is all in the Insurance Policy or Contract:
I have nothing against the insurance industry or agents, but read your policy. The insurance company will only honor the contract and sometimes they will decline a claim for reimbursement on the first submission, but will pay on subsequent submissions. So, if coverage is denied, don't give up, resubmit your claim. I particularly detest this practice by some companies. They may do it on purpose to discourage some claiments when they have legitimate claims.
Note to Canadian Travellers:
I recently heard about a case where a woman was hospitalized during a vacation, and her insurer wanted to transfer her home. However, they were unable to find a hosptial bed. Firstly, this may cause an increase in travel health insurance costs for Canadians. Secondly, one wonders if a transport service like SkyMed would be useful. Services like this usually transport a stabalized patient and they require a doctor and hospital willing to admit the patient.
About the Author, Maggie - Internet Marketer - Insta-Health Quote & Wellness Guide and former RV'er. | https://hubpages.com/travel/Travel-Insurance-by-an-old-RVer | CC-MAIN-2018-22 | refinedweb | 1,240 | 51.58 |
For motivational purposes, let's start with a program that displays a DWM thumbnail.
Start with the scratch program and add the following:
#include <dwmapi.h> HWND g_hwndThumbnail; HTHUMBNAIL g_hthumb; void UpdateThumbnail(HWND hwndFrame, HWND hwndTarget) { if (g_hwndThumbnail != hwndTarget) { g_hwndThumbnail = hwndTarget; if (g_hthumb != nullptr) { DwmUnregisterThumbnail(g_hthumb); g_hthumb = nullptr; } if (hwndTarget != nullptr) { RECT rcClient; GetClientRect(hwndFrame, &rcClient); if (SUCCEEDED(DwmRegisterThumbnail(hwndFrame, g_hwndThumbnail, &g_hthumb))) { DWM_THUMBNAIL_PROPERTIES props = {}; props.dwFlags = DWM_TNP_RECTDESTINATION | DWM_TNP_VISIBLE; props.rcDestination = rcClient; props.rcDestination.top += 50; props.fVisible = TRUE; DwmUpdateThumbnailProperties(g_hthumb, &props); } } } }
The
UpdateThumbnail
function positions a thumbnail of the target window
inside the frame window.
There's a small optimization in the case that the
target window is the same one that the thumbnail
is already viewing.
Overall, no big deal.
void OnDestroy(HWND hwnd) { UpdateThumbnail(hwnd, nullptr); PostQuitMessage(0); }
When our window is destroyed, we need to clean up the thumbnail, which we do by updating it to a null pointer.
For the purpose of illustration, let's say that pressing the 1 key changes the thumbnail to a randomly-selected window.
struct RANDOMWINDOWINFO { HWND hwnd; int cWindows; }; BOOL CALLBACK RandomEnumProc(HWND hwnd, LPARAM lParam) { if (hwnd != g_hwndThumbnail && IsWindowVisible(hwnd) && (GetWindowStyle(hwnd) & WS_CAPTION) == WS_CAPTION) { auto prwi = reinterpret_cast<RANDOMWINDOWINFO *>(lParam); prwi->cWindows++; if (rand() % prwi->cWindows == 0) { prwi->hwnd = hwnd; } } return TRUE; } void ChooseRandomWindow(HWND hwndFrame) { RANDOMWINDOWINFO rwi = {}; EnumWindows(RandomEnumProc, reinterpret_cast<LPARAM>(&rwi)); UpdateThumbnail(hwndFrame, rwi.hwnd); } void OnChar(HWND hwnd, TCHAR ch, int cRepeat) { switch (ch) { case TEXT('1'): ChooseRandomWindow(hwnd); break; } } HANDLE_MESSAGE(hwnd, WM_CHAR, OnChar);
The random window selector selects among windows with a caption which are visible and which are not already being shown in the thumbnail. (That last bit is so that when you press 1, it will always pick a different window.)
Run this program, and yippee, whenever you press the 1 key, you get a new thumbnail.
Okay, but usually your program shows more than just a thumbnail. It probably incorporates the thumbnail into its other content, so let's draw some other content, too. Say, a single-character random message.
TCHAR g_chMessage = '?'; void PaintContent(HWND hwnd, PAINTSTRUCT *pps) { if (!IsRectEmpty(&pps->rcPaint)) { RECT rcClient; GetClientRect(hwnd, &rcClient); DrawText(pps->hdc, &g_chMessage, 1, &rcClient, DT_TOP | DT_CENTER); } } void ChooseRandomMessage(HWND hwndFrame) { g_chMessage = rand() % 26 + TEXT('A'); InvalidateRect(hwndFrame, nullptr, TRUE); } void OnChar(HWND hwnd, TCHAR ch, int cRepeat) { switch (ch) { case TEXT('1'): ChooseRandomWindow(hwnd); break; case TEXT('2'): ChooseRandomMessage(hwnd); break; } }
Now, if you press 2,
we change the random message.
There is a small optimiztion in
PaintContent that skips the rendering
if the paint rectangle is empty.
Again, no big deal.
Okay, but sometimes there are times where your program wants to update the thumbnail and the message at the same time. Like this:
void OnChar(HWND hwnd, TCHAR ch, int cRepeat) { switch (ch) { case TEXT('1'): ChooseRandomWindow(hwnd); break; case TEXT('2'): ChooseRandomMessage(hwnd); break; case TEXT('3'): ChooseRandomWindow(hwnd); ChooseRandomMessage(hwnd); break; } }
Run this program and press 3 and watch the thumbnail and message change simultaneously.
And now we have a problem.
You see, the
ChooseRandomWindow function updates
the thumbnail immediately,
since the thumbnail is presented by DWM,
whereas the
ChooseRandomMessage function updates
the message, but the new message doesn't appear on the screen
until the next paint cycle.
This means that there is a window of time where the new
thumbnail is on the screen, but you still have the old message.
Since painting is a low-priority activity,
the window manager is going to deliver other messages to your
window before it finally gets around to painting,
and the visual mismatch between the thumbnail and the message can
last for quite some time.
(You can exaggerate this in the sample program by inserting a
call to
Sleep.)
What can we do to get rid of this visual glitch?
One solution would be to delay updating the thumbnail until the next paint cycle. At the paint cycle, we update the thumbnail and render the new message. Now both updates occur at the same time, and you get rid of the glitch. To trigger a paint cycle, we can invalidate a dummy 1×1 pixel in the window.
HWND g_hwndThumbnailWanted; void PaintContent(HWND hwnd, PAINTSTRUCT *pps) { UpdateThumbnail(hwnd, g_hwndThumbnailWanted); if (!IsRectEmpty(&pps->rcPaint)) { RECT rcClient; GetClientRect(hwnd, &rcClient); DrawText(pps->hdc, &g_chMessage, 1, &rcClient, DT_TOP | DT_CENTER); } } void ChooseRandomWindow(HWND hwndFrame) { RANDOMWINDOWINFO rwi = {}; EnumWindows(RandomEnumProc, reinterpret_cast
(&rwi)); g_hwndThumbnailWanted = rwi.hwnd; RECT rcDummy = { 0, 0, 1, 1 }; InvalidateRect(hwndFrame, &rcDummy, FALSE); }
Now, when we want to change the thumbnail, we just
remember what thumbnail we want (the "logical" current
thumbnail)
and invalidate a dummy pixel in our window.
The invalid dummy pixel triggers a paint cycle,
and in our paint cycle, we call
UpdateThumbnail to synchronize
the logical current thumbnail with the physical
current thumbnail.
And then we continue with our regular painting
(in case there is also painting to be done, too).
But it sure feels wasteful invalidating a pixel
and forcing the
DrawText to occur
even though we really didn't update anything.
Wouldn't it be great if we could just say,
"Could you fire up a paint cycle for me,
even though there's technically nothing to paint?
Because I actually do have stuff to paint,
it's just something outside your knowledge
since it is not rendered by GDI."
Enter the
RDW_ flag.
If you pass the
RDW_ flag
to
RedrawWindow,
that means,
"Set the 'Yo, there's painting to be done!' flag.
I know you think there's no actual painting to be done,
but trust me on this."
(It's
not actually a flag, but you can think of it that way.)
When the window manager then get around to deciding whether
there is any painting to be done,
before it concludes,
"Nope, this window is all valid,"
it checks if you made a special
RDW_ request,
and if so, then it will generate
a dummy
WM_ message for you.
Using this new flag is simple:
g_hwndThumbnailWanted = rwi.hwnd; //
RECT rcDummy = { 0, 0, 1, 1 };// InvalidateRect(hwndFrame, &rcDummy, FALSE);RedrawWindow(hwndFrame, nullptr, nullptr, RDW_INTERNALPAINT);
Now, when the program wants to update its thumbnail,
it just schedules a fake-paint message with the window manager.
These fake-paint messages coalesce with real-paint messages,
so if you do an internal paint and an invalidation,
only one actual paint message will be generated.
If the paint message is a fake-paint message,
the
rcPaint will be empty,
and you can test for that in your
paint handler and skip your GDI painting.
How does RDW_INTERNALPAINT interact with UpdateWindow? I hope MSDN just dropped the ball and internal paints are honored there too…
And is there a corresponding mechanism to Validate Rect for saying thanks, but I changed my mind? Could not find anything.
Thanks, and keep it up please.
UpdateWindowrespects
RDW_INTERNALPAINT. Basically, setting the internal paint flag means "Act as if the update region is nonempty (even though it might actually be empty)." -Raymond]
Sorry, withdrawing my 2nd question, just found a flag for RedrawWindow.
BTW: Could you enlighten me why Microsoft splintered the API reference, so there are separate and conflicting copies mostly focused for all those versions? That makes it quite easy to look at the wrong docs and not realizing that parts dont apply to you and which ones. It also burries the right docs under nefarious false friends.
Well, haven't found two conflicting pages claiming the exact same systems yet. But taking RedrawWindow as an example, there are at least 6 pages, one each for: desktop, ce5, ce6, ce6.5, ce7compact, ce.net. All ce pages seem to contain the same basic info with few differences (dropped min versions/different ratings/possibility to add community content (not found any actual ommunity content for the ce pages)/sometimes linking to _one_ of the other pages/…). The only significant difference seems to be to the desktop page, which lists two more flags than the rest and has community contributions.
Are you sure if one of those pages is corrected for something, all the others will be done too? And how about missing the vital clue (hidden in community content on one of the pages you are not looking at just then), even if all the other content is completely reproduced? What i personally find most irritating is 1: having to hunt down the differences, complicated by the difficulty of moving from any page to corresponding pages in different sets, especially if porting/developing not only for Windows Y. and 2: Having my search for information on SomeApiFunctionOrFlag spammed by nearly right pages which might be dead wrong. Both parts lead to serious frustrations.
PS: Thanks for the answers you already gave.
I found RDW_INTERNALPAINT useful when rendering content on demand in WM_PAINT: Whenever the underlying content changes, I post an RDW_INTERNALPAINT message. Then, in WM_PAINT, I compute the updated layout and invalidate the regions affected by the changes before calling BeginPaint.
One thing I remember is that apparently you couldn't combine RDW_INTERNALPAINT with some other flags in a single call to RedrawWindow (possibly RDW_UPDATENOW, but I don't remember).
rs, I believe this is what Raymond is alluding to when he says "It's not actually a flag, but you can think of it that way."
I can't be bothered to look it up in the header file, but perhaps it's a combination of flags which would conflict with yours, or it's a magic constant, or something.
WM_PAINTmessage" is not a flag.
RDW_INTERNALPAINTis a flag. -Raymond]
Often the first msdn online help page VS shows of API calls when selecting a WinApi function and pressing F1 is a 5-10 year old Windows CE page, even when developing straight win32 apps.
"I meant that the thing that says "This window needs a WM_PAINT message" is not a flag. RDW_INTERNALPAINT is a flag. -Raymond"
I am sure I am not the only one that was initially confused both by the original wording in the article and this "clarification", which merely repeats the mistake of the article text. When reading: "The thing that says "…" etc", the "thing" I seem to be reading about is RDW_INTERNALPAINT. This creates an apparent contradiction when on the one hand you said "The thing … is not a flag." and then immediately after "[The thing] IS a flag".
I took me a couple of reads, both of the original and the clarification, to realise that what you were trying to say was:
Whilst RDW_INTERNALPAINT is a flag, the effect it has on the window manager is to trigger a message to be sent, not set a flag.
RedrawWindowand the one the window manager uses to remember that a paint message is needed. The second one is not actually a flag. -Raymond]
@msdn libb, yeah, it's a little annoying when you search Google or Bing and the first result is a CE hit, not a desktop hit. But they're getting better over time, and moving the desktop result up. I can't remember OTTOMH but there's slight differences in wordings in the summary you get on the search results page that lets you know whether it's desktop or CE versions of the function.
In regard to searching: They start favoring the desktop pages over arbitrary ce pages? Good for 'desktop' only developers, even though its not good enough until its reliable that you get the desktop page.
Still does not help anyone developing for ce-x.y or worse yet needing info from two or more split docs. In the last case you really want the differences highlighted.
@raymond: I intentionally said corrected not updated beecause updating could mean making things conform to an expanded new version of the api, while correcting only implies faulty docs (which might be duplicated inclusive any errors).
Surely it's much easier and less confusing to just say "There is only one flag. The mechanism it invokes doesn't involve a flag at all." ?
Unless you had tongue firmly inserted into cheek of course. :)
Not that is matters now. The ball has long since gone. :)
Great! I always follow this blog.
I think it will be very helpful, If you can share the whole application code by an Zip file as an attachement. Investigate the runtime behavior will be very helpful to understanding the code. | https://blogs.msdn.microsoft.com/oldnewthing/20130621-00/?p=4023/ | CC-MAIN-2017-22 | refinedweb | 2,056 | 53.41 |
I have a really good looking page that lists images and stuff from a certain Data Collection. Now I want to copy this page and make the other page get stuff from Data Collection but with other data.
I have a page called Ideas and one page called Projects. At the top I list images that are stored in my dataset. I connect the gallery to my dataset.
Now comes the magic with WIX Code, I now check what is the path of the page? mysite.com/ideas/ and mysite.com/projects/. So how can I just duplicate the page and make stuff on the page get set by data instead or hardcoded?
I get the path, I check if there is stuff in data collection tagged with this path, if it is I filter the dataset just displaying the images / galleri records that matches the path. This way I can use simple pages but insert and make some dynamic stuff as well.
import location from 'wix-location'; import wixData from 'wix-data'; $w.onReady(function () { let path = location.path; let filter = wixData.filter; let categoryName = path[0]; let searchFieldName = "categoryName"; let dataSet = "#ideas"; let dataCollection = "Ideas"; console.log("getting page records within category " + categoryName); wixData.query(dataCollection).eq(searchFieldName, categoryName).find().then((res) => { console.log(res); if (res.length > 0) { console.log("result found"); $w("#ideas").setFilter( filter() .eq(searchFieldName, categoryName) ); $w(dataSet).refresh(); } else { console.log("no records found"); // maybe set some default images? } }); }); | https://www.wix.com/corvid/forum/community-discussion/setting-filter-by-url-path | CC-MAIN-2019-47 | refinedweb | 246 | 61.12 |
Xamarin Forms splash screen on Android and iOS
Adding a splash screen to Android and iOS using a Xamarin Forms project isn't as long winded as you think it might be. iOS already has one and Android just requires another activity.
Adding the splash screen to Android:
Android will require another activity to be placed within your app, so within the droid project, create a new class file and name is SplashActivity.cs and add the following code:
using System.Threading.Tasks; using Android.App; using Android.Content; using Android.OS; using Android.Support.V7.App; namespace MyApp.Droid { ); } protected override void OnResume() { base.OnResume(); Task startupWork = new Task(() => { Task.Delay(2000); }); startupWork.ContinueWith(t => { StartActivity(new Intent(Application.Context, typeof (MainActivity))); }, TaskScheduler.FromCurrentSynchronizationContext()); startupWork.Start(); } } }
Then in your MainActivity.cs file change the MainLauncher attribute on the MainActivity class to false.
Now add a new file to /Resources/Drawable called splash_screen.xml and add the following:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:
<item>
<color android:
</item>
<item>
<bitmap
android:src="@drawable/applogo"
android:tileMode="disabled"
android:
</item>
</layer-list>
Change applogo to the name of your application splash screen image which should also be in the drawable folder (do not add the file extension to the filename). You can also change the background colour by changing the android:color="#ffffff" part of the file to represent your preferred colour.
Now under Resources/values, create a file called styles.xml and add the following to it:
<resources>
<style name="MyTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
</style>
<style name="MyTheme" parent="MyTheme.Base">
</style>
<style name="MyTheme.Splash" parent ="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash_screen</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
That's it for Android, wasn't so difficult was it? I was also surprised when I did it.
Adding the splash screen to iOS:
iOS already has a splash screen that displays a blue background and either a Xamarin logo or your app logo in the middle. This works but let's be honest, it looks horrible having your tiny app icon with perhaps a white background on a blue application background. Ugh.
The only step for making the Launch Screen look better is to open the the LaunchScreen.storyboard file under the /Resources folder. Double clicking the file should open the designer as long as you're connected to a mac.
From here you can click the logo in the center of the screen to change which image to display.
You can also click the background and type in a new background colour code. That should be it, recompile your app and you're good to go.
Published at 16 Aug 2016, 08:51 AM
Tags: Xamarin
| https://lukealderton.com/blog/posts/2016/august/xamarin-forms-splash-screen-on-android-and-ios/ | CC-MAIN-2022-40 | refinedweb | 462 | 51.65 |
As we all know web pages are stateless pages and we need to use session variables in web application to maintain some session over page. Some time we divide our application into multiple layers for example business logic layer,database layer etc. This all layers will be a class library projects.
So when you have your applications divided into the multiple layers at that time you might need to use session variables in the class library projects. For that we are adding System.Web namespace as a reference to a class library project and then we can use session with HttpContext object. That’s works fine if your layers are going to be used in web application projects. But for example if you have service oriented architecture and your services also access your class libraries via non standard protocol i.e. WCF Service hosted on TCP/IP bindings. At that time sessions will not work.
Instead of that you should always use the parameters in method and avoid direct use of session variables. That parameters will passed either from the web application or from the services which is calling the class libraries.
Hope you liked it. Stay tuned for more..
Wednesday, April 10, 2013
Your feedback is very important to me. Please provide your feedback via putting comments. | https://www.dotnetjalps.com/2013/04/Why-sometimes-it-not-a-good-idea-to-use-session-variables-in-class-library-project.html | CC-MAIN-2019-51 | refinedweb | 218 | 74.9 |
08 June 2011 17:48 [Source: ICIS news]
By Anna Jagger
LONDON (ICIS)--Thailand’s Indorama Ventures is studying purified terephthalic acid (PTA) and polyethylene terephthalate (PET) projects in the Middle East and India as part of plans to extend its global reach, founder and CEO Aloke Lohia said on Wednesday.
The proposed projects are part of the company’s plans to raise its global production capacity, for PTA, PET and fibres, to at least 10m tonnes/year from approximately 5.5m tonnes/year today, he told ICIS in a telephone interview.
This will be achieved both by building new capacities and through acquisitions, he said.
To achieve this goal, the company intends to invest approximately $2bn (€1.36bn) between now and the end of 2014, Lohia added.
Indorama Ventures has already announced expansions and acquisitions that will add about 1m tonnes/year of capacity, including the pending purchase of ?xml:namespace>
This means there is another 3.5m tonnes of capacity that has not been announced “and that is in the pipeline,” he remarked.
Announced projects include a PET expansion in
Lohia said the company is finalising plans to build a worldscale PTA/PET complex in the Middle East and another in
There may be a time lag between the start-up of the PTA and PET units, he noted, but the objective is to have integrated production.
Worldscale sizes for new PTA and PET plants are 1m-1.2m tonnes/year and 400,000-500,000 tonnes/year respectively, Lohia said.
He declined to discuss the locations of the
The company does not currently have assets in the Middle East or
Indorama Ventures expects to begin construction of the Middle East and
The company is also considering investment opportunities in PTA/PET and fibres in
“We would like to build a market leadership position in
($1 = €0.68)For more on Indorama | http://www.icis.com/Articles/2011/06/08/9467656/indorama-ventures-studies-mideast-india-ptapet-projects.html | CC-MAIN-2015-18 | refinedweb | 314 | 50.36 |
28 March 2012 07:33 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The company is also planning to start up the CDU’s auxiliary units during the same timeframe, the source said.
This includes a 2m tonne/year residue hydrogenation unit, a 2m tonne/year hydrocracker, a 2m tonne/year fluid catalytic cracker (FCC), a 1.5m tonne/year continuous reformer as well as a 500,000 tonne/year aromatics unit, according to the source.
The company will shut a 3.5m tonne/year CDU at the same site once the new facilities commence operations but will keep another 4.5m tonne/year CDU at the same site running, he added.
Yangzi Petrochemical is a subsidiary of state-owned refiner | http://www.icis.com/Articles/2012/03/28/9545413/chinas-yangzi-petrochemical-to-start-up-new-cdu-in-late.html | CC-MAIN-2014-35 | refinedweb | 120 | 58.28 |
As a part of our collaboration with freeCodeCamp, their eminent instructor Beau Carnes has turned their entire ES6 curriculum into an interactive Scrimba course which you can watch today.
As you might know, ES6 is just a way to describe newer JavaScript features that weren’t fully and widely accepted until 2017. Now, almost all JavaScript is written using ES6 features, so this course sets you up to become a modern JavaScript developer.
In this article, I’ll list out the chapters and give you a sentence or two about it. This way you should be able to quickly judge whether this course looks interesting to you.
If so, be sure to head over to Scrimba to watch it!
1. Introduction
In the first screencast, Beau gives you a quick intro to the course and himself and talks a little bit about ES6. He also shows you how you can find the curriculum if you’d like to go through it on the freeCodeCamp site as well.
2. Explore Differences Between the var and let Keywords
The first subject is variables. In ES5 we could only declare variables with
var, but starting with ES6 we can now use
let and
const.
How are
let and
var different?
let doesn’t allow you to declare a variable twice.
var catName = "Quincy"; var catName = "Beau"; // Works fine! let dogName = "Quincy"; let dogName = "Beau"; // Error: TypeError: unknown: Duplicate declaration "dogName"
3. Compare Scopes of the var and let Keywords
Another major difference between
var and
let is how they are scoped (freeCodeCamp’s guide on scope).
When you declare a variable with
var it is declared globally or locally if inside a function.
When it’s declared with
let it would be limited to a block statement or expression scope.
Beau shows you two examples.
4. Declare a Read-Only Variable with the const Keyword
const is a way to assign a read-only variable that cannot be reassigned.
const fcc = "freeCodeCamp"; const sentence = fcc + " is cool!"; sentence = fcc + " is amazing!"; // Error: SyntaxError: unknown: "sentence" is read-only
5. Mutate an Array Declared with const
You should be careful with
const, though as it is still possible to mutate arrays assigned with it.
const myArray = [5, 7, 2]; myArray[0] = 2; myArray[1] = 7; myArray[2] = 5; console.log(myArray); // [2, 7, 5]
Same applies to objects.
6. Prevent Object Mutation
In order to avoid object and array mutation, you can use
Object.freeze():
const MATH_CONSTANTS = { PI: 3.14 }; Object.freeze(MATH_CONSTANTS); MATH_CONSTANTS.PI = 99; // TypeError: Cannot assign to read-only property 'PI' of object '#<Object>'
If you wish to freeze arrays, you can also use
Object.freeze() and pass your array, but it might not work on some old browsers.
7. Use Arrow Functions to Write Concise Anonymous Functions
ES6 also introduces a shorter way of writing anonymous functions.
// ES5 anonymous function var magic = function() { return new Date(); }; // A shorter ES6 arrow function var magic = () => { return new Date(); }; // And we can shorten it even further var magic = () => new Date();
8. Write Arrow Functions with Parameters
Passing parameters to arrow functions is also easy.
var myConcat = (arr1, arr2) => arr1.concat(arr2); console.log(myConcat([1, 2], [3, 4, 5])); // [1, 2, 3, 4, 5]
9. Write Higher Order Arrow Functions
Arrow functions shine when used with higher order functions, like
map(),
filter(),
reduce().
10. Set Default Parameters for Your Functions
If some of our function parameters can be set to a default value, this is how you can do it in ES6:
// If value parameter is not passed in, it will be assigned to 1. function increment(number, value = 1) { return number + value; }; console.log(increment(5, 2)); // 7 console.log(increment(5)); // 6
11. Use the Rest Operator with Function Parameters
Rest operator allows you to create a function that takes a variable number of arguments.
function sum(...args) { return args.reduce((a, b) => a + b); }; console.log(sum(1, 2, 3)); // 6 console.log(sum(1, 2, 3, 4)); // 10
12. Use the Spread Operator to Evaluate Arrays In-Place
The spread operator looks exactly like the rest operator and looks like this:
…, but it expands an already existing array into individual parts.
const monthsOriginal = ['JAN', 'FEB', 'MAR']; let monthsNew = [...monthsOriginal]; monthsOriginal[0] = 'potato'; console.log(monthsOriginal); // ['potato', 'FEB', 'MAR'] console.log(monthsNew); // ['JAN', 'FEB', 'MAR']
13. Use Destructuring Assignment to Assign Variables from Objects
Destructuring is a special syntax for neatly assigning values taken directly from an object to a new variable.
// Object we want to destructure var voxel = {x: 3.6, y: 7.4, z: 6.54 }; // This is how we would do it in ES5 var a = voxel.x; // a = 3.6 var b = voxel.y; // b = 7.4 var c = voxel.z; // c = 6.54 // A shorter ES6 way const { x : a, y : b, z : c } = voxel; // a = 3.6, b = 7.4, c = 6.54
14. Use Destructuring Assignment to Assign Variables from Nested Objects
You can use destructuring to get values out of even nested objects:
const LOCAL_FORECAST = { today: { min: 72, max: 83 }, tomorrow: { min: 73.3, max: 84.6 } }; function getMaxOfTmrw(forecast) { "use strict"; // we get tomorrow object out of the forecast // and then we create maxOfTomorrow with value from max const { tomorrow : { max : maxOfTomorrow }} = forecast; return maxOfTomorrow; } console.log(getMaxOfTmrw(LOCAL_FORECAST)); // 84.6
15. Use Destructuring Assignment to Assign Variables from Arrays
Do you wonder if destructuring can be used with arrays? Absolutely! There is one important difference though. While destructuring arrays, you cannot specify a value you wish to go into a specific variable and they all go in order.
const [z, x, , y] = [1, 2, 3, 4, 5, 6]; // z = 1; // x = 2; // Skip 3 // y = 4;
16. Use Destructuring Assignment with the Rest Operator to Reassign Array Elements
Let’s now combine the rest operator with destructuring to supercharge our ES6 skills.
const list = [1,2,3,4,5,6,7,8,9,10]; // Create a and b out of first two members // Put the rest in a variable called newList const [ a, b, ...newList] = list; // a = 1; // b = 2; // newList = [3,4,5,6,7,8,9,10];
17. Use Destructuring Assignment to Pass an Object as a Function’s Parameters
We can create more readable functions.
const stats = { max: 56.78, standard_deviation: 4.34, median: 34.54, mode: 23.87, min: -0.75, average: 35.85 }; // ES5 function half(stats) { return (stats.max + stats.min) / 2.0; }; // ES6 using destructuring function half({max, min}) { return (max + min) / 2.0; }; console.log(half(stats)); // 28.015
18. Create Strings using Template Literals
Template literals help us to create complex strings. They use a special syntax of
`` and
${} where you can combine template text with variables together. For example
`Hello, my name is ${myNameVariable} and I love ES6!`
const person = { name: "Zodiac Hasbro", age: 56 }; // Template literal with multi-line and string interpolation const greeting = `Hello, my name is ${person.name}! I am ${person.age} years old.`; console.log(greeting);
19. Write Concise Object Literal Declarations Using Simple Fields
ES6 added support for easily defining object literals.
// returns a new object from passed in parameters const createPerson = (name, age, gender) => ({ name: name, age: age, gender: gender }); console.log(createPerson("Zodiac Hasbro", 56, "male")); // { name: "Zodiac Hasbro", age: 56, gender: "male" }
20. Write Concise Declarative Functions with ES6
Objects in JavaScript can contain functions.
const ES5_Bicycle = { gear: 2, setGear: function(newGear) { "use strict"; this.gear = newGear; } }; const ES6_Bicycle = { gear: 2, setGear(newGear) { "use strict"; this.gear = newGear; } }; ES6_Bicycle.setGear(3); console.log(ES6Bicycle.gear); // 3
21. Use class Syntax to Define a Constructor Function
ES6 provides syntax to create objects using the
class keyword:
var ES5_SpaceShuttle = function(targetPlanet){ this.targetPlanet = targetPlanet; } class ES6_SpaceShuttle { constructor(targetPlanet){ this.targetPlanet = targetPlanet; } } var zeus = new ES6_SpaceShuttle('Jupiter'); console.log(zeus.targetPlanet); // 'Jupiter'
22. Use getters and setters to Control Access to an Object
With an object, you often want to obtain values of properties and set a value of a property within an object. These are called getters and setters. They exist to hide some underlying code, as it should not be of concern for anyone using the class.
class Thermostat { // We create Thermostat using temperature in Fahrenheit. constructor(temp) { // _temp is a private variable which is not meant // to be accessed from outside the class. this._temp = 5/9 * (temp - 32); } // getter for _temp get temperature(){ return this._temp; } // setter for _temp // we can update temperature using Celsius. set temperature(updatedTemp){ this._temp = updatedTemp; } } // Create Thermostat using Fahrenheit value const thermos = new Thermostat(76); let temp = thermos.temperature; // We can update value using Celsius thermos.temperature = 26; temp = thermos.temperature; console.log(temp) // 26
23. Understand the Differences Between import and require
In the past, we could only use
require to import functions and code from other files. In ES6 we can use
import:
// in string_function.js file export const capitalizeString = str => str.toUpperCase() // in index.js file import { capitalizeString } from "./string_function" const cap = capitalizeString("hello!"); console.log(cap); // "HELLO!"
24. Use export to Reuse a Code Block
You would normally
export functions and variables in certain files so that you can import them in other files — and now we can reuse the code!
const capitalizeString = (string) => { return string.charAt(0).toUpperCase() + string.slice(1); } // Named export export { capitalizeString }; // Same line named export export const foo = "bar"; export const bar = "foo";
25. Use * to Import Everything from a File
If a file exports several different things, you can either import them individually, or you can use
* to import everything from a file.
This is how you would import all the variables from the file in the previous exercise.
import * as capitalizeStrings from "capitalize_strings";
26. Create an Export Fallback with export default
We looked at named exports in previous chapters and sometimes there might be a single function or a variable that we want to export from a file —
export default, often used as a fallback export too.
// In math_functions.js file export default function subtract(x,y) { return x - y; }
27. Import a Default Export
If you wish to import
export default function from the previous exercise, this is how you would do it.
Note the absence of
{} around the
subtract function. Default exports don’t need them.
// In index.js file import subtract from "math_functions"; subtract(7,4); // returns 3;
28. JavaScript ES6 Outro
If you’ve reached this far: congratulations! Most people who start courses never finish them, so you can be proud of yourself.
If you’re looking for your next challenge, you should check out Beau’s course on Regex here!
Good luck! :)<< | https://www.freecodecamp.org/news/learn-modern-javascript-in-this-free-28-part-course-7ec8d353eb/ | CC-MAIN-2019-43 | refinedweb | 1,773 | 59.09 |
PITA::XML::SAXDriver - Implements a SAX Driver for PITA::XML objects
Although you won't need to use it directly, this class provides a "SAX Driver" class that converts a PITA::XML object into a stream of SAX events (which will mostly likely be written to a file).
Please note that this class is incomplete at this time. Although you can create objects, you can't actually run them yet.
# Create a SAX Driver to generate in-memory $driver = PITA::XML::SAXDriver->new(); # ... or to stream (write) to a file $driver = PITA::XML::SAXDriver->new( Output => 'filename' ); # ... or to send the events to a custom handler $driver = PITA::XML::SAXDriver->new( Handler => $handler );
The
new constructor creates a new SAX generator for PITA-XML files.
It takes a named param of EITHER an XML Handler object, or an
Output value that is compatible with XML::SAX::Writer.
Returns a
PITA::XML::SAXDriver object, or dies on error.
The
NamespaceURI returns the name of the XML namespace being used in the file generation.
While PITA is still in development, this should be something like the following, where
$VERSION is the PITA::XML version string.
The
Prefix returns the name of the XML prefix being used for the output.
The
Handler returns the SAX Handler object that the SAX events are being sent to. This will be or the SAX Handler object you originally passed in, or a XML::SAX::Writer object pointing at your
Output value.
If you did not provide a custom SAX Handler, the
Output accessor returns the location you are writing the XML output to.
If you did not provide a
Handler or
Output param to the constructor, then this returns a
SCALAR reference containing the XML as a string.
Bugs should be reported via the CPAN bug tracker at
For other issues, contact the author.
Adam Kennedy <adamk@cpan.org>,
PITA::XML, PITA::XML::SAXParser
The Perl Image-based Testing Architecture ()
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the LICENSE file included with this module. | http://search.cpan.org/~adamk/PITA-XML-0.52/lib/PITA/XML/SAXDriver.pm | CC-MAIN-2014-52 | refinedweb | 361 | 62.27 |
Never Mind the Namespaces: An XSLT RSS Client
:
- Most XSLT processors can read remote documents using XSLT's document() function; our stylesheet will use it to retrieve the news feeds from their servers.
- Converting the RSS elements and attributes to HTML for display by the browser.
- Using the local-name() function to create template rules that don't care about the namespace of RSS elements such as channel, item, and link.:
- This doesn't work with Mozilla, which, as of release 1.2.1, still has some kinks in its implementation of the document() function.
- I'd hoped to put the XML file and its stylesheet on a public server so that you could just link to it from this article to see it in action, but I got an "Access denied" message when the stylesheet tried to use the document() function to retrieve a document from a different server. This could be a security precaution in IE's XSLT implementation.:
- The first is for the root RSSChannels element of the main document that holds the RSS feed URIs. It does the basic setup of the result HTML document, including the addition of a CSS stylesheet.
- The short second template rule acts on an RSSChannel element, using the XSLT document() function to read in the document named by the element's src attribute. The stylesheet assumes that the document being read is an RSS document, and the stylesheet uses the remaining three template rules to transform the elements of the RSS document read in by the document() function into HTML.
- The third template rule's xsl:template element has a name attribute instead of a match attribute, making it a named template rule that must be explicitly called from a template rule. Because the fourth and fifth template rules surround their result contents with an HTML a element of a similar structure, the common code is stored in this named template. Note how the xsl:apply-templates instruction uses the local-name() function to selectively identify which element types to use for attribute values in the result.
- The fourth template rule outputs the name of an RSS channel -- typically, the title of the news channel such as "XML.com" or "InfoWorld: Top News" -- as an HTML h1 element. The h1 element wraps an a element that links back to the main page of the site using the URI named in the channel element's link child element. The a element includes the description of the channel in a title element so that when the resulting HTML is displayed using recent releases of Internet Explorer, Mozilla, or Opera, a
mouseOverevent displays that description in a pop-up box. The actual a element is output with a call to the "a-element" named template.
- The last template rule outputs an HTML p element containing a link to a particular news item. It uses the RSS item element's link and description child elements the same way that the preceding template rule does, which is why the creation of the a element with these attributes was moved to a separate template rule that these two both call. This final template rule adds one more bit of information: if a dc:date element is supplied with the news item, the template rule adds that to the result tree as plain text.!
2007-11-15 12:43:06 vpolite
I'm new to XML and need to do a newsreader. Forgive me my errors. How do I put this client in a HTML page
2007-11-15 12:49:38 Bob DuCharme
You don't put it in an HTML page; it creates HTML pages, so you incorporate it into whatever tool is creating your HTML pages.
- Help pt.2
2007-11-15 17:34:07 vpolite
I modified this page for my own use, well governmental use. The link to the actual xml is:
I get an error message that there is a missing"';'. " in the area of the '&location'. Any idea what that could mean? Thanks for helping a newbie along.
- Help pt.2
2007-11-15 17:37:47 Bob DuCharme
It thinks that "location" is an entity reference for which you forget the closing delimiter. If any of that doesn't make sense, then you need to learn some more basic aspects of XML before you get too far into an application like that.
I think that the mailing list would be a better place for such questions.
- Help pt.2
2007-12-17 13:41:28 SVanya
What I found to work is to reorganize the xml to make the "src" a child of RSSChannel and then wrap it as a CDATA and then have the xsl applied to ./src instead of @src. This has an added benefit (and how I found it) in that it can now read ampersands, such a google (news) searches, etc., that don't end in .xml or .rss Thank you, Bob, for this! Note: it also helps to drop it into a frameset and have the a-link point to the right frame. Ciao!
- Sharepoint WSS 3.0 & RSS client
2007-08-09 02:18:09 pdigs
Hi,
Sharepoint MOSS has a built-in RSS viewer - however, the free Sharepoint (WSS 3.0) does not.
I used your xslt RSS client to make an RSS viewer for Sharepoint WSS 3.0.
I ran it using javascript on the client in IE6.
It works great.
Thanks for sharing your efforts.
-KR, Pdigs
- Saxon through the firewall
2003-10-22 13:03:31 Scott Hudson
For those trying to process the above examples from the command line behind a firewall, try:
java -Dhttp.proxyHost=servername -Dhttp.proxyPort=8080 com.icl.saxon.StyleSheet RSSChannels.xml getRSS2.xsl > headlines.html
where servername is your favorite proxy host...
- Aggregation versus merely displaying
2003-01-09 08:58:12 Damian Cugley
Displaying RSS feeds organized by their originator is simple enough; that's what my.netscape.com did in the olden days. Displaying them organized by DATE is harder. Much harder, because RSS 0.91 does not include per-item date fields at all!
The only solution to this is to poll RSS feeds periodically and see if you can spot additions; this way you can tag items with the date you discovered them, which is approximatly the same as their publication date.
This does not really work if items can be expected to change, since in that case you don't have any deterministic way to work out if a given item is new or is an old item edited. Giving items their own permanent URIs helps, but that is also not an RSS 0.91 feature, alas!
On top of this, regular polling makes for bandwidth issues. Your program had better know about caching and ETags and If-Modified-Since and the various which-RSS-has-changed-recently services if it is to be a good WWW citizen.
All of this means that a really good RSS aggregator has to be a fairly tricky piece of software. Don't get me wrong, XSLT is a great tool (and I use it every day) but RSS as a format has too many features that defeat any elegant solution... :-(
- Re: RSS xslt, not quite so simple
2003-01-08 13:42:23 Bob DuCharme
Well, it's not trying to be a complete all-around RSS processor, pluggable into other apps; it pulls out information that it reasonably expects to find and uses it to create something useful.
I missed Mike Champion's Wednesday talk at XML 2002 (see ; the slides are somewhere on that site, but I can't find them right now) but I really liked how his accompanying paper (on the conference CD) used RSS as an example of how much can get done when by concentrating on the needs of the receiving side of an XML transmission. My needs were similar to those of a lot of RSS use, and very simple: I wanted to display, in a web browser, story titles with descriptions and links to the stories from a variety of providers. It won't work with all the RSS out there, but it works with enough RSS to make it useful.
I could have made it even simpler (left out the date, etc.) and certainly could have made it richer and more bullet-proof (use more RSS information, do more error-checking, etc.). I hope that in its present state it will give a head start to XSLT developers who want to take advantage of RSS feeds.
Bob
- RSS xslt, not quite so simple
2003-01-08 00:09:59 bryan rasmussen
Although I agree that local-name() is a help when dealing with the whole RSS mess, this stylesheet just scratches the surface, this is no doubt it's purpose, but as a surface scratcher it doesn't seem to me that you can note how little code it took when there is quite a bit more to be done.
For example, when you do an if test="dc:date" under item, if you actually wanted to check about the date you would have to support pubDate in RSS 2.0, dc:date in RSS 1.0 and it looks like nothing in the earlier versions.
I suppose the best thing would be choose, when dc:date use dc:date otherwise use pubDate.
That's a quibble I suppose but the fact that your strategy here depends on skipping the description of an item can be seen as an indication of where XSLT is going to have problems, since description in certain RSS versions can have escaped html inside of it.
As can be seen here:
most of the time, as in the example above this is to put in a link so it would be possible, if tedious, to parse out the a tags as text and create actual links from them, however in some RSS feeds, I'm thinking of that of Jon Udell, description is filled with so much variant html it's pretty much inconceivable that one should want to work with it.
As you indicated people can use the RSS as they want, but once one gets beyond the tagset you have chosen to work with here RSS is something that quickly can cause an increase in xslt code, despite the relative simplicity of any individual RSS spec. | http://www.xml.com/pub/a/2003/01/02/tr.html | crawl-003 | refinedweb | 1,741 | 66.67 |
rubicon.objc’s problem
latest when i try rubicon_objc.
the code below, run once is normal. run anther time will raise a err.
how can i solve it? thanks in advance
RuntimeError: An Objective-C class named b'Handler' already exists
code:
from rubicon.objc import NSObject, objc_method
class Handler(NSObject):
@objc_method
def initWithValue_(self, v: int):
self.value = v
return self
@objc_method def pokeWithValue_andName_(self, v: int, name) -> float: print("My name is", name) return v / 2.0
my_handler = Handler.alloc().initWithValue(42)
I'm not sure how Rubicon handles things -- for objc_util, the way it handles that is by renaming the objc class -- so if you define Handler again, it will create a class called Handler1. There is a debug flag that allows this. The problem is that objc runtime does not allow deletion of classes or creating a new class with the same name.
That only works if your class is stable -- if you need to change it, you will have to force quit the app.
For reference, @JonB has opened an issue for this feature on the rubicon.objc issue tracker: | https://forum.omz-software.com/topic/6447/rubicon-objc-s-problem | CC-MAIN-2021-49 | refinedweb | 185 | 67.65 |
the entry points for open() and close() functions in block device drivers. See Chapter 15, Drivers for Character Devices for more information on open(9E) and close(9.
Example 16-2 Block Driver open(9E) Routine by the number of block opens and layered opens.
Example 16-3 Block Device close(9E) Routine
static int xxclose(dev_t dev, int flag, int otyp, cred_t *credp) { minor_t instance; struct xxstate *xsp; instance = getminor(dev); xsp = ddi_get_soft_state(statep, instance); if (xsp == NULL) return (ENXIO); mutex_enter(&xsp->mu); switch (otyp) { case OTYP_LYR: xsp->nlayered--; break; case OTYP_BLK: xsp->open = 0; break; default: mutex_exit(&xsp->mu); return (EINVAL); } if (xsp->open || xsp->nlayered) { /* not done yet */ mutex_exit(&xsp->mu); return (0); } /* cleanup (rewind tape, free memory, etc.) */ /* wait for I/O to drain */ mutex_exit(&xsp->mu); return (0); } */
where:
Pointers that the driver can use to manage a list of buffers by the driver. See Asynchronous Data Transfers (Block Drivers) for a discussion of the av_forw and av_back pointers.
Specifies the number of bytes to be transferred by the device.
The kernel virtual address of the data buffer. Only valid after bp_mapin(9F) call.
The starting 32-bit logical block number on the device for the data transfer, which is expressed in 512-byte DEV_BSIZE units. The driver should use either b_blkno or b_lblkno but not both.
The starting 64-bit logical block number on the device for the data transfer, which is expressed in 512-byte DEV_BSIZE units. The driver should use either b_blkno or b_lblkno but not both.
Set by the driver to indicate the number of bytes that were not transferred because of an error. See Example 16-7 for an example of setting b_resid. The b_resid member is overloaded. b_resid is also used by disksort(9F).
Set to an error number by the driver when a transfer error occurs. b_error is set in conjunction with the b_flags B_ERROR bit. See the Intro(9E) man page for details about error values. Drivers should use bioerror(9F) rather than setting b_error directly.
Flags with status and transfer attributes of the buf structure. If B_READ is set, the buf structure indicates a transfer from the device to memory. Otherwise, this structure indicates a transfer from memory to the device. If the driver encounters an error during data transfer, the driver should set the B_ERROR field in the b_flags member. In addition, the driver should provide a more specific error value in b_error. Drivers should use bioerror(9F) rather than setting B_ERROR.
For exclusive use by the driver to store driver-private data.
Contains the device number of the device that was used in the transfer. Chapter 9,. | http://docs.oracle.com/cd/E23824_01/html/819-3196/block-6.html | CC-MAIN-2015-22 | refinedweb | 443 | 65.62 |
29 October 2010 07:11 [Source: ICIS news]
By Malini Hariharan and Becky Zhang
MUMBAI (ICIS)--Spot paraxylene (PX) and purified terephthalic acid (PTA) prices in ?xml:namespace>
Based on ICIS data, PX hit a two-year high of $1,265-1,275/tonne (€911-918/tonne) CFR (cost and freight) China/Taiwan in mid-October, while PTA touched a 26-month high of $1,035-1,065/tonne CFR China, on the back of strong demand.
PX was trading softer on Friday at $1,235/tonne CFR China/Taiwan, but would still likely post week-on-week gains, market sources said. PTA, on the other hand, was being quoted at $1,040-1,065/tonne CFR China this week, they said.
PX and PTA logged increases of 9.3 % and 11.4%, respectively, since the start of the year, while polyester staple fibre prices (PSF) for 1.4 denier had risen 30% over the same period to $1,570/tonne FOB (free on board)
PSF economics had reversed since the second quarter mainly because of brisk demand, said two Chinese producers.
Domestic PSF margins in
“Everyone is wondering what’s going on? We are back to square one now; across the chain prices are looking the same as January 2008,” said Leonard de Guzman of consultancy Dewitt & Co.
Recent plant shutdowns/troubles that cut PX supply helped producers raise prices, successfully raising the PX-naphtha spreads to more than $450/tonne in October from around $250/tonne last quarter.
“PX producers are at last getting a piece of the profit; it is finally tight,” de Guzman said.
Operating hitches at PX facilities of CNOOC Kings, Fujia Dahua and Oman Aromatics, along with a reduction in Iranian exports following the country’s decision to feed reformate straight to gasoline production had.
Cotton, which has been on an upward spiral since early this year, moved even higher after the August floods in
Earlier this week, December futures hit a 140-year high of $1.29/lb on the Intercontinental Exchange (ICE), on strong demand from
While this has, on paper, created room for further price hikes along the polyester chain, market players said the outlook remained hazy.
There were concerns that cotton would see a price correction as it was overvalued.
“The current high prices could also result in new acreage being added which would result in higher cotton production next year,” said a leading polyester producer.
But the cotton shortage could last until next August and final volumes would also depend on weather condition.
"We don't see much potential downside for cotton prices," said a major Taiwanese polyester producer.
Upstream,
But de Guzman said he.”
“It is going to get bloody,” he warned.
He also pointed out that polyester buyers were resisting paying higher prices.
“They would rather shut down; they can’t afford to pay more,” he said.
Further downstream, Chinese textile factories were reluctant to accept spikes in costs of cotton and polyester.
"They have slowed down purchasing because price increases of end-products cannot catch up with the jumps in raw materials," said a Chinese polyester maker.
Transaction volumes at the
Meanwhile, de Guzman said that the PTA and PX markets may not see much support from crude oil values, which he expected to remain in the $70-80 range in the fourth quarter.
“Some people are projecting $95/bbl, but we do not see it happening when the
At noon, US crude futures were trading at $81.75/bbl, down 43 cents/bbl from Thursday amid declines in leading Asian equity markets.
With additional reporting by Bohan Loh
( | http://www.icis.com/Articles/2010/10/29/9405645/asia-px-pta-rally-may-fizzle-out-on-demand-fundamentals.html | CC-MAIN-2014-52 | refinedweb | 603 | 60.55 |
std::ranges::cend
Returns a sentinel indicating the end of a const-qualified range.
Let
CT be
- const std::remove_reference_t<T>& if the argument is a lvalue (i.e.
Tis an lvalue reference type),
- const T otherwise,
a call to
ranges::cend is expression-equivalent to ranges::end(static_cast<CT&&>(t)).
If ranges::cend(e) is valid for an expression e, where decltype((e)) is
T, then
CT models std::ranges::range, and std::sentinel_for<S, I> is true in all cases, where
S is decltype(ranges::cend(e)), and
I is decltype(ranges::cbegin(e)).
::cend denotes a customization point object, which is a const function object of a literal semiregular class type (denoted, for exposition purposes, as
cend_ftor). All instances of
cend_ftor are equal. Thus,
ranges::cend can be copied freely and its copies can be used interchangeably.
Given a set of types
Args..., if std::declval<Args>()... meet the requirements for arguments to
ranges::cend above,
cend_ftor will satisfy std::invocable<const cend_ftor&, Args...>. Otherwise, no function call operator of
cend_ftor participates in overload resolution.
[edit] Example
#include <algorithm> #include <iostream> #include <ranges> #include <vector> int main() { std::vector<int> v = { 3, 1, 4 }; namespace ranges = std::ranges; if (ranges::find(v, 5) != ranges::cend(v)) { std::cout << "found a 5 in vector v!\n"; } int a[] = { 5, 10, 15 }; if (ranges::find(a, 5) != ranges::cend(a)) { std::cout << "found a 5 in array a!\n"; } }
Output:
found a 5 in array a! | https://en.cppreference.com/w/cpp/ranges/cend | CC-MAIN-2020-50 | refinedweb | 247 | 57.87 |
7
Creating Custom Modules
Shop at Packt Publishing To Buy This Book Online!
In this chapter, we are going to walk you through creating a custom module for the CoffeeConnections portal. A custom module can consist of one or more custom web controls. The areas we will cover are:
· Creating a private assembly project to build and debug your module
· Creating View and Edit controls
· Adding additional options to the module settings page
· Implementing the IActionable , ISearchable , and IPortable interfaces
· Using the Dual List Control
· Creating a SQLDataProvider
· Packaging your module
· Uploading your module
Coffee Shop Listing Module Overview
One of the main attractions for the CoffeeConnections portal is that users will be able to search, by zip code, for coffee shops in their area. After searching, the users will be presented with the shops in their area. To allow the focus of this chapter to be on module development, we will present a simplified version of this control. We will not spend time on the ASP.NET controls used or validation of these controls, instead we will focus only on what is necessary to create your own custom modules.
Setting Up Your Project (Private Assembly)
The design environment we will be using is Visual Studio .NET 2003. The files used in DotNetNuke come pre-packaged as a VS.NET solution and it is the best way to create custom modules for DotNetNuke. Visual Studio will allow us to create private assemblies (PA ) which will keep our custom module code separate from the DotNetNuke framework code.
A private assembly is an assembly (.dll or .exe ) that will be deployed along with an application to be used in conjunction with that application. In our case, the main application is the DotNetNuke core framework. The private assembly will be a project that is added to the DotNetNuke solution (.sln ). This will keep our module architecture separate from the DotNetNuke core architecture but will allow us to use Visual Studio to debug the module within the framework. Since building our modules in a PA allows us to have separation from the DotNetNuke core framework, upgrading to newer versions of DotNetNuke is a simple process.
Even though the DotNetNuke framework is built using VB.NET, you can create your module private assemblies using any .NET language. Since your module logic will be compiled to a .dll , you can code in the language you like.
The DotNetNuke project is divided into many different solutions enabling you to work on different parts of the project. We have already seen the HTTP Module solution and the Providers solutions. Since we want to look at the default modules that have been packaged with DotNetNuke we will be using the DotNetNuke.DesktopModules solution.
You can even create a new solution and add the DotNetNuke project to the new solution. You would then need to create a build support project to support your modules. We are using the DotNetNuke.DesktopModules solution so that you are able to look at the default modules for help in design process.
To set up your private assembly as part of the DotNetNuke.DesktopModules solution, take the following steps:
1. Open up the DotNetNuke Visual Studio.NET solution file (C:\DotNetNuke\Solutions\DotNetNuke.DesktopModules\DotNetNuke.DesktopModules.sln ).
2. In the Solution Explorer, right-click on the DotNetNuke solution (not the project) and select Add | New Project :
3. In Project Types , make sure that Visual Basic Projects is highlighted and select Class Library as your project type. Our controls are going to run in the DotNetNuke virtual directory, so we do not want to create a web project. This would create an additional virtual directory that we do not need.
4. Your project should reside under the C:\DotNetNuke\DesktopModules folder. Make sure to change the location to this folder.
5. The name of your project should follow the following convention. CompanyName.ModuleName . This will help avoid name conflicts with other module developers. Ours is named EganEnterprises.CoffeeShopListing . You should end up with a new project added to the DotNetNuke solution.
If you have installed URLScan, which is part of Microsoft's IIS Lockdown Tool, you will have problems with folders that contain a period (. ). If this is the case, you can create your project using an underscore instead of a period. Refer to for more information on the IIS Lockdown Tool.
6. You need to modify a few properties to allow you to debug our project within the DotNetNuke solution:
· In the Common Properties folder, under the General section remove the Root namespace . Our module will be running under the DotNetNuke namespace, so we do not want this to default to the name of our assembly.
· Delete the Class1.vb file that was created with the project.
· Right-click on our private assembly project and select Properties .
7. In the Common Properties folder, under the Imports subsection , we want to add imports that will help us as we create our custom module. Enter each of the namespaces below into the namespace box and click on Add Import .
· DotNetNuke
· DotNetNuke.Common
· DotNetNuke.Common.Utilities
· DotNetNuke.Data
· DotNetNuke.Entities.Users
· DotNetNuke.Framework
· DotNetNuke.Services.Exceptions
· DotNetNuke.Services.Localization
· DotNetNuke.UI
8. Click OK to save your settings
When we run a project as a private assembly in DotNetNuke, the DLL for the module will build into the
DotNetNuke bin
directory. This is
where DotNetNuke will look for
the assembly when it tries to load your module. To accomplish this, there is a project called BuildSupport inside each of the solutions. The BuildSupport project is responsible for taking the DLL that is created by your project and adding it to the DotNetNuke solution's bin folder.
To allow the BuildSupport project to add our DLL, we need to add a reference to our custom module project.
1. Right-click on the reference folder located below the BuildSupport project and select Add Reference .
2. Select the Projects tab.
3. Double-click on the EganEnterprises.CoffeeShopListing project to place it in the Selected Components box.
4. Click OK to add the reference.
Finally, we want to be able to use all of the objects available to us in DotNetNuke within our private assembly, so we need to add a reference to DotNetNuke in our project.
1.
Right-click on the reference folder located
below the EganEnterprises
.CoffeeShopListing private assembly project we just created and select Add Reference .
2. Select the Projects tab.
3. Double-click on the DotNetNuke project to place it in the Selected Components box.
4. Click OK to add the reference.
Before moving on, we want to make sure that we can build the solution without any errors. We will be doing this at different stages in development to help us pinpoint any mistakes we make along the way.
After building the solution, you should see something similar to the following in your output window.
---------------------- Done ----------------------
Build: 35 succeeded, 0 failed, 0 skipped
The number you have in succeeded may be different but make sure that there is a zero in failed . If there are any errors fix them before moving on.
Creating Controls Manually in Visual Studio
When using a Class Library project as a starting point for your private assembly, you cannot add a Web User Control to your project by selecting Add | New Item from the project menu. Because of this we will have to add our controls manually.
An optional way to create the user controls needed is to create a Web User Control inside the DotNetNuke project and then drag the control to your PA project to make modifications.
Creating the View Control
The View control is what a non-administrator sees when you add the module to your portal. In other words, this is the public interface for your module.
Let's walk through the steps needed to create this control.
1. Making sure that your private assembly project is highlighted, select Add New Item from the Project menu.
2. Select Text File from the list of available templates and change the name to ShopList.ascx .
3. Click Open to create the file.
4. Click on the HTML tab and add the following directive to the top of the page:
<%@ Control language="vb" AutoEventWireup="false"
Inherits="EganEnterprises.CoffeeShopListing.ShopList"
CodeBehind="ShopList.ascx.vb"%>
Directives can be located anywhere within the file, but it is standard practice to place them at the beginning of the file. This directive sets the language to VB.NET and specifies the class and code-behind file that we will inherit from.
5. Click the save icon on the toolbar to save the page.
6.
In the Solution Explorer right-click on the ShopList.ascx
file and select
View Code .
This will create a code-behind file for the Web User Control that we just created. The code-behind file follows the format of a normal Web User Control that inherits from System.Web.UserControl . This control, though based on Web.UserControl , will instead inherit from a class in DotNetNuke. Change the code-behind file to look like the code that follows. Here is the code-behind page in its entirety minus the Web Form Designer Generated Code:
Imports DotNetNuke
Imports DotNetNuke.Security.Roles
Namespace EganEnterprises.CoffeeShopListing
Public MustInherit Class ShopList
Inherits Entities.Modules.PortalModuleBase
Implements Entities.Modules.IActionable
Implements Entities.Modules.IPortable
Implements Entities.Modules.ISearchable
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
End Sub
Public ReadOnly Property ModuleActions() As _
DotNetNuke.Entities.Modules.Actions.ModuleActionCollection _
Implements DotNetNuke.Entities.Modules.IActionable.ModuleActions
Get
Dim
End Property
End Class
End Namespace
Let's break up the code listing above so that we can better understand what is happening in this section. The first thing that we do is add an Imports statement for DotNetNuke and DotNetNuke.Security.Roles so that we may access their methods without using the fully qualified names.
Imports DotNetNuke
Imports DotNetNuke.Security.Roles
Namespace EganEnterprises.CoffeeShopListing
Next, we add the
namespace to the class and set it to inherit from Entities.Modules
.PortalModuleBase . This is the base class for all module controls in DotNetNuke. Using the base class is what gives our controls consistency and implements the basic module behavior like the module menu and header. This class also gives us access to useful items such as User ID, Portal ID, and Module ID among others.
This section then finishes up by implementing three different interfaces. These interfaces allow us to add enhanced functionality to our module. We will only be implementing the IActionable interface in this file. The others will only be placed in this file to allow the framework to see, using reflection, whether the module implements the interfaces. The actual implementation for the other interfaces occurs in the controller class that we will create later.
Public MustInherit Class ShopList
Inherits Entities.Modules.PortalModuleBase
Implements Entities.Modules.IActionable
Implements Entities.Modules.IPortable
Implements Entities.Modules.ISearchable
Since we will be implementing the IActionable interface in this file, we will now look at the IActionable ModuleActions properties that need to be implemented.
The core framework creates certain menu items automatically. These include the movement, module settings, and so on. You can manually add functionality to the menu by implementing this interface.
To add an action menu item to the module actions menu, we need to create an instance of a ModuleActionCollection . This is done in the ModuleActions property declaration.
Public ReadOnly Property ModuleActions() As _
DotNetNuke.Entities.Modules.Actions.ModuleActionCollection _
Implements DotNetNuke.Entities.Modules.IActionable.ModuleActions
Get
Dim Actions As New _
Entities.Modules.Actions.ModuleActionCollection
We then use the Ad d method of this object to add and item to the menu.
Actions.Add(GetNextActionID, _
Localization.GetString( _
Entities.Modules.Actions.ModuleActionType.AddContent, _
LocalResourceFile), _
Entities.Modules.Actions.ModuleActionType.AddContent, _
"", _
"", _
EditUrl(), _
False, _
Security.SecurityAccessLevel.Edit, _
True, _
False)
Return Actions
End Get
End Property
The parameters of the Actions.Add method are:
You will notice that the second parameter of the Add method asks for a title. This is the text that will show up on the menu item you create. In our code you will notice that instead of using a string, we use the Localization.GetString method to get the text from a local resource file.
Actions.Add(GetNextActionID, _
Localization.GetString( _
Entities.Modules.Actions.ModuleActionType.AddContent, _
LocalResourceFile), _
Entities.Modules.Actions.ModuleActionType.AddContent, _
"", _
"", _
EditUrl(), _
False, _
Security.SecurityAccessLevel.Edit, _
True, _
False)
Localization is one of the many things that DotNetNuke 3.0 has brought us. This allows you to set the language seen on most sections of your portal to the language of your choice. Localization is somewhat beyond the scope of this chapter, but we will at least implement it for the actions menu.
To add a localization file, we first need to create a folder to place it in. Right-click on the EganEnterprises.CoffeeShopListing project in the Solution Explorer and select Add | New Folder . Name the folder App_LocalResources . This is where we will place our localization file. To add the file, right-click on the App_LocalResources folder and select Add | Add New Item from the menu. Select Assembly Resource File from the options and name it ShopList.ascx.resx . Click on Open when you are done.
Under the name section add the resource key AddContent.Action and give it a value of Add Coffee Shop . The action menu we implemented using the IActionable interface earlier uses this key to place Add Coffee Shop on the context menu.
To learn more about how to implement localization in your DotNetNuke modules, please see the DotNetNuke Localization white paper (\DotNetNuke\Documentation\Public\DotNetNuke Localization.doc ).
Now we can move on to the other interfaces. As we stated earlier, these interfaces only need us to add the shell of the implemented functions into this file. These will only be placed in this file to allow the framework to see, using reflection, if the module implements the interfaces. We will write the code to implement these interfaces in the CoffeeShopListingController class later.
That is all the code we need at this time to set up our view module. Open up the display portion of the control in Visual Studio, and by using Table | Insert | Table on Visual Studio's main menu, add an HTML table to the form. Add the following text to the table:
We add the table and text because we will be testing our modules to make sure that everything is in order before moving on the more advanced coding. Again, setting test points in your development allows you to pinpoint errors that may have been introduced into your code. Once we finish the setup for the Edit and Settings controls we will test the module to make sure we have not missed anything.
Module Edit Control
The Edit control is used by administrators to modify or change how your module functions. To set up the Edit control follow the steps we took to create the View control with the following exceptions:
· Do not
implement the IPortable
, IActionable
, and ISearchable
interfaces.
The context menu only works with the View control.
The control menu is used to navigate to the Edit control.
· Change the text in the table to say EditShopList
RowOne
and
EditShopList RowTwo .
· Save the file as EditShopList.ascx .
Add the following in the HTML section:
<%@ Control language="vb" AutoEventWireup="false"
Inherits="EganEnterprises.CoffeeShopListing.EditShopList"
CodeBehind="EditShopList.ascx.vb"%>
and this to the code-behind page:
Imports DotNetNuke
Namespace EganEnterprises.CoffeeShopListing
Public MustInherit Class EditShopList
Inherits Entities.Modules.PortalModuleBase
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
End Sub
End Class
End Namespace
Again, add an HTML table to your control. When viewing your control in design mode it should look like the figure below.
Module Settings Control
The DotNetNuke framework allows you to add customized settings to the Module Settings Page. To do this you need to implement a Settings control.
To set up the Settings control follow the steps we took to create the View control with the following exceptions.
· Do not
implement the IPortable
, IActionable
, and
ISearchable interfaces.
· Change the text in the table to say OptionModule
RowOne
and
OptionModule RowTwo .
· Save the file as Settings.ascx .
Add the following to the HTML section:
<%@ Control language="vb" AutoEventWireup="false" Inherits="EganEnterprises.CoffeeShopListing.Settings" CodeBehind="Settings.ascx.vb"%>
In the code-behind
section it gets a little tricky. As opposed to the other two controls,
this control inherits from ModuleSettingsBase instead of PortalModuleBase . This causes a problem in the Visual Studio designer when you attempt to view your form in design mode. The Visual Studio designer will show the following error.
This is because the ModuleSettingsBase has two abstract methods that we will need to implement: LoadSettings and UpdateSettings . So unless you want to design your control using only HTML, you will need to use the following workaround.
When you need to see
this control in the designer, just comment out the Inherits
ModuleSettingsBase
declaration and both the public overrides
methods (LoadSettings
and UpdateSettings)
, and instead inherit from the PortalModuleBase
. You can then
drag and drop all the controls you would like to use from the toolbox and adjust them on your form. When you are happy with how it looks in the designer, simply switch over the Inherits statements. For now, the only code we need in the code-behind file for this control is the one below. We will add to this code once we have created the DAL (Data Access Layer)
Imports DotNetNuke
Namespace EganEnterprises.CoffeeShopListing
Public Class Settings
Inherits Entities.Modules.ModuleSettingsBase
'Inherits Entities.Modules.PortalModuleBase
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
End Sub
Public Overrides Sub LoadSettings()
End Sub
Public Overrides Sub UpdateSettings()
End Sub
End Class
End Namespace
Just like the other controls, add an HTML table to the control so we can test our modules to this point.
With all your controls complete, build your project and verify that it builds successfully. At this point, the module still cannot be viewed in a browser within the DotNetNuke framework. To do this you will first need to add module definitions to the portal.
Adding Module Definitions
When you upload a free or purchased module to your portal by using the host's file manager, the module definitions are added for you automatically. When developing modules, you will want to be able to debug them in the DotNetNuke environment using Visual Studio. This requires you to add module definitions manually.
Adding module
definitions makes the module appear in the control panel module dropdown when
you are signed on as host or admin. It connects your controls to the portal
framework.
To add the module definitions needed for our project:
1. Hit F5 to run the DotNetNuke solution, log in as host, and click on the Module Definitions option on the Host menu.
2. Under the Module Definition menu, select Add New Module Definition :
3. Enter the name for your module and a short description of what it does. When you are finished, click on the Update link:
4. This will bring up a new section that allows you to add the definitions for the module. Enter the New Definition name and click on Add Definition . This will add the definition to the Definitions dropdown and will bring up a third section that will allow you to add the controls created in the previous section:
First, we will add the View control for the module.
1. Click on the Add Control link to start.
2. Enter the Title for the control. This is the default title when the control is added to a tab.
3. Select the Source for the control from the drop-down list. You will be selecting the file name of our control. This is the View control we created in the last section. Select the control from the dropdown.
4. Select the Type of control. This is the control that non-administrators will see when they view your module on the portal. Select View from the dropdown.
5. Click Update when done.
Next we want to add our Edit control.
1. Enter Edit for the Key field. This is the key that the Actions Menu we created earlier will use to navigate to this control.
2. Enter a Title for the control.
3. Select the ShopListEdit.ascx control from the Source drop-down list.
4. Select Edit as in the Type dropdown.
5. Click Update when complete.
Finally we need to add our Settings control.
1. Click on Add Control to add the third control for this module.
2. Enter Settings for the key field.
3. Enter a Title for the control.
4. Select the Settings.ascx control from the Source drop-down list.
5. Select Edit as in the Type dropdown.
6. Click Update when complete.
This will complete the module definition. Your control page will look like the following.
Click on the Home page menu item to exit the module definition section.
Adding Your Module to a Page
The last step before adding the real functionality to our module is to add the module to a page. I prefer to add a Testing Tab to the portal to test out my new modules. We add the modules to the site before adding any functionality to them to verify that we have set them up correctly. We'll do this in stages so that you can easily determine any errors you encountered, by ensuring each stage of development was completed successfully.
Create a tab called Testing Tab and select EganEnterprises ShopList (or the name you used) from the Module drop-down list on the control panel and click on the Add link to add it to a pane on the page.
If all goes well you should see the module we created on the page. Verify that you can access the custom menu items from the context menu. When selected, they should bring you to the Edit and Settings controls that we created earlier.
For your Module Settings section to appear correctly in the module settings page, make sure that you have it inheriting from ModuleSettingsBase , and not PortalModuleBase .
We now have a basic template for creating our module. Before we can give our controls the functionality they need we need to construct our data layers.
This brings us to the end of this extract from Beginning Websites with VB.NET and DotNetNuke 3.0. | http://odetocode.com/Articles/410.aspx | CC-MAIN-2014-52 | refinedweb | 3,802 | 57.87 |
hey guys im learning to make my own functions and iv had a little trouble it seems my function is returning what i want but for some reason when i put it in a do while loop it just keeps looping instead of exiting when i want, you should be able to see what i mean from this sample text. Thanks in advance much appreciated the people on this site are so helpful.
for some reason it just keeps looping even if something other than y or Y is entered.for some reason it just keeps looping even if something other than y or Y is entered.Code:
#include <stdio.h>
const int TRUE = 1;
const int FALSE = 0;
int isY(char ch);
int main()
{
int x = 1;
int choice;
while (x = 1)
{
choice = isY(choice);
if (choice == FALSE)
x++;
}
return 0;
}
int isY(char ch)
{
int result;
printf("Say this massage again\n(Y/N)? ");
scanf("%c", &ch);
fflush(stdin);
printf("\n");
if ( (ch == 'y') || (ch == 'Y') )
result = TRUE;
else
result = FALSE;
return result;
}
p.s. fflush(stdin) works fine on my compiler (quincy 2005) and i have not yet been tought a better way to flush the standard input thing, but that should not be the problem here. thanks again | http://cboard.cprogramming.com/c-programming/102423-problems-prototype-function-looping-printable-thread.html | CC-MAIN-2016-18 | refinedweb | 212 | 71.89 |
Objective This article will give step to step illustration of creating a simple browser for Windows 7 mobile. Step 1Create a new Windows Phone Application. From Silverlight for Windows Phone tab select Windows Phone Application project type. Step 2 Right click on project and add reference of Microsoft.Phone.Controls.WebBrowser Step 3 On the XAML page add … Continue reading Mini Browser for Windows 7 Mobile
Month: March 2010
A Silverlight Twitter Client for Windows 7 Mobile Part #1
Objective. Follow the below … Continue reading A Silverlight Twitter Client for Windows 7 Mobile Part #1
Touch events in Silverlight for Windows 7 mobile application Part #2
Objective This article will explain how to work with Touch events in Silverlight for Windows 7 mobile application. This is part 2 of the touch events. Read my first article on touch events before going through this article. Background We saw in last article on touch events that, even if after touching (clicking) somewhere else … Continue reading Touch events in Silverlight for Windows 7 mobile application Part #2
Touch events in Silverlight for Windows 7 mobile application
Objective … Continue reading Touch events in Silverlight for Windows 7 mobile application
Get an Image using WCF REST service
Objective This article will give a very simple and basic explanation of , how to fetch an image using WCF REST service. Step 1 Create a WCF application. To create a new application File -> New -> Web-> WCF Service Application.Remove all the default code created by WCF. Remove code from IService 1 interface and … Continue reading Get an Image using WCF REST service
Creating first Windows 7 mobile application in Silverlight
Objective … Continue reading Creating first Windows 7 mobile application in Silverlight
Creating IPL Photo gallery using AccordionControl in Silverlight 3.0: Part #1
Objective This article will explain Basic use of Accordion control in Silverlight 3.0 Binding Accordion items with properties of entity class. Creating an Imagesource from Image URL provided. Background This article is first part of 3 or 4 parts IPL Photo Gallery series. In this article, I am reading image, team name and caption name … Continue reading Creating IPL Photo gallery using AccordionControl in Silverlight 3.0: Part #1
Reading RSS feed in Silverlight 3.0
Objective This article is going to explain; how we can read RSS feeds in Silverlight 3.0. Expected output User will enter RSS URL in text box. On click of Fetch Feed button ; RSS items will get populated On Clear Search button click text box and list box will be cleared. So, let us start … Continue reading Reading RSS feed in Silverlight 3.0
LINQ to Object Part #4: Querying Non- IEnumerable collections
Objective In this article, I am going to show, how we could apply LINQ to query non-IEnumerable<T> Collections. I have created a class for my explanation purpose. Student class is having details of students. Student.cs 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace LINQtoOBJECT1 7 { 8 public class Student 9 { 10 11 … Continue reading LINQ to Object Part #4: Querying Non- IEnumerable collections
Demystifying CLR Part #1
Objective This is a fully theoretical article. In this article, I am going to explain fundamentals of CLR. How CLR executes codes written in different languages. I am going to explain various components of MANAGED MODULES also. Note: I have written this article on basis of my learning from the very nice book written by … Continue reading Demystifying CLR Part #1 | https://debugmode.net/2010/03/ | CC-MAIN-2020-40 | refinedweb | 587 | 54.42 |
Listen to this article
If you're like me, or like many other Python developers, you've probably lived (and maybe migrated) through a few version releases. Python 3.7(.3), one of the latest releases, includes some impressive new language features that help to keep Python one of the easiest, and most powerful languages out there. If you're already using a Python 3.x version, you should consider upgrading to Python 3.7. Read on to learn more about some of the exciting features and improvements.
Data Classes
One of the most tedious parts about working with Python prior to 3.7 in an object-oriented way was creating classes to represent data in your application.
Prior to Python 3.7, you would have to declare a variable in your class, and then set it in your
__init__ method from a named parameter. With applications that had complex data models, this invariably led to a large number of boilerplate model and data contract code that had to be maintained.
With Python 3.7, thanks to PEP-557, you now have access to a decorator called
@dataclass, that automatically adds an implicit
__init__ function for you when you add typings to your class variables. When the decorator is added, Python will automatically inspect the attributes and typings of the associated class and generate an
__init__ function with parameters in the order specified.
from typing import List from dataclasses import dataclass, field @dataclass class Foo: name: str id: str bars: List[str] = field(default_factory=list) # usage a_foo = Foo("My foo’s name", "Foo-ID-1", ["1","2"])
You can still add class methods to your data class, and use it like you would any other class. For JSON support, see the library dataclasses-json on PYPI.
Asyncio and the
async/
await Keywords
The most obvious change here is that
async and
await are now reserved keywords in Python. This goes hand in hand with some improvements to asyncio, Python's concurrency library. Notably, this includes high-level API improvements which make it easier to run asynchronous functions. Take the following as an example of what was required to make a function asynchronous prior to Python 3.7:
import asyncio loop = asyncio.get_event_loop() loop.run_until_complete(some_async_task()) loop.close()
Now in Python 3.7:
import asyncio asyncio.run(some_async_task())
breakpoint()
In previous versions of Python adding in a breakpoint to use the built-in Python debugger (
pdb) would require
import pdb; pdb.set_trace().
PEP-553 adds the ability to use a new keyword and function, called
breakpoint, used like below:
do_something() breakpoint() do_something_else()
When running from a console, this will enter straight away into
pdb and allow the user to enter debug statements, evaluate variables, and step through program execution. See here for more information on how to use
pdb.
Lazy Loading via Module Attributes
Some experienced Python users might be familiar with
__getattr__ and
dir for classes and objects. PEP-562 exposes
__getattr__ for modules as well.
Without diving into the realm of technical possibilities that this exposes, one of its clearest and most obvious use cases is that it now allows for modules to lazy load. Consider the example below, modified from PEP-562, and its usage.
/mymodule/__init__.py
import importlib __all__ = ['mysubmodule', ...] def __getattr__(name): if name in __all__: return importlib.import_module("." + name, __name__) raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
/mymodule/mysubmodule.py
print("Submodule loaded") class BigClass: pass
/main.py
import mymodule mymodule.mysubmodule.BigClass # prints Submodule loaded
Notice that although we imported
mymodule in this example, the submodule containing
BigClass didn't load until we called it.
Context Variables
When using async/await functions in the Python event loop prior to 3.7, context managers that used thread local variables had the chance to bleed values across executions, potentially creating bugs that are difficult to find.
Python 3.7 introduces the concept of context variables, which are variables that have different values depending on their context. They're similar to thread locals in that there are potentially different values, but instead of differing across execution threads, they differ across execution contexts and are thus compatible with
async and
await functions.
Here's a quick example of how to set and use a context variable in Python 3.7. Notice that when you run this, the second
async call produces the default value as it is evaluating in a different context.
import contextvars import asyncio val = contextvars.ContextVar("val", default="0") async def setval(): val.set("1") async def printval(): print(val.get()) asyncio.run(setval()) # sets the value in this context to 1 asyncio.run(printval()) # prints the default value “0” as its a different context
Order of Dictionaries Preserved
Python dictionaries were considered unordered dictionaries for many versions, which meant that you could write the following in Python 3.6 and earlier, and expect an out-of-order result when iterating over the keys.
>>> x = {'first': 1, 'second': 2, 'third': 3} >>> print([k for k in x]) ['second', 'third', 'first']
For those prior versions, there was
OrderedDict available from collections to the rescue, which provided the strong ordering guarantees needed with certain use cases.
In Python 3.6 dictionaries were re-implemented to be ordered dictionaries, and now in Python 3.7 it is officially part of the language specification. This means that dictionary order can now be relied on but also must be accounted for when considering backwards compatibility.
Don't expect usage of
OrderedDict to go away anytime though; it is still in Python 3.7, and has more advanced operations and different equality comparisons than the standard
dict.
Also, this update has proven to be one of the more unpopular updates to Python 3.7. It allows for a developer to ambiguously define an ordered
dict when he/she didn't mean to.
Optimizations to Python 3.7
Still not sure if you should check out Python 3.7? You should know that Python 3.7 has numerous performance improvements, notably:
- Python startup time has been reduced between 10-30% on various operating systems.
- Typing operations are faster.
List.sortand sorted methods have improved between 45-70% for common cases.
dict.copy()is now 5.5 times faster.
namedtuplecreation via
collections.namedtuple()is 4-6 times faster.
For a complete list, check out the official release notes.
If you want a deeper dive into some of the Python 3.7 language features, check out this lightning talk I gave at the PyCascades conference.
Or try it out by deploying a Python app to Heroku. As of April 2019, Python 3.6.8 is the default version installed if you don’t explicitly specify a version in a
runtime.txt file. Put
python-3.7.3 in it to try out all these new Python features.
👋 Heroku is a Diamond Sponsor of PyCon 2019, May 1-9. If you'll be there, please come say hi to the team at the Heroku booth. 🐍 | https://blog.heroku.com/python37-dataclasses-async-await | CC-MAIN-2020-24 | refinedweb | 1,165 | 57.27 |
libblkid - block device identification library
Synopsis
Description
Author
Files
Availability
Copying
#include <blkid/blkid.h>
cc file.c -lblkid.
Block device information is normally kept in a cache file /etc/blkid.
libblkid was written by Andreas Dilger for the ext2 filesystem utilties, with input from Ted Tso. The library was subsequently heavily modified by Ted Tso.
libblkid is part of the e2fsprogs package since version 1.33 and is available from.
libblkid is available under the terms of the GNU Library General Public License (LGPL), version 2 (or at your discretion any later version). A copy of the LGPL should be included with this library in the file COPYING. If not, write toFree Software Foundation, Inc.
59 Temple Place
Suite 330
Boston, MA 02111-1307 USA
or visit
blkid_get_cache(3), blkid_put_cache(3), blkid_get_dev(3), blkid_probe_all(3), blkid_get_devname(3), blkid_get_tag_value(3), blkid.tab(7) | http://manpages.sgvulcan.com/libblkid.3.php | CC-MAIN-2018-39 | refinedweb | 143 | 59.6 |
I was wondering if anyone could give me some pointers. I'm trying to come up with a matrix class so that I can do a class assignment that has me go through 3 dif iterative methods that work off of matrices (Jacobi, Gauss-seidel, SOR with user input for the omega value). I'm sure there are algorithms out there already for those three so that shouldn't be a problem.
What my issues are trying to finish this matrix class so that I can achieve the following: Generate a random, diagonally dominant matrix problem and save to file A and b into separate files, Load a matrix of size nxn from a file named A.txt, Load a vector of size n from a file named b.txt, then solve the problem Ax=b using the 3 methods above.
matrix.h
#ifndef MATRIX_H_INCLUDED #define MATRIX_H_INCLUDED class matrix { public: matrix(int n); void gensol(); void genb(); void display(); private: int N; double ** A; double *Sol; double *b; }; #endif // MATRIX_H_INCLUDED
matrix.cpp
#include <cmath> #include <stdlib.h> #include <iomanip> #include <iostream> #include "matrix.h" using namespace std; matrix::matrix(int n) { double sum=0; N=n; A = new double * [N]; Sol = new double [N]; b = new double [N]; gensol(); for (int i=0; i<N; i++) {A[i]= new double [N];} int r; for(int i=0; i<N; i++) for(int j=0; j<N; j++) {A[i][j]=( (double) (rand()%10000) )/100.0; r=rand()%2; if(r==1){A[i][j]=A[i][j]*-1;} } //enforcing diagonal dominance for (int row=0; row<N; row++) { for(int col=0; col<N; col++) {if(row!=col) {sum= sum+abs(A[row][col]);} } A[row][row]=sum+100; sum=0; } genb(); } void matrix::display() { for(int i=0; i<N; i++) {for(int j=0; j<N; j++) {cout<<setw(10)<<A[i][j];} cout<<setw(15)<<Sol[i]; cout<<setw(15)<<b[i]; cout<<endl; } } void matrix::gensol() { int r; for(int row=0; row<N; row++) {Sol[row]=( (double) (rand()%10000) )/100.0; r=rand()%2; if(r==1){Sol[row]=Sol[row]*-1;} } } void matrix::genb() { double temp = 0; for(int row=0; row<N; row++) { for(int col=0; col<N; col++) { temp=(A[row][col]*Sol[col])+temp; } b[row]=temp; temp=0.0; } }
main.cpp
Not developed yet
I'm trying to just get this thing to be created first.
*EDIT*
Do you guys think I can follow this and then just add my functions that are already declared to it to get everything in order?
This post has been edited by R2B Boondocks: 12 February 2014 - 07:57 AM | http://www.dreamincode.net/forums/topic/339869-c-matrix-program-class/ | CC-MAIN-2018-13 | refinedweb | 447 | 58.72 |
IntelliSense in Visual Studio
IntelliSense is a code-completion aid that includes a number of features: List Members, Parameter Info, Quick Info, and Complete Word. These features help you to learn more about the code you're using, keep track of the parameters you're typing, and add calls to properties and methods with only a few keystrokes.
Many aspects of IntelliSense are language-specific. For more information about IntelliSense for different languages, see the topics listed in the See also section.
List Members
A list of valid members from a type (or namespace) appears after you type a trigger character (for example, a period (
.) in managed code or
:: in C++). If you continue typing characters, the list is filtered to include only the members that begin with those characters or where the beginning of any word within the name starts with those characters. IntelliSense also performs "camel case" matching, so you can just type the first letter of each camel-cased word in the member name to see the matches. PgUp and PgDn to move up or down in the list.
You can invoke the List Members feature manually by typing Ctrl+J, choosing Edit > IntelliSense > List Members, or by choosing, or choose Edit > IntelliSense > Toggle Completion Mode.
Parameter Info Supply XML code comments.
You can manually invoke Parameter Info by choosing Edit > IntelliSense > Parameter Info, by pressing Ctrl+Shift+Space, or by choosing the Parameter Info button on the editor toolbar.
Quick Info
Quick Info displays the complete declaration for any identifier in your code.
When you select a member from the List Members box, Quick Info also appears.
You can manually invoke Quick Info by choosing Edit > IntelliSense > Quick Info, by pressing Ctrl+K, Ctrl+I, or by choosing the Quick Info button on the editor toolbar.
If a function is overloaded, IntelliSense may not display information for all forms of the overload.
You can turn Quick Info off for C++ code by navigating to Tools > Options > Text Editor > C/C++ > Advanced, and setting Auto Quick Info to
false.
Complete Word
Complete Word completes the rest of a variable, command, or function name after you have entered enough characters to disambiguate the term. You can invoke Complete Word by choosing Edit > IntelliSense > Complete Word, by pressing Ctrl+Space, or by choosing the Complete Word button on the editor toolbar.
IntelliSense options
IntelliSense options are on by default. To turn them off, choose Tools > Options > Text Editor and deselect Parameter information or Auto list members if you do not want the List Members feature.
IntelliSense icons
The icons in IntelliSense can convey additional meaning with icon modifiers. These are stars, hearts, and locks layered on top of the object's icon that convey protected, internal, or private, respectively.
Troubleshoot IntelliSense:
MessageBox( hWnd, "String literal|")
The automatic options are turned off. By default, IntelliSense works automatically, but you can disable it. Even if automatic statement completion is disabled, you can invoke an IntelliSense feature. | https://docs.microsoft.com/en-us/visualstudio/ide/using-intellisense?view=vs-2019 | CC-MAIN-2021-49 | refinedweb | 495 | 52.7 |
Google Maps provides Android developers with localization tools that can be included within your own app interfaces. In this series, we are creating a basic Android application with Google Maps and Google Places integration. In this part, we will access the Google Places API to retrieve information about places of interest near the user's current location. We will use the returned data to present markers for each place on the map in the final part of this tutorial series. We will also set the application to update the map markers when the user's location changes.
This is the third of four parts in a tutorial series on Using Google Maps and Google Places in Android apps:
- Working with Google Maps - Application Setup
- Working with Google Maps - Map Setup
- Working with Google Maps - Places Integration
- Working with Google Maps - Displaying Nearby Places (Pending Publication)
1. Get Google Places API Access
Step 1
In the first part of this series we used the Google API Console to get an API key for the mapping tools. Now we need to do the same for the Google Places API. Sign into your Google Account and browse to the Console again. Select Services from the options in the left-hand column and scroll down to the entry for Places API. Click to turn Places on for your account.
Remember you need to carry out this step for any Google API service you wish to access, as your keys will not work otherwise.
Step 2
Now we need to get the key to access the Places API. Select API Access from the left-hand column in your Google APIs Console. You will see the page we used in the first part of the series to retrieve an API key for the mapping package. Although we are going to use the Places API in an Android app, the type of access is actually the same as for browser apps. When we retrieve the Places data, we request it using a URL and retrieve the results in JSON format, as you would in a Web application. Copy the key listed in the Key for browser apps section and save it.
We're finished with the Google APIs Console so feel free to log out of your account.
2. Build a Places Search Query
Step 1
Google Places API provides a range of information about places. For our app, we are going to use the Place Search request to return a list of places near the user's current location. We need to build the necessary elements into a URL query string to execute the Place Search. This is the basic format of the URL:
The output can be JSON or XML; we will use JSON for this app. The URL must be appended with various required parameters, including your API key, the user's location as longitude and latitude values, the radius to search within, and a boolean flag indicating whether the location was derived from a location sensor such as a GPS. There are various optional parameters you can add to your query; see the Place Search documentation for an overview. For the purpose of this app, we will add the optional types parameter to search for places of particular types.
This is an indicator of what the final query will look like:? location=55.864237,-4.251805999999988 &radius=1000 &sensor=true &types=food|bar|store|museum|art_gallery &key=your_api_key
We will build the longitude and latitude values dynamically (the hard-coded example values above are just for demonstration). The radius value is in meters, so feel free to alter it to suit the purpose of your app. You can also alter the place types if you wish; see the Supported Place Types overview for the available options. Make sure you separate the place types using the pipe "|" character. You should of course alter the key parameter value to reflect your own API key.
In your Activity class updatePlaces helper method, after the existing code in which we retrieved the user location and animated the map camera to it, create a string for the Place Search URL:
String placesSearchStr = "" + "json?location="+lat+","+lng+ "&radius=1000&sensor=true" + "&types=food|bar|store|museum|art_gallery"+ "&key=your_key_here";
Include the API key you copied from the Google APIs Console for browser apps. Note that we pass the latitude and longitude values we previously retrieved from the user's location.
3. Create an AsyncTask to Fetch Place Data in the Background
Step 1
You will need to add the following import statements to your Activity class for the code we'll use next:
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader;; import android.os.AsyncTask;
Since we will fetch data over the Web, we will use an AsyncTask to carry out this process off the UI thread. This will allow us to handle the results within the UI thread, adding markers to the visible map when the app receives the Place Search data.
In your Activity class, create the AsyncTask class outline as follows:
private class GetPlaces extends AsyncTask<String, Void, String> { //fetch and parse place data }
The three types indicated represent the types of parameters, progress units, and the result of the background operation. We will pass the Place Search URL as a string, so this is the parameter. We won't indicate progress for this app, so the second type is void. The result of the background operation in this case will be a JSON string representing the places, so the third type is a text string.
Step 2
When you use an AsyncTask, you indicate the processing you want to occur in the background within the doInBackground method. Once that has executed and retrieved a result, the onPostExecute method will then execute. For this app, we will fetch the Place Search results in doInBackground, then parse the results in onPostExecute, creating markers to display on the map at the same time.
Inside your AsyncTask class, add the doInBackground method:
@Override protected String doInBackground(String... placesURL) { //fetch places }
The parameter type is string, as indicated by the class outline above. Let's use a String Builder to build the returned JSON text string inside this new method:
StringBuilder placesBuilder = new StringBuilder();
Although we will only pass a single Place Search query URL string, the doInBackground method expects to potentially receive an array of parameters, so add a loop to process this:
//process search parameter string(s) for (String placeSearchURL : placesURL) { //execute search }
Inside the loop, create an HTTP Client object to execute the query URL:
HttpClient placesClient = new DefaultHttpClient();
As with any input/output process, we need to take care of potential errors, so add try and catch blocks next, still inside the loop:
try { //try to fetch the data } catch(Exception e){ e.printStackTrace(); }
Inside the try block, create an HTTP Get object, passing the URL string:
HttpGet placesGet = new HttpGet(placeSearchURL);
Use the HTTP Client to execute this, retrieving an HTTP Response:
HttpResponse placesResponse = placesClient.execute(placesGet);
Let's check that we have a positive response before we attempt to carry out any further processing. Retrieve the status line:
StatusLine placeSearchStatus = placesResponse.getStatusLine();
We can only continue if we have a 200 "OK" status code indicating that the request was successful, so add a conditional statement:
if (placeSearchStatus.getStatusCode() == 200) { //we have an OK response }
Inside the if block, retrieve the HTTP Entity from the response object:
HttpEntity placesEntity = placesResponse.getEntity();
Now we can start to retrieve the actual content of the response, which should be the JSON string. Start by creating an Input Stream:
InputStream placesContent = placesEntity.getContent();
Now create a reader for this stream:
InputStreamReader placesInput = new InputStreamReader(placesContent);
Let's carry out our input stream processing using a Buffered Reader:
BufferedReader placesReader = new BufferedReader(placesInput);
Now we can use a loop to read the input one line at a time, appending each one to the String Builder as we go along:
String lineIn; while ((lineIn = placesReader.readLine()) != null) { placesBuilder.append(lineIn); }
This loop will continue to execute as long as there is still data to read in.
Finally, we can return the string that is handled by the String Builder. At the end of the doInBackground method after the for loop, return the JSON data:
return placesBuilder.toString();
Conclusion
The third part of this tutorial series is now complete. We set the app up to utilize Google Places API and created an inner class to fetch the place data in the background off the app's main UI thread. We executed the Place Search query and retrieved the resulting JSON. When you run your app, it will not behave any differently than it did after the previous part of this series. This is because we have not yet completed or instantiated the AsyncTask class. We will do that in the final part, after we add the onPostExecute method to parse the JSON Place Search result and translate it into map markers. We will also extend the app to update the displayed markers as the user's location changes.
| http://code.tutsplus.com/tutorials/android-sdk-working-with-google-maps-google-places-integration--mobile-16054 | CC-MAIN-2015-14 | refinedweb | 1,520 | 58.52 |
HashSet Sample program in Java
By: Kamini Printer Friendly Format
The following constructors are defined:
HashSet( )
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
The first form constructs a default hash set. The second form initializes the hash set by using the elements of c. The third form initializes the capacity of the hash set to capacity. The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments. The fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded. For constructors that do not take a fill ratio, 0.75 is used.
HashSet does not define any additional methods beyond those
provided by its superclasses and interfaces. Importantly, note that a hash set does not guarantee the order
of its elements, because
the process of hashing doesn't usually lend itself to the creation of sorted sets. If you need sorted storage, then another collection, such as TreeSet, is a better choice.
Here is an example that demonstrates HashSet:
// Demonstrate HashSet.
import java.util.*;);
}
}
The following is the output from this program:
[F, E, D, C, B, A]
As explained, the elements are not stored in sorted very usefull to the users who were in startin
View Tutorial By: Harichandana at 2013-02-28 04:37:17
2.
View Tutorial By: Venkat at 2013-04-11 06:40:45
3. Good
View Tutorial By: Siva Sreekanth at 2013-10-01 16:29:55
4. Your output is not correct.. Give the correct out
View Tutorial By: Surendrakumar at 2014-06-04 07:00:16
5. CaseyOffer
View Tutorial By: CaseyOffer at 2017-03-15 18:27:37
6. CaseyOffer
View Tutorial By: CaseyOffer at 2017-04-10 22:16:46 | https://java-samples.com/showtutorial.php?tutorialid=348 | CC-MAIN-2022-21 | refinedweb | 334 | 56.86 |
21055/can-we-set-a-list-of-discovery-nodes-in-hyperledger-fabric
When starting a new node we have to indicate the address of a root node so as it can connect and discover the network. Is there a way to set a list of nodes so as the new node does not depend on a single peer?
New nodes doesn't depend on a single peer and ROOTNODE can be any peer.
Upon start up, a peer runs discovery protocol if CORE_PEER_DISCOVERY_ROOTNODE is specified.
CORE_PEER_DISCOVERY_ROOTNODE is the IP address of another peer on the network (any peer) that serves as the starting point for discovering all the peers on the network.
Is your transaction actually called 'OrderPlaced' (in ...READ MORE
For hyperledger fabric you can use query ...READ MORE
The peers communicate among them through the ...READ MORE
There are two types to implement ordering:
1. ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
{
"nonce": "0x0000000000000042",
"difficulty": "0x000000100",
"alloc": {
},
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"coinbase": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
This link might help you: ...READ MORE
Consensus is the key concept for validating ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/21055/can-we-set-a-list-of-discovery-nodes-in-hyperledger-fabric?show=21122 | CC-MAIN-2021-21 | refinedweb | 211 | 67.65 |
If you format namenode, you need to cleanup storage directories of DataNode as well if that
is having some data already. DN also will have namespace ID saved and compared with NN namespaceID.
if you format NN, then namespaceID will be changed and DN may have still older namespaceID.
So, just cleaning the data in DN would be fine.
Regards,
Uma
________________________________
From: hadoop hive [hadoophive@gmail.com]
Sent: Friday, November 16, 2012 1:15 PM
To: user@hadoop.apache.org
Subject: Re: High Availability - second namenode (master2) issue: Incompatible namespaceIDs
Seems like you havn't format your cluster (if its 1st time made).
On Fri, Nov 16, 2012 at 9:58 AM, ac@hsk.hk<mailto:ac@hsk.hk> <ac@hsk.hk<mailto:ac@hsk.hk>>
wrote:
Hi,
Please help!
I have installed a Hadoop Cluster with a single master (master1) and have HBase running on
the HDFS. Now I am setting up the second master (master2) in order to form HA. When I used
JPS to check the cluster, I found :
2782 Jps
2126 NameNode
2720 SecondaryNameNode
i.e. The datanode on this server could not be started
In the log file, found:
2012-11-16 10:28:44,851 ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: java.io.IOException:
Incompatible namespaceIDs in /app/hadoop/tmp/dfs/data: namenode namespaceID = 1356148070;
datanode namespaceID = 1151604993
One of the possible solutions to fix this issue is to: stop the cluster, reformat the NameNode,
restart the cluster.
QUESTION: As I already have HBASE running on the cluster, if I reformat the NameNode, do I
need to reinstall the entire HBASE? I don't mind to have all data lost as I don't have many
data in HBASE and HDFS, however I don't want to re-install HBASE again.
On the other hand, I have tried another solution: stop the DataNode, edit the namespaceID
in current/VERSION (i.e. set namespaceID=1151604993), restart the datanode, it doesn't work:
Warning: $HADOOP_HOME is deprecated.
starting master2, logging to /usr/local/hadoop-1.0.4/libexec/../logs/hadoop-hduser-master2-master2.out
Exception in thread "main" java.lang.NoClassDefFoundError: master2
Caused by: java.lang.ClassNotFoundException: master: master2. Program will exit.
QUESTION: Any other solutions?
Thanks | http://mail-archives.apache.org/mod_mbox/hadoop-user/201211.mbox/%3C1542FA4EE20C5048A5C2A3663BED2A6B30B139B3@szxeml531-mbx.china.huawei.com%3E | CC-MAIN-2018-39 | refinedweb | 374 | 58.28 |
Question:
I'd like to know the proper place to put GUI based sequential start-up code in my Blackberry app.
In main(), I create MyApp and enterEventDispatcher() I have UiApplication (MyApp) In the MyApp CTOR: - I create a MainScreen (MyMain) - I call pushScreen() on MyMain
When the event dispatcher starts, is there an event I can listen for in my MainScreen that will give me the event thread where I can happily do synchronous start-up tasks?
I can use invokeLater() but I want each call to block because their order is important in this phase. invokeAndWait() throws an exception in most cases where I've attempted to use it.
I've attempted the code below but I get an exception when trying to run on the "Testing 1 2 3" line.
public class MyApp extends UiApplication { static public void main(String[] args) { new MyApp().enterEventDispatcher(); } public MyApp() { MyView theView = new MyView(); theView.startUpdateTimer(); pushScreen(theView); Dialog.alert("Testing 1 2 3"); } }
Solution:1
If it's pretty quick UI stuff (creating a screen, pushing it onto the stack), do it from the main thread before calling enterEventDispatcher. You can actually do as much as you want, just the user experience will be worse if your app takes a long time.
The thread that calls enterEventDispatcher basically becomes the event dispatch thread, so you're safe to do any GUI stuff on that thread before calling enterEventDispatcher.
Specifically, don't call invokeAndWait from the main thread - that'll cause deadlock and probably an exception.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon | http://www.toontricks.com/2018/06/tutorial-where-to-put-gui-based-start.html | CC-MAIN-2018-43 | refinedweb | 275 | 59.94 |
OCaml Planet
The OCaml Planet aggregates various blogs from the OCaml community. If you would like to be added, read the Planet syndication HOWTO.
On fixed-point theorems in synthetic computability — Andrej Bauer, Nov 06, 2019 poi…Read more...!Hide
Runners in action — Andrej Bauer, Oct 27, 2019…Read more.....
General-purpose programming languages, even the so-called pure ones, have to have some account of interaction with the external environment. A popular choice is to provide a foreign-function interface that connects the language with an external library, and through it with an operating system and the universe. A more nuanced approach would differentiate between a function that just happens to be written in a different language, and one that actually performs an effect. The latter kind is known as an algebraic operation in the algebraic-effects-and-handlers way of doing things.
A bad approach to modeling the external world is to pretend that it is
internal to the language. One would think that this is obvious but it is not.
For instance, Haskell represents the interface to the external world through the
IO
monad.
But what is this monad really? How does it get to interact with the external
world? The Haskell Wiki page which answers this question has the following
disclaimer:
"Warning: The following story about
IOis incorrect in that it cannot actually explain some important aspects of
IO(including interaction and concurrency). However, some people find it useful to begin developing an understanding."
The Wiki goes on to say how
IO is a bit like a state monad with an imaginary
RealWorld state, except that of course
RealWorld is not really a Haskell
type, or at least not one that actually holds the state of the real world.
The situation with Eff is not much better: it treats some operations at the
top-level in a special way. For example, if
If
IO monad is not an honest monad and a top-level handler is not really a
handler, then what we have is a case of ingenious hackery in need of proper
programming-language design.
How precisely does an operation call in the program cause an effect in the external world? As we have just seen, some sort of runtime environment or top level needs to relate it to the external world. From the viewpoint of the program, the external world appears as state which is not directly accessible, or even representable in the language. The effect of calling an operation $\mathtt{op}(a,\kappa)$ is to change the state of the world, and to get back a result. We can model the situation with a map $\overline{\mathtt{op}} : A \times W \to B \times W$, where $W$ is the set of all states of the world, $A$ is the set of parameters, and $B$ the set of results of the operation. The operation call $\mathtt{op}(a, \kappa)$ is "executed" in the current world $w \in W$ by computing $\overline{\mathtt{op}}(a,w) = (b, w')$ to get the next world $w'$ and a result $b$. The program then proceeds with the continuation $\kappa\,b$ in the world $w'$. Notice how the world $w$ is an external entity that is manipulated by the external map $\overline{\mathtt{op}}$ realistically in a linear fashion, i.e., the world is neither discarded nor copied, just transformed.
What I have just described is not a monad or a handler, but a comodel, also known as a runner, and the map $\overline{\mathtt{op}}$ is not an operation, but a co-operation. This was all observed a while ago by Gordon Plotkin and John Power, Tarmo Uustalu, and generalized by Rasmus Møgelberg and Sam Staton, see our paper for references. Perhaps we should replace "top-level" handlers and "special" monads with runners?
Danel and I worked out how effectful runners (a generalization of runners that supports other effects in addition to state) provide a mathematical model of resource management. They also give rise to a programming concept that models top-level external resources, as well as allows programmers to modularly define their own “virtual machines” and run code inside them. Such virtual machines can be nested and combined in interesting ways. We capture the core ideas of programming with runners in an equational calculus $\lambda_{\mathsf{coop}}$, that guarantees the linear use of resources and execution of finalization code.
An interesting practical aspect of $\lambda_{\mathsf{coop}}$, that was begotten by theory, is modeling of extra-ordinary circumstances. The external environment should have the ability to signal back to the program an extra-ordinary circumstance that prevents if from returning a result. This is normally accomplished by an exception mechanism, but since the external world is stateful, there are two ways of combining it with exceptions, namely the sum and the tensor of algebraic theories. Which one is the right one? Both! After a bit of head scratching we realized that the two options are (analogous to) what is variously called "checked" and "non-checked" exceptions, errors and signals, or synchronous and asynchronous exceptions. And so we included in $\lambda_{\mathsf{coop}}$ both mechanisms: ordinary exceptions, which are special events that disrupt the flow of user code but can be caught and attended to, and signals which are unrecoverable failures that irrevocably kill user code, but can still be finalized. We proved a finalization theorem which gives strong guarantees about resources always being properly finalized.
If you are familiar with handlers, as a first approximation you can think of
runners as handlers that use the continuation at most once in a tail-call
position. Many handlers are already of this form but not all. Non-determinism,
probability, and handlers that hijack the continuation (
delimcc, threads, and
selection functionals) fall outside of the scope of runners. Perhaps in the
future we can resurrect some of these (in particular it seems like threads, or
even some form of concurrency would be worth investigating). There are many
other directions of possible future investigations: efficient compilation, notions
of correctness, extensions to the simple effect subtyping discipline that we
implemented, etc.
To find out more, we kindly invite you to have a look at the paper, and to try out the implementations. The prototype programming language Coop implements and extends $\lambda_{\mathsf{coop}}$. You can start by skimming the Coop manual and the examples. If you prefer to experiment on your own, you might prefer the Haskell-Coop library, as it allows you to combine runners with everything else that Haskell has to offer.Hide
Coq 8.10.1 is out — Coq, Oct 25,.
Announcing MirageOS 3.6.0 — MirageOS (Martin Lucina), Oct 18, 2019enentargets. The
genodeand
virtiotargets are still limited to using a single network or block storage device.
- Several notable security enhancements to Solo5 targets, such as enabling stack smashing protection throughout the toolchain by default and improved page protections on some targets. For details, please refer to the Solo5 0.6.0 release notes.
Additional user-visible changes:
- Solo5 0.6.0 has removed the compile-time specialization of the.
- New functions
Mirage_key.is_solo5and
Mirage_key.is_xen, analogous to
Mirage_key.is_unix.
Thanks to Hannes Mehnert for help with the release engineering for MirageOS 3.6.0.Hide
Commas in big numbers everywhere: An OpenType adventure — Jane Street, Oct 14, 2019
Coq 8.10.0 is out — Coq, Oct 07, 2019.
All details can be found in the user manual.
Feedback and bug reports are extremely welcome.Hide
OCaml expert and beginner training by OCamlPro (in French): Nov. 5-6 & 7-8 — OCamlPro, Sep 25, 2019 …Read more... also an opportunity to come discuss with OCamlPro’s OPAM & Flambda lead developers and core contributors in Paris.
Training in English can also be organized, on-demand.
Register link:
HideHide
This complements the excellent OCaml MOOC from Université Paris-Diderot and the learn-OCaml platform of the OCaml Software Foundation.
Mr. MIME - Parse and generate emails — Tarides (Romain Calascibetta), Sep 25, 2019 h…Read more... human-comprehensible format (or rich-document as we said a long time ago), there are several details of emails which complicate the process of analyzing them (and can be prone to security lapses). These details are mostly described by three RFCs:
Even though they are cross-compatible, providing full legacy email parsing is an archaeological exercise: each RFC retains support for the older design decisions (which were not recognized as bad or ugly in 1970 when they were first standardized).
The latest email-related RFC (RFC5322) tried to fix the issue and provide a better formal specification of the email format – but of course, it comes with plenty of obsolete rules which need to be implemented. In the standard, you find both the current grammar rule and its obsolete equivalent.
An extended email parser
Even if the email format can defined by "only" 3 RFCs, you will miss email internationalization (RFC6532), the MIME format (RFC2045, RFC2046, RFC2047, RFC2049), or certain details needed to be interoperable with SMTP (RFC5321). There are still more RFCs which add extra features to the email format such as S/MIME or the Content-Disposition field.
Given this complexity, we took the most general RFCs and tried to provide an easy way to deal with them. The main difficulty is the multipart parser, which deals with email attachments (anyone who has tried to make an HTTP 1.1 parser knows about this).
A realistic email parser
Respecting the rules described by RFCs is not enough to be able to analyze any
email from the real world: existing email generators can, and do, produce
non-compliant email. We stress-tested
mrmime by feeding it a batch of 2
billion emails taken from the wild, to see if it could parse everything (even if
it does not produce the expected result). Whenever we noticed a recurring
formatting mistake, we updated the details of the ABNF to enable
mrmime to parse it anyway.
A parser usable by others
One demonstration of the usability of
mrmime is `ocaml-dkim`, which wants to
extract a specific field from your mail and then verify that the hash and signature
are as expected.
ocaml-dkim is used by the latest implementation of `ocaml-dns` to request
public keys in order to verify email.
The most important question about
ocaml-dkim is: is it able to
verify your email in one pass? Indeed, currently some implementations of DKIM
need 2 passes to verify your email (one to extract the DKIM signature, the other
to digest some fields and bodies). We focused on verifying in a single pass in
order to provide a unikernel SMTP relay with no need to store your email between
verification passes.
An email generator
OCaml is a good language for making little DSLs for specialized use-cases. In this case, we took advantage of OCaml to allow the user to easily craft an email from nothing.
The idea is to build an OCaml value describing the desired email header, and then let the Mr. MIME generator transform this into a stream of characters that can be consumed by, for example, an SMTP implementation. The description step is quite simple:
#require "mrmime" ;; #require "ptime.clock.os" ;; open Mrmime let romain_calascibetta = let open Mailbox in Local.[ w "romain"; w "calascibetta" ] @ Domain.(domain, [ a "gmail"; a "com" ]) let john_doe = let open Mailbox in Local.[ w "john" ] @ Domain.(domain, [ a "doe"; a "org" ]) |> with_name Phrase.(v [ w "John"; w "D." ]) let now () = let open Date in of_ptime ~zone:Zone.GMT (Ptime_clock.now ()) let subject = Unstructured.[ v "A"; sp 1; v "Simple"; sp 1; v "Mail" ] let header = let open Header in Field.(Subject $ subject) & Field.(Sender $ romain_calascibetta) & Field.(To $ Address.[ mailbox john_doe ]) & Field.(Date $ now ()) & empty let stream = Header.to_stream header let () = let rec go () = match stream () with | Some buf -> print_string buf; go () | None -> () in go ()
This code produces the following header:
Date: 2 Aug 2019 14:10:10 GMT To: John "D." <john@doe.org> Sender: romain.calascibetta@gmail.com Subject: A Simple Mail
78-character rule
One aspect about email and SMTP is about some historical rules of how to generate them. One of them is about the limitation of bytes per line. Indeed, a generator of mail should emit at most 80 bytes per line - and, of course, it should emits entirely the email line per line.
So
mrmime has his own encoder which tries to wrap your mail into this limit.
It was mostly inspired by Faraday and Format powered with
GADT to easily describe how to encode/generate parts of an email.
A multipart email generator
Of course, the main point about email is to be able to generate a multipart
email - just to be able to send file attachments. And, of course, a deep work
was done about that to make parts, compose them into specific
Content-Type
fields and merge them into one email.
Eventually, you can easily make a stream from it, which respects rules (78 bytes per line, stream line per line) and use it directly into an SMTP implementation.
This is what we did with the project `facteur`. It's a little command-line tool to send with file attachement mails in pure OCaml - but it works only on an UNIX operating system for instance.
Behind the forest
Even if you are able to parse and generate an email, more work is needed to get the expected results.
Indeed, email is a exchange unit between people and the biggest deal on that is to find a common way to ensure a understable communication each others. About that, encoding is probably the most important piece and when a French person wants to communicate with a latin1 encoding, an American person can still use ASCII.
Rosetta
So about this problem, the choice was made to unify any contents to UTF-8 as the
most general encoding of the world. So, we did some libraries which map an encoding flow
to Unicode code-point, and we use
uutf (thanks to dbuenzli) to normalize it to UTF-8.
The main goal is to avoid a headache to the user about that and even if contents of the mail is encoded with latin1 we ensure to translate it correctly (and according RFCs) to UTF-8.
This project is `rosetta` and it comes with:
Pecu and Base64
Then, bodies can be encoded in some ways, 2 precisely (if we took the main standard):
- A base64 encoding, used to store your file
- A quoted-printable encoding
So, about the
base64 package, it comes with a sub-package
base64.rfc2045
which respects the special case to encode a body according RFC2045 and SMTP
limitation.
Then,
pecu was made to encode and decode quoted-printable contents. It was
tested and fuzzed of course like any others MirageOS's libraries.
These libraries are needed for an other historical reason which is: bytes used to store mail should use only 7 bits instead of 8 bits. This is the purpose of the base64 and the quoted-printable encoding which uses only 127 possibilities of a byte. Again, this limitation comes with SMTP protocol.
Conclusion
mrmime is tackling the difficult task to parse and generate emails according to 50 years of usability, several RFCs and legacy rules.
So, it
still is an experimental project. We reach the first version of it because we
are currently able to parse many mails and then generate them correctly.
Of course, a bug (a malformed mail, a server which does not respect standards or a bad use of our API) can appear easily where we did not test everything. But we have the feeling it was the time to release it and let people to use it.
The best feedback about
mrmime and the best improvement is yours. So don't be
afraid to use it and start to hack your emails with it.
A look back on OCaml since 2011 — OCamlPro, Sep 20, 2019 jour…Read more...!Hide
Frama-C 19.1 (Potassium) is out. Download ithere. — Frama-C, Sep 17, 2019
Coq 8.10+beta3 is out — Coq, Sep 16, 2019
The third beta release of Coq 8.10 is available for testing.
This third β version includes various bug fixes and improvements, including:
- improved warning on coercion path ambiguity;
- support for OCaml extraction of primitive machine integers;
- fix for the soundness issue with template polymorphism;
- fix extraction of dependent record projections to OCaml.
More details are given in the user manual.
Feedback and bug reports are extremely welcome.
OCaml Developer at Ahrefs Pte Ltd (Full-time) — Functional Jobs (FunctionalJobs.com), Sep 14, 2019 wi…
We offer: - Competitive compensation package - Informal and thriving work atmosphere - [SG office] First-class workplace equipment (hardware & tools) - Above-average perks and fringe benefits
Work location for this role could be: - Singapore - Remote
Get information on how to apply for this position.Hide
Compiler Engineer at Axoni (Full-time) — Functional Jobs (FunctionalJobs.com), Sep 13, 2019 b…Read more....Hide
Updated Cheat Sheets: OCaml Language and OCaml Standard Library — OCamlPro, Sep 13, 2019…Read more...!Hide
Frama-Clang 0.0.7 is out. Download ithere. — Frama-C, Sep 13, 2019
Decompress: Experiences with OCaml optimization — Tarides (Romain Calascibetta), Sep 13, 2019 t… the performance of
decompress with a C
implementation (like zlib or miniz) is obviously not very fair.
However, using something like
decompress instead of C implementations can be
very interesting for many purposes, especially when thinking about unikernels.
As we said in the previous article, we can take the advantage of the runtime
and the type-system to provide something safer (of course, it's not really
true since zlib has received several security audits).
The main idea in this article is not to give snippets to copy/paste into your codebase but to explain some behaviors of the compiler / runtime and hopefully give you some ideas about how to optimize your own code. We'll discuss the following optimizations:
- specialization
- inlining
- untagged integers
- exceptions
- unrolling
- hot-loop
- caml_modify
- representation sizes
Cautionary advice
Before we begin discussing optimization, keep this rule in mind:
Only perform optimization at the end of the development process.
An optimization pass can change your code significantly, so you need to keep a state of your project that can be trusted. This state will provide a comparison point for both benchmarks and behaviors. In other words, your stable implementation will be the oracle for your benchmarks. If you start with nothing, you'll achieve arbitrarily-good performance at the cost of arbitrary behavior!
We optimized
decompress because we are using it in bigger projects for a long
time (2 years). So we have an oracle (even if
zlib can act as an oracle in
this special case).
Specialization
One of the biggest specializations in
decompress is regarding the
min
function. If you don't know, in OCaml
min is polymorphic; you can compare
anything. So you probably have some concerns about how
min is implemented?
You are right to be concerned: if you examine the details,
min calls the C
function
do_compare_val, which traverses your structure and does a comparison
according the run-time representation of your structure. Of course, for integers, it
should be only a
cmpq assembly instruction. However, some simple code like:
let x = min 0 1
will produce this CMM and assembly code:
(let x/1002 (app{main.ml:1,8-15} "camlStdlib__min_1028" 1 3 val) ...)
.L101: movq $3, %rbx movq $1, %rax call camlStdlib__min_1028@PLT
Note that beta-reduction, inlining and specialization were not done in this code. OCaml does not optimize your code very much – the good point is predictability of the produced assembly output.
If you help the compiler a little bit with:
external ( <= ) : int -> int -> bool = "%lessequal" let min a b = if a <= b then a else b [@@inline] let x = min 0 1
We have:
(function{main.ml:2,8-43} camlMain__min_1003 (a/1004: val b/1005: val) (if (<= a/1004 b/1005) a/1004 b/1005)) (function camlMain__entry () (let x/1006 1 (store val(root-init) (+a "camlMain" 8) 1)) 1a)
.L101: cmpq %rbx, %rax jg .L100 ret
So we have all optimizations, in this produced code,
x was evaluated as
0
(
let x/... (store ... 1)) (beta-reduction and inlining) and
min was
specialized to accept only integers – so we are able to emit
cmpq.
Results
With specialization, we won 10 Mb/s on decompression, where
min is used
in several places. We completely avoid an indirection and a call to the slow
do_compare_val function.
This kind of specialization is already done by `flambda`, however, we currently use OCaml 4.07.1. So we decided to this kind of optimization by ourselves.
Inlining
In the first example, we showed code with the
[@@inline] keyword which is
useful to force the compiler to inline a little function. We will go outside the
OCaml world and study C code (gcc 5.4.0) to really understand
inlining.
In fact, inlining is not necessarily the best optimization. Consider the following (nonsensical) C program:
#include <stdio.h> #include <string.h> #include <unistd.h> #include <time.h> #include <stdlib.h> #ifdef HIDE_ALIGNEMENT __attribute__((noinline, noclone)) #endif void * hide(void * p) { return p; } int main(int ac, const char *av[]) { char *s = calloc(1 << 20, 1); s = hide(s); memset(s, 'B', 100000); clock_t start = clock(); for (int i = 0; i < 1280000; ++i) s[strlen(s)] = 'A'; clock_t end = clock(); printf("%lld\n", (long long) (end-start)); return 0; }
We will compile this code with
-O2 (the second level of optimization in C),
once with
-DHIDE_ALIGNEMENT and once without. The assembly emitted differs:
.L3: movq %rbp, %rdi call strlen subl $1, %ebx movb $65, 0(%rbp,%rax) jne .L3
.L3: movl (%rdx), %ecx addq $4, %rdx leal -16843009(%rcx), %eax notl %ecx andl %ecx, %eax andl $-2139062144, %eax je .L3
In the first output (with
-DHIDE_ALIGNEMENT), the optimization pass
decides to disable inlining of
strlen; in the second output (without
-DHIDEAlIGNEMENT), it decides to inline
strlen (and do some other clever
optimizations). The reason behind this complex behavior from the compiler is
clearly described here.
But what we want to say is that inlining is not an automatic optimization;
it might act as a pessimization. This is the goal of
flambda: do the right
optimization under the right context. If you are really curious about what
gcc
does and why, even if it's very interesting, the reverse engineering of the
optimization process and which information is relevant about the choice to
optimize or not is deep, long and surely too complicated.
A non-spontaneous optimization is to annotate some parts of your code with
[@@inline never] – so, explicitly say to the compiler to not inline the
function. This constraint is to help the compiler to generate a smaller code
which will have more chance to fit under the processor cache.
For all of these reasons,
[@@inline] should be used sparingly and an oracle to
compare performances if you inline or not this or this function is necessary to
avoid a pessimization.
In
decompress
Inlining in
decompress was done on small functions which need to allocate
to return a value. If we inline them, we can take the opportunity to store
returned value in registers (of course, it depends how many registers are free).
As we said, the goal of the inflator is to translate a bit sequence to a byte. The largest bit sequence possible according to RFC 1951 has length 15. So, when we process an inputs flow, we eat it 15 bits per 15 bits. For each packet, we want to recognize an existing associated bit sequence and then, binded values will be the real length of the bit sequence and the byte:
val find : bits:int -> { len: int; byte: int; }
So for each call to this function, we need to allocate a record/tuple. It's
why we choose to inline this function.
min was inlined too and some other
small functions. But as we said, the situation is complex; where we think that
inlining can help us, it's not systematically true.
NOTE: we can recognize bits sequence with, at most, 15 bits because a Huffman coding is prefix-free.
Untagged integers
When reading assembly, the integer
0 is written as
$1.
It's because of the GC bit needed to differentiate a pointer
and an unboxed integer. This is why, in OCaml, we talk about a 31-bits integer
or a 63-bits integer (depending on your architecture).
We will not try to start a debate about this arbitrary choice on the representation of an integer in OCaml. However, we can talk about some operations which can have an impact on performances.
The biggest example is about the
mod operation. Between OCaml and C,
% or
mod should be the same:
let f a b = a mod b
The output assembly is:
.L105: movq %rdi, %rcx sarq $1, %rcx // b >> 1 movq (%rsp), %rax sarq $1, %rax // a >> 1 testq %rcx, %rcx // b != 0 je .L107 cqto idivq %rcx // a % b jmp .L106 .L107: movq caml_backtrace_pos@GOTPCREL(%rip), %rax xorq %rbx, %rbx movl %ebx, (%rax) movq caml_exn_Division_by_zero@GOTPCREL(%rip), %rax call caml_raise_exn@PLT .L106: salq $1, %rdx // x << 1 incq %rdx // x + 1 movq %rbx, %rax
where idiomatically the same C code produce:
.L2: movl -12(%rbp), %eax cltd idivl -8(%rbp) movl %edx, -4(%rbp)
Of course, we can notice firstly the exception in OCaml (
Divided_by_zero) -
which is pretty good because it protects us against an interrupt from assembly
(and keep the trace). Then, we need to untag
a and
b with
sarq assembly
operation. We do, as the C code,
idiv and then we must retag returned value
x with
salq and
incq.
So in some parts, it should be more interesting to use
Nativeint. However, by
default, a
nativeint is boxed. boxed means that the value is allocated in
the OCaml heap alongside a header.
Of course, this is not what we want so, if our
nativeint ref (to have
side-effect, like
x) stay inside a function and then, you return the real
value with the deref
! operator, OCaml, by a good planet alignment, can
directly use registers and real integers. So it should be possible to avoid
these needed conversions.
Readability versus performance
We use this optimization only in few parts of the code. In fact, switch
between
int and
nativeint is little bit noisy:
hold := Nativeint.logor !hold Nativeint.(shift_left (of_int (unsafe_get_uint8 d.i !i_pos)) !bits)
In the end, we only gained 0.5Mb/s of inflation rate, so it's not worthwhile to do systematically this optimization. Especially that the gain is not very big. But this case show a more troubling problem: loss of readability.
In fact, we can optimize more and more a code (OCaml or C) but we lost, step by
step, readability. You should be afraid by the implementation of
strlen for
example. In the end, the loss of readability makes it harder to understand the purpose
of the code, leading to errors whenever some other person (or you in 10 years time)
tries to make a change.
And we think that this kind of optimization is not the way of OCaml in general where we prefer to produce an understandable and abstracted code than a cryptic and super fast one.
Again,
flambda wants to fix this problem and let the compiler to do this
optimization. The goal is to be able to write a fast code without any pain.
Exceptions
If you remember our article about the release of
base64, we talked a
bit about exceptions and used them as a jump. In fact, it's pretty
common for an OCaml developer to break the control-flow with an exception.
Behind this common design/optimization, it's about calling convention.
Indeed, choose the jump word to describe OCaml exception is not the best where
we don't use
setjmp/
longjmp.
In the details, when you start a code with a
try .. with, OCaml saves a trap
in the stack which contains information about the
with, the catcher. Then,
when you
raise, you jump directly to this trap and can just discard several
stack frames (and, by this way, you did not check each return codes).
In several places and mostly in the hot-loop, we use this pattern. However, it completely breaks the control flow and can be error-prone.
To limit errors and because this pattern is usual, we prefer to use a local exception which will be used only inside the function. By this way, we enforce the fact that exception should not (and can not) be caught by something else than inside the function.
let exception Break in ( try while !max >= 1 do if bl_count.(!max) != 0 then raise_notrace Break ; decr max done with Break -> () ) ;
This code above produce this assembly code:
.L105: pushq %r14 movq %rsp, %r14 .L103: cmpq $3, %rdi // while !max >= 1 jl .L102 movq -4(%rbx,%rdi,4), %rsi // bl_count,(!max) cmpq $1, %rsi // bl_count.(!max) != 0 je .L104 movq %r14, %rsp popq %r14 ret // raise_notrace Break .L104: addq $-2, %rdi // decr max movq %rdi, 16(%rsp) jmp .L103
Where the
ret is the
raise_notrace Break. A
raise_notrace is needed,
otherwise, you will see:
movq caml_backtrace_pos@GOTPCREL(%rip), %rbx xorq %rdi, %rdi movl %edi, (%rbx) call caml_raise_exn@PLT
Instead the
ret assembly code. Indeed, in this case, we need to store where we
raised the exception.
Unrolling
When we showed the optimization done by
gcc when the string is aligned,
gcc
did another optimization. Instead of setting the string byte per byte, it decides to
update it 4 bytes per 4 bytes.
This kind of this optimization is an unroll and we did it in
decompress.
Indeed, when we reach the copy opcode emitted by the lz77
compressor, we want to blit length byte(s) from a source to the outputs
flow. It can appear that this
memcpy can be optimized to copy 4 bytes per 4
bytes – 4 bytes is generally a good idea where it's the size of an
int32 and
should fit under any architectures.
let blit src src_off dst dst_off = if dst_off – src_off < 4 then slow_blit src src_off dst dst_off else let len0 = len land 3 in let len1 = len asr 2 in for i = 0 to len1 – 1 do let i = i * 4 in let v = unsafe_get_uint32 src (src_off + i) in unsafe_set_uint32 dst (dst_off + i) v ; done ; for i = 0 to len0 – 1 do let i = len1 * 4 + i in let v = unsafe_get_uint8 src (src_off + i) in unsafe_set_uint8 dst (dst_off + i) v ; done
In this code, at the beginning, we copy 4 bytes per 4 bytes and if
len is not
a multiple of 4, we start the trailing loop to copy byte per byte then. In
this context, OCaml can unbox
int32 and use registers. So this function does
not deal with the heap, and by this way, with the garbage collector.
Results
In the end, we gained an extra 10Mb/s of inflation rate. The
blit function is the
most important function when it comes to inflating the window to an output flow.
As the specialization on the
min function, this is one of the biggest optimization on
decompress.
hot-loop
A common design about decompression (but we can find it on hash implementation
too), is the hot-loop. An hot-loop is mainly a loop on the most common
operation in your process. In the context of
decompress, the hot-loop is
about a repeated translation from bits-sequence to byte(s) from the inputs flow
to the outputs flow and the window.
The main idea behind the hot-loop is to initialize all information needed for the translation before to start the hot-loop. Then, it's mostly an imperative loop with a pattern-matching which corresponds to the current state of the global computation.
In OCaml, we can take this opportunity to use
int ref (or
nativeint
ref), and then, they will be translated into registers (which is the fastest
area to store something).
Another deal inside the hot-loop is to avoid any allocation – and it's why we
talk about
int or
nativeint. Indeed, a more complex structure like an option
will add a blocker to the garbage collection (a call to
caml_call_gc).
Of course, this kind of design is completely wrong if we think in a functional way. However, this is the (biggest?) advantage of OCaml: hide this ugly/hacky part inside a functional interface.
In the API, we talked about a state which represents the inflation (or the deflation). At the beginning, the goal is to store into some references essentials values like the position into the inputs flow, bits available, dictionary, etc. Then, we launch the hot-loop and only at the end, we update the state.
So we keep the optimal design about inflation and the functional way outside the hot-loop.
caml_modify
One issue that we need to consider is the call to
caml_modify. In
fact, for a complex data-structure like an
int array or a
int option (so,
other than an integer or a boolean or an immediate value), values can move to the
major heap.
In this context,
caml_modify is used to assign a new value into your mutable
block. It is a bit slower than a simple assignment but needed to
ensure pointer correspondence between minor heap and major heap.
With this OCaml code for example:
type t = { mutable v : int option } let f t v = t.v <- v
We produce this assembly:
camlExample__f_1004: subq $8, %rsp movq %rax, %rdi movq %rbx, %rsi call caml_modify@PLT movq $1, %rax addq $8, %rsp ret
Where we see the call to
caml_modify which will be take care about the
assignment of
v into
t.v. This call is needed mostly because the type of
t.v is not an immediate value like an integer. So, for many values in the
inflator and the deflator, we mostly use integers.
Of course, at some points, we use
int array and set them at some specific
points of the inflator – where we inflated the dictionary. However, the impact
of
caml_modify is not very clear where it is commonly pretty fast.
Sometimes, however, it can be a real bottleneck in your computation and this depends on how long your values live in the heap. A little program (which is not very reproducible) can show that:
let t = Array.init (int_of_string Sys.argv.(1)) (fun _ -> Random.int 256) let pr fmt = Format.printf fmt type t0 = { mutable v : int option } type t1 = { v : int option } let f0 (t0 : t0) = for i = 0 to Array.length t – 1 do let v = match t0.v, t.(i) with | Some _ as v, _ -> v | None, 5 -> Some i | None, _ -> None in t0.v <- v done; t0 let f1 (t1 : t1) = let t1 = ref t1 in for i = 0 to Array.length t – 1 do let v = match !t1.v, t.(i) with | Some _ as v, _ -> v | None, 5 -> Some i | None, _ -> None in t1 := { v } done; !t1 let () = let t0 : t0 = { v= None } in let t1 : t1 = { v= None } in let time0 = Unix.gettimeofday () in ignore (f0 t0) ; let time1 = Unix.gettimeofday () in ignore (f1 t1) ; let time2 = Unix.gettimeofday () in pr "f0: %f ns\n%!" (time1 -. time0) ; pr "f1: %f ns\n%!" (time2 -. time1) ; ()
In our bare-metal server, if you launch the program with 1000, the
f0
computation, even if it has
caml_modify will be the fastest. However, if you
launch the program with 1000000000,
f1 will be the fastest.
$ ./a.out 1000 f0: 0.000006 ns f1: 0.000015 ns $ ./a.out 1000000000 f0: 7.931782 ns f1: 5.719370 ns
About
decompress
At the beginning, our choice was made to have, as @dbuenzli does, mutable structure to represent state. Then, @yallop did a big patch to update it to an immutable state and we won 9Mb/s on inflation.
However, the new version is more focused on the hot-loop and it is 3 times faster than before.
As we said, the deal about
caml_modify is not clear and depends a lot about
how long your data lives in the heap and how many times you want to update it.
If we localize
caml_modify only on few places, it should be fine. But it still
is one of the most complex question about (macro?) optimization.
Smaller representation
We've discussed the impact that integer types can have on the use of immediate values. More generally, the choice of type to represent your values can have significant performance implications.
For example, a dictionary which associates a bits-sequence (an integer) to the
length of it AND the byte, it can be represented by a:
(int * int) array, or
more idiomatically
{ len: int; byte: int; } array (which is structurally the
same).
However, that means an allocation for each bytes to represent every bytes.
Extraction of it will need an allocation if
find : bits:int -> { len: int;
byte: int; } is not inlined as we said. And about memory, the array can be
really heavy in your heap.
At this point, we used
spacetime to show how many blocks we allocated for a
common inflation and we saw that we allocate a lot. The choice was made to use
a smaller representation. Where
len can not be upper than 15 according RFC 1951
and when byte can represent only 256 possibilities (and should fit under one
byte), we can decide to merge them into one integer (which can have, at least,
31 bits).
let static_literal_tree = [| (8, 12); (8, 140); (8, 76); ... |] let static_literal_tree = Array.map (fun (len, byte) -> (len lsl 8) lor byte) static_literal_tree
In the code above, we just translate the static dictionary (for a STATIC DEFLATE
block) to a smaller representation where
len will be the left part of the
integer and
byte will be the right part. Of course, it's depends on what you
want to store.
Another point is readability. `cstruct-ppx` and
`bitstring` can help you but
decompress
wants to depend only on OCaml.
Conclusion
We conclude with some closing advice about optimising your OCaml programs:
Optimization is specific to your task. The points highlighted in this article may not fit your particular problem, but they are intended to give you ideas. Our optimizations were only possible because we completely assimilated the ideas of
zliband had a clear vision of what we really needed to optimize (like
blit).
As your first project, this article can not help you a lot to optimize your code where it's mostly about micro-optimization under a specific context (hot-loop). But it helps you to understand what is really done by the compiler – which is still really interesting.
Optimise only with respect to an oracle. All optimizations were done because we did a comparison point between the old implementation of
decompressand
zlibas oracles. Optimizations can change the semantics of your code and you should systematically take care at any step about expected behaviors. So it's a long run.
Use the predictability of the OCaml compiler to your advantage. For sure, the compiler does not optimize a lot your code – but it sill produce realistic programs if we think about performance. For many cases, you don't need to optimize your OCaml code. And the good point is about expected behavior.
The mind-link between the OCaml and the assembly exists (much more than the C and the assembly sometimes where we let the C compiler to optimize the code). The cool fact is to keep a mental-model about what is going on on your code easily without to be afraid by what the compiler can produce. And, in some critical parts like eqaf, it's really needed.
We have not discussed benchmarking, which is another hard issue: who should you
compare with? where? how? For example, a global comparison between
zlib and
decompress is not very relevant in many ways – especially because of the
garbage collector. This could be another article!
Finally, all of these optimizations should be done by
flambda; the difference
between compiling
decompress with or without
flambda is not very big. We
optimized
decompress by hand mostly to keep compatibility with OCaml (since
flambda needs another switch) and, in this way, to gain an understanding of
flambda optimizations so that we can use it effectively!
On complete ordered fields — Andrej Bauer, Sep 08, 2019 …Read more...!
As there are many constructive versions of order and completeness, let me spell out the definitions that are well adapted to the oddities of constructive mathematics. In classical logic these are all equivalent to the usual ones. Having to disentangle definitions when passing to constructive mathematics is a bit like learning how to be careful when passing from commutative to non-commutative algebra.
A partial order $\leq$ on a set $P$ is a reflexive, transitive and antisymmetric relation on $P$.
We are interested in linearly ordered fields, but constructively we need to take care, as the usual linearity, $x \leq y \lor y \leq x$, is quite difficult to satisfy, and may fail for reals.
A strict order on a set $P$ is a relation $<$ which is:
- irreflexive: $\lnot (x < x)$,
- tight: $\lnot (x < y \lor y < x) \Rightarrow x = y$,
- weakly linear: $x < y \Rightarrow x < z \lor z < y$
The associated partial order is defined by $x \leq y \Leftrightarrow \lnot (y < x)$. The reflexivity, antisymmetry and transitivity of $\leq$ follow respectively from irreflexivity, tightness, and weak linearity of $<$.
Next, an element $x \in P$ is an upper bound for $S \subseteq P$ when $y \leq x$ for all $y \in P$. An element $x \in P$ is the supremum of $S \subseteq P$ if it is an upper bound for $S$, and for every $y < x$ there exists $z \in S$ such that $y < z$. A poset $P$ is (Dedekind-MacNeille) complete when every inhabited bounded subset has a supremum (for the classically trained, $S \subseteq P$ is inhabited when there exists $x \in S$, and this is not the same as $S \neq \emptyset$).
A basic exercise is to give a non-trivial complete order, i.e., a strict order $<$ whose associated partial order $\leq$ is complete.
Theorem: If there exists a non-trivial complete order then excluded middle holds.
Proof. Suppose $<$ is a strict order on a set $P$ whose associated order $\leq$ is complete, and there exist $a, b \in P$ such that $a < b$. Let $\phi$ be any proposition. Consider the set $S = \lbrace x \in P \mid x = a \lor (\phi \land x = b)\rbrace$. Observe that $\phi$ is equivalent to $b \in S$. Because $a \in S \subseteq \lbrace a, b\rbrace$, the set $S$ is inhabited and bounded, so let $s$ be its supremum. We know that $a < s$ or $s < b$, from which we can decide $\phi$:
- If $a < s$ then $b \in S$: indeed, there exists $c \in S$ such that $a < c$, but then $c = b$. In this case $\phi$ holds.
- If $s < b$ then $\lnot(b \in S)$: if we had $b \in S$ then $S = \lbrace a, b \rbrace$ and $b = s < b$, which is impossible. In this case $\lnot\phi$. $\Box$
This immediately gives us the desired theorem.
Theorem (constructive): All complete ordered fields are isomorphic.
Proof. The definition of a complete ordered field requires $0 < 1$, therefore excluded middle holds. Now proceed with the usual classical proof. $\Box$
This is very odd, as I always thought that the MacNeille reals form a MacNeille complete ordered field. Recall that a MacNeille real is a pair $(L, U)$ of subsets of $\mathbb{Q}$ such that:
- $U$ is the set of upper bounds of $L$: $u \in U$ if, and only if, $\ell \leq u$ for all $\ell \in L$,
- $L$ is the set of lower bounds of $U$: $\ell \in L$ if, and only if, $\ell \leq u$ for all $u \in U$,
- $L$ and $U$ are inhabited.
Furthermore, the MacNeille reals are complete, as they are just the MacNeille completion of the rationals. We may define a strict order on them by stipulating that, for $x = (L_x, U_x)$ and $y = (L_y, U_y)$, $$x < y \iff \exists q \in U_x . \exists r \in L_y \,.\, q < r.$$ According to Peter Johnstone (Sketches of an Elephant, D4.7), the MacNeille reals form a commutative unital ring in which $x$ is invertible if, and only if, $x < 0 \lor x > 0$. So apparently, the weak linearity of the strict order is problematic.
What if we relax completeness? Two standard notions of completeness are:
- An ordered field $F$ is Cauchy-complete if every Cauchy sequence has a limit in $F$.
- An ordered field $F$ is Dedekind-complete if every Dedekind cut determines an element of $F$.
It is easy enough to find non-isomorphic Cauchy-complete fields. Order the field $\mathbb{Q}(x)$ of rational functions with rational coefficients by stipulating that it extends the order of $\mathbb{Q}$ and that $q < x$ for all $q \in \mathbb{Q}$. The Cauchy-completion of $\mathbb{Q}(x)$ is a Cauchy complete field which is not isomorphic to $\mathbb{Q}$. Caveat: I am speaking off the top of my head, do not trust this paragraph! (Or any other for that matter.)
Regarding Dedekind completeness, it is important constructively that we take two-sided Dedekind cuts, i.e., pairs $(L, U)$ of subsets of $F$ such that
- $L$ is lower-rounded: $q \in L \iff \exists r \in L . q < r$,
- $U$ is upper-rounded: $r \in U \iff \exists q \in U . q < r$,
- the cut is bounded: $L$ and $U$ are inhabited,
- the cut is disjoint: $L \cap U = \emptyset$,
- the cut is located: if $q < r$ then $L \in q$ or $r \in U$.
Dedekind completeness states that for every Dedekind cut $(L, U)$ in $F$ there exists a unique $x \in F$ such that $L = \lbrace y \in F \mid y < x\rbrace$ and $U = \lbrace y \in F \mid x < y\rbrace$. Constructively this is a weaker form of completeness than the Dedekind-MacNeille one, but classically they coincide. Thus we cannot hope to exhibit constructively two non-isomorphic Dedekind-complete ordered fields (because constructive results are also classically valid). But perhaps there is a model of constructive mathematics where such strange fields exist. Does anyone know of one?Hide
An introduction to fuzzing OCaml with AFL, Crowbar and Bun — Tarides (Nathan Rebours), Sep 04, 2019. Th…Read more.... The
README contains all the information you need to understand,
build and fuzz them yourself.
What is AFL?
AFL actually isn't just a fuzzer but a set of tools. What makes it so good is that it doesn't just blindly send random input to your program hoping for it to crash; it inspects the execution paths of the program and uses that information to figure out which mutations to apply to the previous inputs to trigger new execution paths. This approach allows for much more efficient and reliable fuzzing (as it will try to maximize coverage) but requires the binaries to be instrumented so the execution can be monitored.
AFL provides wrappers for the common C compilers that you can use to produce the instrumented
binaries along with the CLI fuzzing client:
afl-fuzz.
afl-fuzz is straight-forward to use. It takes an input directory containing a few initial valid
inputs to your program, an output directory and the instrumented binary. It will then repeatedly
mutate the inputs and feed them to the program, registering the ones that lead to crashes or
hangs in the output directory.
Because it works in such a way, it makes it very easy to fuzz a parser.
To fuzz a
parse.exe binary, that takes a file as its first command-line argument and parses it,
you can invoke
afl-fuzz in the following way:
$ afl-fuzz -i inputs/ -o findings/ /path/to/parse.exe @@
The
findings/ directory is where
afl-fuzz will write the crashes it finds, it will create it
for you if it doesn't exist.
The
inputs/ directory contains one or more valid input files for your
program. By valid we mean "that don't crash your program".
Finally the
@@ part tells
afl-fuzz where on the command line the input file should be passed to
your program, in our case, as the first argument.
Note that it is possible to supply
afl-fuzz with more detail about how to invoke your program. If
you need to pass it command-line options for instance, you can run it as:
$ afl-fuzz -i inputs/ -o findings/ -- /path/to/parse.exe --option=value @@
If you wish to fuzz a program that takes its input from standard input, you can also do that by removing the
@@ from the
afl-fuzz invocation.
Once
afl-fuzz starts, it will draw a fancy looking table on the standard output to keep you
updated about its progress. From there, you'll mostly be interested in is the top right
corner which contains the number of crashes and hangs it has found so far:
You might need to change some of your CPU settings to achieve better performance while fuzzing.
afl-fuzz's output will tell you if that's the case and guide you through the steps required to
make that happen.
Using AFL to fuzz an OCaml parser
First of all, if you want to fuzz an OCaml program with AFL you'll need to produce an instrumented
binary.
afl-fuzz has an option to work with regular binaries but you'd lose a lot of what makes it
efficient. To instrument your binary you can simply install a
+afl opam switch and build your
executable from there. AFL compiler variants are available from OCaml
4.05.0 onwards. To install such
a switch you can run:
$ opam switch create fuzzing-switch 4.07.1+afl
If your program already parses the standard input or a file given to it via the command line, you
can simply build the executable from your
+afl switch and adapt the above examples. If it doesn't,
it's still easy to fuzz any parsing function.
Imagine we have a
simple-parser library which exposes the following
parse_int function:
val parse_int: string -> (int, [> `Msg of string]) result (** Parse the given string as an int or return [Error (`Msg _)]. Does not raise, usually... *)
We want to use AFL to make sure our function is robust and won't crash when receiving unexpected inputs. As you can see the function returns a result and isn't supposed to raise exceptions. We want to make sure that's true.
To find crashes, AFL traps the signals sent by your program. That means that it will consider
uncaught OCaml exceptions as crashes. That's good because it makes it really simple to write a
fuzz_me.ml executable that fits what
afl-fuzz expects:
let () = let file = Sys.argv.(1) in let ic = open_in file in let length = in_channel_length ic in let content = really_input_string ic length in close_in ic; ignore (Simple_parser.parse_int content)
We have to provide example inputs to AFL so we can write a
valid file to the
inputs/ directory
containing
123 and an
invalid file containing
not an int. Both should parse without crashing
and make good starting point for AFL as they should trigger different execution paths.
Because we want to make sure AFL does find crashes we can try to hide a bug in our function:
let parse_int s = match List.init (String.length s) (String.get s) with | ['a'; 'b'; 'c'] -> failwith "secret crash" | _ -> ( match int_of_string_opt s with | None -> Error (`Msg (Printf.sprintf "Not an int: %S" s)) | Some i -> Ok i)
Now we just have to build our native binary from the right switch and let
afl-fuzz do the rest:
$ afl-fuzz -i inputs/ -o findings/ ./fuzz_me.exe @@
It should find that the
abc input leads to a crash rather quickly. Once it does, you'll see it in
the top right corner of its output as shown in the picture from the previous section.
At this point you can interrupt
afl-fuzz and have a look at the content of the
findings/crashes:
$ ls findings/crashes/ id:000000,sig:06,src:000111,op:havoc,rep:16 README.txt
As you can see it contains a
README.txt which will give you some details about the
afl-fuzz
invocation used to find the crashes and how to reproduce them in the folder and a file of the form
id:...,sig:...,src:...,op:...,rep:... per crash it found. Here there's just one:
$ cat findings/crashes/id:000000,sig:06,src:000111,op:havoc,rep:16 abc
As expected it contains our special input that triggers our secret crash. We can rerun the program with that input ourselves to make sure it does trigger it:
$ ./fuzz_me.exe findings/crashes/id:000000,sig:06,src:000111,op:havoc,rep:16 Fatal error: exception Failure("secret crash")
No surprise here, it does trigger our uncaught exception and crashes shamefully.
Using Crowbar and AFL for property-based testing
This works well but only being able to fuzz parsers is quite a limitation. That's where Crowbar comes into play.
Crowbar is a property-based testing framework. It's much like Haskell's QuickCheck. To test a given function, you define how its arguments are shaped, a set of properties the result should satisfy and it will make sure they hold with any combinations of randomly generated arguments. Let's clarify that with an example.
I wrote a library called
Awesome_list and I want to test its
sort function:
val sort: int list -> int list (** Sorts the given list of integers. Result list is sorted in increasing order, most of the time... *)
I want to make sure it really works so I'm going to use Crowbar to generate a whole lot of
lists of integers and verify that when I sort them with
Awesome_list.sort the result is, well...
sorted.
We'll write our tests in a
fuzz_me.ml file.
First we need to tell Crowbar how to generate arguments for our function. It exposes some
combinators to help you do that:
let int_list = Crowbar.(list (range 10))
Here we're telling Crowbar to generate lists of any size, containing integers ranging from 0 to 10. Crowbar also exposes more complex and custom generator combinators so don't worry, you can use it to build more complex arguments.
Now we need to define our property. Once again it's pretty simple, we just want the output to be sorted:
let is_sorted l = let rec is_sorted = function | [] | [_] -> true | hd::(hd'::_ as tl) -> hd <= hd' && is_sorted tl in Crowbar.check (is_sorted l)
All that's left to do now is to register our test:
let () = Crowbar.add_test ~name:"Awesome_list.sort" [int_list] (fun l -> is_sorted (Awesome_list.sort l))
and to compile that
fuzz_me.ml file to a binary. Crowbar will take care of the magic.
We can run that binary in "Quickcheck" mode where it will either try a certain amount of random
inputs or keep trying until one of the properties breaks depending on the command-line options
we pass it.
What we're interested in here is its less common "AFL" mode. Crowbar made it so our executable
can be used with
afl-fuzz just like that:
$ afl-fuzz -i inputs -o findings -- ./fuzz_me.exe @@
What will happen then is that our
fuzz_me.exe binary will read the inputs provided by
afl-fuzz
and use it to determine which test to run and how to generate the arguments to pass to our function.
If the properties are satisfied, the binary will exit normally; if they aren't, it will make sure
that
afl-fuzz interprets that as a crash by raising an exception.
A nice side-effect of Crowbar's approach is that
afl-fuzz will still be able to pick up
crashes. For instance, if we implement
Awesome_list.sort as:
let sort = function | [1; 2; 3] -> failwith "secret crash" | [4; 5; 6] -> [6; 5; 4] | l -> List.sort Pervasives.compare l
and use AFL and Crowbar to fuzz-test our function, it will find two crashes: one for the input
[1; 2; 3] which triggers a crash and one for
[4; 5; 6] for which the
is_sorted
property won't hold.
The content of the input files found by
afl-fuzz itself won't be of much help as it needs to be
interpreted by Crowbar to build the arguments that were passed to the function to trigger the bug.
We can invoke the
fuzz_me.exe binary ourselves on one of the files in
findings/crashes
and the Crowbar binary will replay the test and give us some more helpful information about what
exactly is going on:
$ ./fuzz_me.exe findings/crashes/id\:000000\,sig\:06\,src\:000011\,op\:flip1\,pos\:5 Awesome_list.sort: .... Awesome_list.sort: FAIL When given the input: [1; 2; 3] the test threw an exception: Failure("secret crash") Raised at file "stdlib.ml", line 33, characters 17-33 Called from file "awesome-list/fuzz/fuzz_me.ml", line 11, characters 78-99 Called from file "src/crowbar.ml", line 264, characters 16-19 Fatal error: exception Crowbar.TestFailure $ ./fuzz_me.exe findings/crashes/id\:000001\,sig\:06\,src\:000027\,op\:arith16\,pos\:5\,val\:+7 Awesome_list.sort: .... Awesome_list.sort: FAIL When given the input: [4; 5; 6] the test failed: check false Fatal error: exception Crowbar.TestFailure
We can see the actual inputs as well as distinguish the one that broke the invariant from the one that triggered a crash.
Using
bun to run fuzz testing in CI
While AFL and Crowbar provide no guarantees they can give you confidence that your implementation is not broken. Now that you know how to use them, a natural follow-up is to want to run fuzz tests in your CI to enforce that level of confidence.
Problem is, AFL isn't very CI friendly. First it has this refreshing output that isn't going to look great on your travis builds output and it doesn't tell you much besides that it could or couldn't find crashes or invariant infrigements
Hopefully, like most problems, this one has a solution:
`bun`.
bun is a CLI wrapper around
afl-fuzz, written in OCaml, that helps you get the best out of AFL
effortlessly. It mostly does two things:
The first is that it will run several
afl-fuzz processes in parallel
(one per core by default).
afl-fuzz starts with a bunch of deterministic steps. In my experience,
using parallel processes during this phase rarely proved very useful as they tend to find the same
bugs or slight variations of those bugs. It only achieves its full potential in the second phase of
fuzzing.
The second thing, which is the one we're the most interested in, is that
bun provides a useful
and CI-friendly summary of what's going on with all the fuzzing processes so far. When one of them
finds a crash, it will stop all processes and pretty-print all of the bug-triggering inputs to help
you reproduce and debug them locally. See an example
bun output after a crash was found:
Crashes found! Take a look; copy/paste to save for reproduction: 1432 echo JXJpaWl0IA== | base64 -d > crash_0.$(date -u +%s) 1433 echo NXJhkV8QAA== | base64 -d > crash_1.$(date -u +%s) 1434 echo J3Jh//9qdGFiYmkg | base64 -d > crash_2.$(date -u +%s) 1435 09:35.32:[ERROR]All fuzzers finished, but some crashes were found!
Using
bun is very similar to using
afl-fuzz. Going back to our first parser example, we can
fuzz it with
bun like this:
$ bun --input inputs/ --output findings/ /path/to/parse.exe
You'll note that you don't need to provide the
@@ anymore.
bun assumes that it should pass the
input as the first argument of your to-be-fuzzed binary.
bun also comes with an alternative
no-kill mode which lets all the fuzzers run indefinitely
instead of terminating them whenever a crash is discovered. It will regularly keep you updated on
the number of crashes discovered so far and when terminated will pretty-print each of them just like
it does in regular mode.
This mode can be convenient if you suspect your implementation may contain a lot of bugs and you don't want to go through the whole process of fuzz testing it to only find a single bug.
You can use it in CI by running
bun --no-kill via
timeout. For instance:
timeout --preserve-status 60m bun --no-kill --input inputs --output findings ./fuzz_me.exe
will fuzz
fuzz_me.exe for an hour no matter what happens. When
timeout terminates
bun, it will
provide you with a handful of bugs to fix!
Final words
I really want to encourage you to use those tools and fuzzing in general.
Crowbar and
bun are fairly new so you will probably encounter bugs or find that it lacks a feature
you want but combined with AFL they make for very nice tools to effectively test
critical components of your OCaml code base or infrastructure and detect newly-introduced bugs.
They are already used accross the MirageOS ecosystem where it has been used to fuzz the TCP/IP stack
mirage-tcpip and the DHCP implementation charrua thanks to
somerandompacket.
You can consult Crowbar's hall of fame to find out about bugs uncovered by this
approach.
I also encourage anyone interested to join us in using this promising toolchain, report those bugs, contribute those extra features and help the community build more robust software.
Finally if you wish to learn more about how to efficienly use fuzzing for testing I recommend the excellent Write Fuzzable Code article by John Regehr.Hide
What is algebraic about algebraic effects? — Andrej Bauer, Sep 02, 2019.…Read more....Hide
The blog moved from Wordpress to Jekyll — Andrej Bauer, Sep 02, 2019 …Read more... for proper documentation), etc. But all the tools are out there, it's just a simple matter of installing them:
- Jekyll Exporter - an exporter from Wordpress to Jekyll
- Jekyll - static pages blog, free of databases, with support for Markdown
- Staticman - a backend for blog comments
I decided to make the blog repository
mathematics-and-computation
public, as there is no good reason to keep it private. In fact, this way people
can contribute by making pull requests (see the
README.md.
I will use this post to test the working on the new blog, and especially the comments, so please excuse silly comments below.Hide
OCamlPro’s compiler team work update — OCamlPro, Aug 30, 2019, a…Read more..., as well as some compiler modifications that will benefit Flambda2.
This work is funded by JaneStreet.Hide
What the interns have wrought, 2019 edition — Jane Street, Aug 30, 2019
Jane Street’s intern program yet again is coming to an end, which is a nice opportunity to look back over the summer and see what they’ve accomplished.
Decompress: The New Decompress API — Tarides (Romain Calascibetta), Aug 26, 2019 appeared some years ago as a Mirage-compatible replacement for zlib
to be used for compiling a MirageOS unikernel with
ocaml-git. Today, this little project passes a major release with
substantial improvements in several domains.
decompress provides an API for inflating and deflating flows
[1]. The main
goal is to provide a platform-agnostic library: one which may be compiled on
any platform, including JavaScript. We surely cannot be faster than C
implementations like zstd or lz4, but we can play some
optimisation tricks to help bridge the gap. Additionally, OCaml can protect the
user against lot of bugs via the type-system and the runtime too (e.g. using
array bounds checking). `ocaml-tls` was implemented partly in
response to the famous failure of
openssl; a vulnerability
which could not exist in OCaml.
[1]: A flow, in MirageOS land, is an abstraction which wants to receive
and/or transmit something under a standard. So it's usual to say a TLS-flow
for example.
API design
The API should be the most difficult part of designing a library - it reveals what we can do and how we should do it. In this way, an API should:
constrain the user to avoid security issues; too much freedom can be a bad thing. As an example, consider the
Hashtbl.createfunction, which allows the user to pass
~random:falseto select a fixed hash function. The resulting hashtable suffers deterministic key collisions, which can be exploited by an attacker.
An example of good security-awareness in API design can be seen in digestif, which provided an
unsafe_compareinstead of the common
comparefunction (before
eqaf.0.5). In this way, it enforced the user to create an alias of it if they want to use a hash in a
Map– however, by this action, they should know that they are not protected against a timing-attack.
allow some degrees of freedom to fit within many environments; a constrained API cannot support a hostile context. For example, when compiling to an ESP32 target, even small details such as the length of a stream input buffer must be user-definable. When deploying to a server, memory consumption should be deterministic.
Of course, this is made difficult when too much freedom will enable misuse of the API – an example is dune which wants consciously to limit the user about what they can do with it.
imply an optimal design of how to use it. Possibilities should serve the user, but these can make the API harder to understand; this is why documentation is important. Your API should tell your users how it wants to be treated.
A dbuenzli API
From our experiences with protocol/format, one design stands out: the dbuenzli API. If you look into some famous libraries in the OCaml eco-system, you probably know uutf, jsonm or xmlm. All of these libraries provide the same API for computing a Unicode/JSON/XML flow – of course, the details are not the same.
From a MirageOS perspective, even if they use the
in_channel/
out_channel
abstraction rather than a Mirage flow, these libraries
are system-agnostic since they let the user to choose input and output buffers.
Most importantly, they don't use the standard OCaml
Unix module, which cannot
be used in a unikernel.
The APIs are pretty consistent and try to do their best-effort
[2] of
decoding. The design has a type state which represents the current system
status; the user passes this to
decode/
encode to carry out the processing.
Of course, these functions have a side-effect on the state internally, but
this is hidden from the user. One advantage of including states in a design is
that the underlying implementation is very amenable to compiler optimisations (e.g.
tail-call optimisation). Internally, of course, we have a porcelain
[3]
implementation where any details can have an rational explanation.
In the beginning,
decompress wanted to follow the same interface without the
mutability (a choice about performances) and it did. Then, the hard test was to
use it in a bigger project; in this case, ocaml-git. An iterative
process was used to determine what was really needed, what we should not provide
(like special cases) and what we should provide to reach an uniform API that is
not too difficult to understand.
From this experience, we finalised the initial
decompress API and it did not
change significantly for 4 versions (2 years).
[2]: best-effort means an user control on the error branch where we don't
leak exception (or more generally, any interrupts)
[3]: porcelain means implicit invariants held in the mind of the programmer
(or the assertions/comments).
The new
decompress API
The new
decompress keeps the same inflation logic, but drastically changes the
deflator to make the flush operation clearer. For many purposes, people don't
want to hand-craft their compressed flows – they just want
of_string/
to_string functions. However, in some contexts (like a PNG
encoder/decoder), the user should be able to play with
decompress in detail
(OpenPGP needs this too in RFC 4880).
The Zlib format
Both
decompress and zlib use Huffman coding, an algorithm
for building a dictionary of variable-length codewords for a given set of
symbols (in this case, bytes). The most common byte is assigned the shortest bit
sequence; less common bytes are assigned longer codewords. Using this
dictionary, we just translate each byte into its codeword and we should achieve
a good compression ratio. Of course, there are other details, such as the fact
that all Huffman codes are prefix-free. The compression can be
taken further with the LZ77 algorithm.
The zlib format, a superset of the RFC 1951 format, is easy to understand. We will only consider the RFC 1951 format, since zlib adds only minor details (such as checksums). It consists of several blocks: DEFLATE blocks, each with a little header, and the contents. There are 3 kinds of DEFLATE blocks:
- a FLAT block; no compression, just a blit from inputs to the current block.
- a FIXED block; compressed using a pre-computed Huffman code.
- a DYNAMIC block; compressed using a user-specified Huffman code.
The FIXED block uses a Huffman dictionary that is computed when the OCaml runtime is initialised. DYNAMIC blocks use dictionaries specified by the user, and so these must be transmitted alongside the data (after being compressed with another Huffman code!). The inflator decompresses this DYNAMIC dictionary and uses it to do the reverse translation from bit sequences to bytes.
Inflator
The design of the inflator did not change a lot from the last version of
decompress. Indeed, it's about to take an input, compute it and return an
output like a flow. Of course, the error case can be reached.
So the API is pretty-easy:
val decode : decoder -> [ `Await | `Flush | `End | `Malformed of string ]
As you can see, we have 4 cases: one which expects more inputs (
Await), the
second which asks to the user to flush internal buffer (
Flush), the
End case
when we reach the end of the flow and the
Malformed case when we encounter an
error.
For each case, the user can do several operations. Of course, about the
Await
case, they can refill the contents with an other inputs buffer with:
val src : decoder -> bigstring -> off:int -> len:int -> unit
This function provides the decoder a new input with
len bytes to read
starting at
off in the given
bigstring.
In the
Flush case, the user wants some information like how many bytes are
available in the current output buffer. Then, we should provide an action to
flush this output buffer. In the end, this output buffer should be given by
the user (how many bytes they want to allocate to store outputs flow).
type src = [ `Channel of in_channel | `Manual | `String of string ] val dst_rem : decoder -> int val flush : decoder -> unit val decoder : src -> o:bigstring -> w:bigstring -> decoder
The last function,
decoder, is the most interesting. It lets the user, at the
beginning, choose the context in which they want to inflate inputs. So they
choose:
src, where come from inputs flow
o, output buffer
w, window buffer
o will be used to store inflated outputs,
dst_rem will give to us how many
bytes inflator stored in
o and
flush will just set
decoder to be able to
recompute the flow.
w is needed for lz77 compression. However, as we said, we let
the user give us this intermediate buffer. The idea behind that is to let the
user prepare an inflation. For example, in ocaml-git, instead of
allocating
w systematically when we want to decompress a Git object, we
allocate
w one time per threads and all are able to use it and re-use it.
In this way, we avoid systematic allocations (and allocate only once time) which
can have a serious impact about performances.
The design is pretty close to one idea, a description step by the
decoder
function and a real computation loop with the
decode function. The idea is to
prepare the inflation with some information (like
w and
o) before the main
(and the most expensive) computation. Internally we do that too (but it's mostly
about a macro-optimization).
It's the purpose of OCaml in general, be able to have a powerful way to describe something (with constraints). In our case, we are very limited to what we need to describe. But, in others libraries like angstrom, the description step is huge (describe the parser according to the BNF) and then, we use it to the main computation, in the case of angstrom, the parsing (another example is [cmdliner][cmdliner]).
This is why
decoder can be considered as the main function where
decode can
be wrapped under a stream.
Deflator
The deflator is a new (complex) deal. Indeed, behind it we have two concepts:
- the encoder (according to RFC 1951)
- the compressor
For this new version of
decompress, we decide to separate these concepts where
one question leads all: how to put my compression algorithm? (instead to use
LZ77).
In fact, if you are interested in compression, several algorithms exist and, in some context, it's preferable to use lzwa for example or rabin's fingerprint (with duff), etc.
Functor
The first idea was to provide a functor which expects an implementation of the compression algorithm. However, the indirection of a functor comes with (big) performance cost. Consider the following functor example:
module type S = sig type t val add : t -> t -> t val one : t end module Make (S : S) = struct let succ x = S.add x S.one end include Make (struct type t = int let add a b = a + b let one = 1 end) let f x = succ x
Currently, with OCaml 4.07.1, the
f function will be a
caml_apply2. We might
wish for a simple _inlining_ optimisation, allowing
f to become an
addq instruction (indeed, `flambda` does this), but optimizing
functors is hard. As we learned from Pierre Chambart, it is possible
for the OCaml compiler to optimize functors directly, but this requires
respecting several constraints that are difficult to respect in practice.
Split encoder and compressor
So, the choice was done to made the encoder which respects RFC 1951 and the compressor under some constraints. However, this is not what zlib did and, by this way, we decided to provide a new design/API which did not follow, in first instance, zlib (or some others implementations like miniz).
To be fair, the choice from zlib and miniz comes from the first point about API and the context where they are used. The main problem is the shared queue between the encoder and the compressor. In C code, it can be hard for the user to deal with it (where they are liable for buffer overflows).
In OCaml and for
decompress, the shared queue can be well-abstracted and API
can ensure assumptions (like bounds checking).
Even if this design is much more complex than before, coverage tests are better
where we can separately test the encoder and the compressor. It breaks down the
initial black-box where compression was intrinsec with encoding – which was
error-prone. Indeed,
decompress had a bug about generation of
Huffman codes but we never reached it because the (bad)
compressor was not able to produce something (a specific lengh with a specific
distance) to get it.
NOTE: you have just read the main reason for the new version of
decompress!
The compressor
The compressor is the most easy part. The goal is to produce from an inputs flow, an outputs flow which is an other (more compacted) representation. This representation consists to:
- A literal, the byte as is
- A copy code with an offset and a length
The last one say to copy length byte(s) from offset. For example,
aaaa can
be compressed as
[ Literal 'a'; Copy (offset:1, len:3) ]. By this way, instead
to have 4 bytes, we have only 2 elements which will be compressed then by an
Huffman coding. This is the main idea of the lz77
compression.
However, the compressor should need to deal with the encoder. An easy interface, à la uutf should be:
val compress : state -> [ `Literal of char | `Copy of (int * int) | `End | `Await ]
But as I said, we need to feed a queue instead.
At this point, the purpose of the queue is not clear and not really explained. The signature above still is a valid and understandable design. Then, we can imagine passing
Literaland
Copydirectly to the encoder. However, we should (for performance purpose) use a delaying tactic between the compressor and the deflator[^4].
Behind this idea, it's to be able to implement an hot-loop on the encoder which will iter inside the shared queue and transmit/encode contents directly to the outputs buffer.
So, when we make a new
state, we let the user supply their queue:
val state : src -> w:bistring -> q:queue -> state val compress : state -> [ `Flush | `Await | `End ]
The
Flush case appears when the queue is full. Then, we refind the
w window
buffer which is needed to produce the
Copy code. A copy code is limited
according RFC 1951 where offset can not be upper than the length of the window
(commonly 32ko). length is limited too to
258 (an arbitrary choice).
Of course, about the
Await case, the compressor comes with a
src function as
the inflator. Then, we added some accessors,
literals and
distances. The
compressor does not build the Huffman coding which needs
frequencies, so we need firstly to keep counters about that inside the state and
a way to get them (and pass them to the encoder).
[4]: About that, you should be interesting by the reason of why GNU yes is so
fast where the secret is just about buffering.
The encoder
Finally, we can talk about the encoder which will take the shared queue filled by the compressor and provide an RFC 1951 compliant output flow.
However, we need to consider a special detail. When we want to make a DYNAMIC block from frequencies and then encode the inputs flow, we can reach a case where the shared queue contains an opcode (a literal or a copy) which does not appear in our dictionary.
In fact, if we want to encode
[ Literal 'a'; Literal 'b' ], we will not try to
make a dictionary which will contains the 256 possibilities of a byte but we
will only make a dictionary from frequencies which contains only
'a' and
'b'. By this way, we can reach a case where the queue contains an opcode
(like
Literal 'c') which can not be encoded by the pre-determined
Huffman coding – remember, the DYNAMIC block starts with
the dictionary.
Another point is about inputs. The encoder expects, of course, contents from the shared queue but it wants from the user the way to encode contents: which block we want to emit. So it has two entries:
- the shared queue
- an user-entry
So for many real tests, we decided to provide this kind of API:
type dst = [ `Channel of out_channel | `Buffer of Buffer.t | `Manual ] val encoder : dst -> q:queue -> encoder val encode : encoder -> [ `Block of block | `Flush | `Await ] -> [ `Ok | `Partial | `Block ] val dst : encoder -> bigstring -> off:int -> len:int -> unit
As expected, we take the shared queue to make a new encoder. Then, we let the
user to specify which kind of block they want to encode by the
Block
operation.
The
Flush operation tries to encode all elements present inside the shared
queue according to the current block and feed the outputs buffer. From it, the
encoder can returns some values:
Okand the encoder encoded all opcode from the shared queue
Partial, the outputs buffer is not enough to encode all opcode, the user should flush it and give to us a new empty buffer with
dst. Then, they must continue with the
Awaitoperation.
Block, the encoder reachs an opcode which can not be encoded with the current block (the current dictionary). Then, the user must continue with a new
Blockoperation.
The hard part is about the ping-pong game between the user and the encoder
where a
Block expects a
Block response from the user and a
Partial expects
an
Await response. But this design reveals something higher about zlib
this time: the flush mode.
The flush mode
Firstly, we talk about mode because zlib does not allow the user to
decide what they want to do when we reach a
Block or a
Ok case. So, it
defines some under-specified _modes_ to apply a policy of what
to do in this case.
In
decompress, we followed the same design and see that it may be not a good
idea where the logic is not very clear and the user wants may be an another
behavior. It was like a black-box with a black-magic.
Because we decided to split encoder and compressor, the idea of the flush mode does not exists anymore where the user explicitly needs to give to the encoder what they want (make a new block? which block? keep frequencies?). So we broke the black-box. But, as we said, it was possible mostly because we can abstract safely the shared queue between the compressor and the encoder.
OCaml is an expressive language and we can really talk about a queue where, in
C, it will be just an other array. As we said, the deal is about performance,
but now, we allow the user the possibility to write their code in this corner-case
which is when they reachs
Block. Behaviors depends only on them.
APIs in general
The biggest challenge of building a library is defining the API - you must strike a compromise between allowing the user the flexibility to express their use-case and constraining the user to avoid API misuse. If at all possible, provide an intuitive API: force the user not to need to think about security issues, memory consumption or performance.
Avoid making your API so expressive that it becomes unusable, but beware that
this sets hard limits on your users: the current
decompress API can be used to
build
of_string /
to_string functions, but the opposite is not true - you
definitely cannot build a stream API from
of_string /
to_string.
The best advice when designing a library is to keep in mind what you really want and let the other details fall into place gradually. It is very important to work in an iterative loop of repeatedly trying to use your library; only this can highlight bad design, corner-cases and details.
Finally, use and re-use it on your tests (important!) and inside higher-level
projects to give you interesting questions about your design. The last version
of
decompress was not used in ocaml-git mostly because the flush
mode was unclear.
Derivations as computations (ICFP 2019 slides) — Andrej Bauer, Aug 21, 2019 e… entire derivation, but only its proof relevant part. This is not a problem, as long as the missing subderivations can be reconstructed algorithmically. For instance, an equation may be re-checked, as long as we work in a type theory with decidable equality checking.
But what happens when a type theory misbehaves? For instance, the extensional type theory elides arbitrarily complex term type theories.Hide
Deriving Slowly — Rudi Grinberg, Aug 20, 2019
There’s been some recent grumbling about the usability of ppx in OCaml, and
instead of just letting it slide again, I’ve decided to do something
constructive about this and write a little tutorial on how to write a
deriving plugin.
Using OCaml to drive a Raspberry Pi robot car — Jane Street, Aug 19, 2019
Back.
Do applied programming languages research at Jane Street! — Jane Street, Aug 16, 2019
As our Tools & Compilers team has grown, the kinds of projects we work on has become more ambitious. Here are some of the major things we’re currently working on:
X509 0.7 — Hannes Mehnert (hannes), Aug 15, 2019, …Read more..., and other information into it. X.509 is a standard to solve this encoding and embedding, and provides more functionality, such as establishing chains of trust and revocation of invalidated or compromised material. X.509 uses certificates, which contain the public key, and additional information (in a extensible key-value store), and are signed by an issuer, either the private key corresponding to the public key - a so-called self-signed certificate - or by a different private key, an authority one step up the chain. A rather long, but very good introduction to certificates by Mike Malone is available here.
OCaml ecosystem evolving
More than 5 years ago David Kaloper and I released the initial ocaml-x509 package as part of our TLS stack, which contained code for decoding and encoding certificates, and path validation of a certificate chain (as described in RFC 5280). The validation logic and the decoder/encoder, based on the ASN.1 grammar specified in the RFC, implemented using David's asn1-combinators library changed much over time.
The OCaml ecosystem evolved over the years, which lead to some changes:
- Camlp4 deprecation - we used camlp4 for stream parsers of PEM-encoded certificates, and sexplib.syntax to derive s-expression decoders and encoders;
- Avoiding brittle ppx converters - which we used for s-expression decoders and encoders of certificates after camlp4 was deprecated;
- Build and release system iterations - initially oasis and a packed library, then topkg and ocamlbuild, now dune;
- Introduction of the
resulttype in the standard library - we used to use
[ `Ok of certificate option | `Fail of failure ];
- No more leaking exceptions in the public API;
- Usage of pretty-printers, esp with the fmt library
val pp : Format.formatter -> 'a -> unit, instead of
val to_string : t -> stringfunctions;
- Release of ptime, a platform-independent POSIX time support;
- Release of rresult, which includes combinators for computation
results;
- Release of gmap, a
Mapwhose value types depend on the key, used for X.509 extensions, GeneralName, DistinguishedName, etc.;
- Release of domain-name, a library for domain name operations (as specified in RFC 1035) - used for name validation;
- Usage of the alcotest unit testing framework (instead of oUnit).
More use cases for X.509
Initially, we designed and used ocaml-x509 for providing TLS server endpoints and validation in TLS clients - mostly on the public web, where each operating system ships a set of ~100 trust anchors to validate any web server certificate against. But once you have a X.509 implementation, every authentication problem can be solved by applying it.
Authentication with path building
It turns out that the trust anchor sets are not equal across operating systems and versions, thus some web servers serve sets, instead of chains, of certificates - as described in RFC 4158, where the client implementation needs to build valid paths and accept a connection if any path can be validated. The path building was initially in 0.5.2 slightly wrong, but fixed quickly in 0.5.3.
Fingerprint authentication
The chain of trust validation is useful for the open web, where you as software developer don't know to which remote endpoint your software will ever connect to - as long as the remote has a certificate signed (via intermediates) by any of the trust anchors. In the early days, before let's encrypt was launched and embedded as trust anchors (or cross-signed by already deployed trust anchors), operators needed to pay for a certificate - a business model where some CAs did not bother to check the authenticity of a certificate signing request, and thus random people owning valid certificates for microsoft.com or google.com.
Instead of using the set of trust anchors, the fingerprint of the server certificate, or preferably the fingerprint of the public key of the certificate, can be used for authentication, as optionally done since some years in jackline, an XMPP client. Support for this certificate / public key pinning was added in x509 0.2.1 / 0.5.0.
Certificate signing requests
Until x509 0.4.0 there was no support for generating certificate signing requests (CSR), as defined in PKCS 10, which are self-signed blobs containing a public key, an identity, and possibly extensions. Such as CSR is sent to the certificate authority, and after validation of ownership of the identity and paying a fee, the certificate is issued. Let's encrypt specified the ACME protocol which automates the proof of ownership: they provide a HTTP API for requesting a challenge, providing the response (the proof of ownership) via HTTP or DNS, and then allow the submission of a CSR and downloading the signed certificate. The ocaml-x509 library provides operations for creating such a CSR, and also for signing a CSR to generate a certificate.
Mindy developed the command-line utility certify which uses these operations from the ocaml-x509 library and acts as a swiss-army knife purely in OCaml for these required operations.
Maker developed a let's encrypt library which implements the above mentioned ACME protocol for provisioning CSR to certificates, also using our ocaml-x509 library.
To complete the required certificate authority functionality, in x509 0.6.0 certificate revocation lists, both validation and signing, was implemented.
Deploying unikernels
As described in another post, I developed albatross, an orchestration system for MirageOS unikernels. This uses ASN.1 for internal socket communication and allows remote management via a TLS connection which is mutually authenticated with a X.509 client certificate. To encrypt the X.509 client certificate, first a TLS handshake where the server authenticates itself to the client is established, and over that connection another TLS handshake is established where the client certificate is requested. Note that this mechanism can be dropped with TLS 1.3, since there the certificates are transmitted over an already encrypted channel.
The client certificate already contains the command to execute remotely - as a custom extension, being it "show me the console output", or "destroy the unikernel with name = YYY", or "deploy the included unikernel image". The advantage is that the commands are already authenticated, and there is no need for developing an ad-hoc protocol on top of the TLS session. The resource limits, assigned by the authority, are also part of the certificate chain - i.e. the number of unikernels, access to network bridges, available accumulated memory, accumulated size for block devices, are constrained by the certificate chain presented to the server, and currently running unikernels. The names of the chain are used for access control - if Alice and Bob have intermediate certificates from the same CA, neither Alice may manage Bob's unikernels, nor Bob may manage Alice's unikernels. I'm using albatross since 2.5 years in production on two physical machines with ~20 unikernels total (multiple users, multiple administrative domains), and it works stable and is much nicer to deal with than
scp and custom hacked shell scripts.
Why 0.7?
There are still some missing pieces in our ocaml-x509 implementation, namely modern ECC certificates (depending on elliptic curve primitives not yet available in OCaml), RSA-PSS signing (should be straightforward), PKCS 12 (there is a pull request, but this should wait until asn1-combinators supports the
ANY defined BY construct to cleanup the code), ...
Once these features are supported, the library should likely be named PKCS since it supports more than X.509, and released as 1.0.
The 0.7 release series moved a lot of modules and function names around, thus it is a major breaking release. By using a map instead of lists for extensions, GeneralName, ..., the API was further revised - invariants that each extension key (an ASN.1 object identifier) may occur at most once are now enforced. By not leaking exceptions through the public interface, the API is easier to use safely - see let's encrypt, openvpn, certify, tls, capnp, albatross.
I intended in 0.7.0 to have much more precise types, esp. for the SubjectAlternativeName (SAN) extension that uses a GeneralName, but it turns out the GeneralName is as well used for NameConstraints (NC) in a different way -- IP in SAN is an IPv4 or IPv6 address, in CN it is the IP/netmask; DNS is a domain name in SAN, in CN it is a name starting with a leading dot (i.e. ".example.com"), which is not a valid domain name. In 0.7.1, based on a bug report, I had to revert these variants and use less precise types.
Conclusion
The work on X.509 was sponsored by OCaml Labs. You can support our work at robur by a donation, which we will use to work on our OCaml and MirageOS projects. You can also reach out to us to realize commercial products.
I'm interested in feedback, either via
BAP Knowledge Representation - Part 1 — The BAP Blog, Aug 15, 2019 stor…Read more... stored in the knowledge base, which is roughly a global storage of information which could be used by different components for information exchange. It is like a set of global variables but without common problems associated with the global mutable state since the knowledge system will prevent data anomalies by ensuring that all updates are consistent and firing up a fixed point computation in case of mutual dependencies between different variables.
This knowledge base is essentially a set of objects. Objects belong to classes. Classes denote what properties objects have. Classes are further subdivided into sorts, which we will discuss in a separate blog post.
Object properties could be read or written. It is also possible to associate triggers with a property. Triggers are called promises in our parlance. A promise is a function that will be called when a property of an object is accessed. The promises are stored procedures in our knowledge base and they act like the injection points for different plugins, e.g., a lifter is just a promise to provide the semantics property of an object of class
core-theory:program. The promise itself can access any other properties of any other objects (which it can reach, of course), even including the property that it is providing (recursive case). Moreover, with each property, we can associate several promises (triggers). For example, we can have several lifters working at the same time. The knowledge system will take care of running and scheduling different promises and will compute the fixed point solution in linear time using stochastic fixed-point computation, and yadda, yadda. The point is that it will make it automatically and transparent to the user, and will guarantee the consistency of the result (e.g., that it doesn’t depend on the order of evaluation of promises). It is also important to understand, that once a triggered property is computed it will be stored and never recomputed again1.
Now let’s look underneath the hood of the knowledge base to see what objects and classes do we have right now. If you will run
bap ./exe -dknowledge you will find out that most of the objects that are currently stored in the base belong to the
core-theory:program class. Later, we will add more classes, but to implement the
Bap.Std interface this one was enough. So let’s take a particular object as an example. The knowledge base is printed in the following format:
(<object> (<properties>)). If an object has a symbolic identifier associated with it, then it will be printed, otherwise, a numeric identifier (basically a pointer) will be printed. The object class is not printed, but all objects are grouped by their class, with each new class opened with the
(in-class <class-name>) statement. Also, note that all symbolic identifiers are properly namespaced, using the package system which is the same as in Common Lisp. All identifiers which do not belong to the current package, denoted with the
(in-package <pkg>) statement, are printed as
<package>:<name>).
Now, we are ready to read the output of
-dknowledge. In the following output, we have an object, that belongs to the
core-theory:program class, which has a printed representation
core-theory:0x402fd0. The printed representation looks very much like a number, and you may notice that it is indeed equal to the address of an instruction which this object denotes.
(in-class core-theory:program) <snip> (core-theory:0x402fd0 ((core-theory:label-addr (0x402fd0)) (bap.std:arch (x86_64)) (bap.std:insn ((MOV32rr EAX ESI))) (bap.std:mem ((402fd0 2 LittleEndian))) (core-theory:semantics ((bap.std:ir-graph ("00004b45: 00004b46: RAX := pad:64[low:32[RSI]]")) (bap.std:insn-dests ((77054))) (bap.std:insn-ops ((EAX ESI))) (bap.std:insn-asm "movl %esi, %eax") (bap.std:insn-properties ((:invalid false) (:jump false) (:cond false) (:indirect false) (:call false) (:return false) (:barrier false) (:affect-control-flow false) (:load false) (:store false))) (bap.std:bil "{RAX := pad:64[low:32[RSI]]}") (bap.std:insn-opcode MOV32rr)))))
We can see, that the object is having the following properties:
core-theory:semantics- the semantics of this instruction
core-theory:label-addr- the address
bap.std:insn– the disassembled instruction
bap.std:mem- the region of memory which this instruction occupies
bap.std:arch- and the architecture
We can immediately infer a novel feature of bap 2.0, is that architecture is now a property of a particular instruction object (basically of an address), not of the whole project. Which enables multi-architectural analysis, where in the same base we have programs from different architectures, calling each other (ARM/Thumb is a good example).
The
label-addr,
insn, and
mem properties are pretty self-explanatory, so let’s jump to the most interesting property called
semantics. The
semantics itself is also a set of properties, which is called a value. Later, we will discover that essentially objects are pointers to values. A value, like an object, also belongs to some class and has some properties. The
core-theory:semantics property belongs to the
core-theory:effect class. This class denotes general effects that are produced when an instruction is executed. In other words, the semantics of an instruction. The semantics may have many different denotations, i.e., we can use different mathematical objects and structures to represent the semantics, which we will discuss in details the later blog posts. But for now let’s briefly look into different denotations of semantics (which all belong to the
bap.std package, so we will omit the package name for brevity):
bil- good old BAP 1.x BIL
ir-graph- the semigraphical BIR representation
insn-dests- the set of destinations
insn-opcode- the opcode
insn-ops- an array of operands
insn-asm- the assembly string
insn-properties- semantic properties provided by the decoder
As we may see, most of those properties are good old properties of the
Bap.Std.Insn data type in BAP 1.x, and indeed in BAP 2.x
Bap.Std.Insn.t is represented as a
Knowledge.value instance. The only new field is the set of destinations, which denote a set of program objects that are reachable from the given address. Which lets us explore the whole graph.
This brings us to the end of the first blog post about BAP 2.0 and the new knowledge system. We will discuss the knowledge system, along with an actual program interface in the upcoming blog posts. To make those posts productive I encourage everyone to join the discussion of BAP 2.0 in our gitter channel. Please, feel free to provide feedback, ask questions and drive the future posts.
1) All this magic with the consistent state, fixed-point solutions, etc is possible due to one trick - a data type of any property in our knowledge base must form a domain. A domain is a set equipped with a partial order and a special element called the bottom, so a domain is a generalization of a lattice (all lattices are domains, but not all domains are lattices). The partial order associated with the data type orders elements of this type by the amount of information. The knowledge system guarantees that all updates to object values preserve knowledge, i.e., the value of a property can never become less (wrt to the associated partial order), than it was before. Going deeper into details, every time a property is updated the existing value is joined with the new value,
x = join old new, where the
join operation is either induced by the domain order associated with the data type, or provided by a user (which basically allows users to register their lattices). To handle cases where
join doesn’t exist (and it may not exist, since we’re not requiring lattices), we extend the user datum with the
top value which denotes conflicting information (therefore named
conflict), thus turning each domain into dcpo (directed complete partial order - the structure that we actually need, to ensure all those magical properties, dcpo is very close to a lattice, but still a little bit more general).
Down — Daniel Bünzli, Jul 23, 2019
View older blog posts.
Syndications
- Ahrefs
- Amir Chaudhry
- Andrej Bauer
- Andy Ray
- Anil Madhavapeddy
- Ashish Agarwal
- CUFP
- Cameleon news
- Caml INRIA
- Caml Spotting
-abriel Radanne
- Gaius Hammond
- Gemma Gordon (OCaml Labs)
- Gerd Stolpmann
- GitHub Jobs
- Grant Rettke
- Hannes Mehnert
- Hong bo Zhang
- Jake Donham
- Jane Street
- KC Sivaramakrishnan
- Leo White
-
- Psellos
- Richard Jones
- Rudenoise
- Rudi Grinberg
- Sebastien Mondet
- Shayne Fletcher
- Stefano Zacchiroli
- Sylvain Le Gall
- Tarides
- The BAP Blog
- Thomas Leonard
- Till Varoquaux
- Xinuo Chen
- Yan Shvartzshnaider | https://ocaml.org/community/planet/ | CC-MAIN-2019-47 | refinedweb | 16,981 | 61.46 |
This section "what is thread in java?" will describe you about threading in Java.
AdsTutorials
In this section we will read about thread in Java. Here you will see the definition of thread, a very simple example of thread execution and the description of the example.
Before, defining a Thread in Java we will first focus on some points which are required to know in advance before knowing about Thread. So, lets first discuss about what is program?, what is process ?
What Is Program?
Program is a set of instructions that are executed sequentially.
What Is Process?
A process is a program that specifies how a specific task should be done. Basically, it follows a sequence for executing. It is a collection of instructions that are executed at the same time at run time . That's why more than one processes can be associated with the same program.
Thread
Definition : Thread is a process which does the special task after executing. This is a lightweight process that resides inside the program. Like, a Process more than one thread can also be associated with a single process. So, a process with single thread called single threaded process whereas, process with multiple thread is called Multi-threaded process.
Thread In Java
Thread in Java has implemented with the same meaning that actually, it is defined. Every Java program is run as a thread, thread is a sequential path of code execution within a program. Thread in Java follows a life cycle from its creation to dead. Threads can define their own variables, they have the program counter that specifies the execution of threads.
Example
Here I am giving a simple example which will demonstrate you about how to write thread in Java. Here we are going to give Java single thread example where you will see how a single thread is processed. In Java Thread can be used by two ways either by extending a Thread class or by implementing a Runnable interface. Here we will give the two examples, one will explain you that how to create a thread by extending and the another will explain you how to create thread by implementing the interface.
Thread Example using extending Thread class
MyThread.java
class MyThread extends Thread{ String s=null; MyThread(String s1){ s=s1; start(); } public void run(){ System.out.println(s); } }
RunThread.java
public class RunThread{ public static void main(String args[]){ MyThread m1=new MyThread("Thread Example Using Extending Thread Class"); } }
Thread Example using implementing Runnable interface
RunnableThread.java
class RunnableThread implements Runnable{ Thread t; String s=null; RunnableThread(String s1){ s=s1; t=new Thread(this); t.start(); } public void run(){ System.out.println(s); } }
RunnableThreadExample.java
public class RunnableThreadExample{ public static void main(String args[]){ RunnableThread m1=new RunnableThread("Thread started...."); } }
Output :
When you will execute both, RunThread.java and RunnableThreadExample.java one by one you will get the same output.
Posted on: June 25, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles
Advertisements
Ads
Ads
Discuss: What Is Thread In Java?
Post your Comment | http://roseindia.net/java/thread/what-is-thread-in-java.shtml | CC-MAIN-2018-13 | refinedweb | 519 | 66.84 |
You want a function to return more than one array or hash, but the return list flattens into just one long list of scalars.
Return references to the hashes or arrays:
($array_ref, $hash_ref) = somefunc( ); sub somefunc { my @array; my %hash; # ... return ( \@array, \%hash ); }
Just as all arguments collapse into one flat list of scalars, return values do, too. Functions that want to return multiple, distinct arrays or hashes need to return those by reference, and the caller must be prepared to receive references. If a function wants to return three separate hashes, for example, it should use one of the following:
sub fn { ..... return (\%a, \%b, \%c); # or return \(%a, %b, %c); # same thing }
The caller must expect a list of hash references returned by the function. It cannot just assign to three hashes.
(%h0, %h1, %h2) = fn( ); # WRONG! @array_of_hashes = fn( ); # eg: $array_of_hashes[2]{"keystring"} ($r0, $r1, $r2) = fn( ); # eg: $r2->{"keystring"}
The general discussions on references in Chapter 11, and in Chapter 8 of Programming Perl; Recipe 10.5 | http://etutorials.org/Programming/Perl+tutorial/Chapter+10.+Subroutines/Recipe+10.9+Returning+More+Than+One+Array+or+Hash/ | CC-MAIN-2019-18 | refinedweb | 170 | 69.72 |
Contributing to Numba¶
We welcome people who want to make contributions to Numba, big or small! Even simple documentation improvements are encouraged. If you have questions, don’t hesitate to ask them (see below).
Communication¶
Real-time Chat¶
Numba uses Gitter for public real-time chat. To help improve the signal-to-noise ratio, we have two channels:
- numba/numba: General Numba discussion, questions, and debugging help.
- numba/numba-dev: Discussion of PRs, planning, release coordination, etc.
Both channels are public, but we may ask that discussions on numba-dev move to the numba channel. This is simply to ensure that numba-dev is easy for core developers to keep up with.
Note that the Github issue tracker is the best place to report bugs. Bug reports in chat are difficult to track and likely to be lost.
Forum¶
Numba uses Discourse as a forum for longer running threads such as design discussions and roadmap planning. There are various categories available and it can be reached at: numba.discourse.group.
Mailing-list¶
We have a public mailing-list that you can e-mail at numba-users@anaconda.com. You can subscribe and read the archives on Google Groups.
Weekly Meetings¶
The core Numba developers have a weekly video conference to discuss roadmap, feature planning, and outstanding issues. These meetings are invite only, but minutes will be taken and will be posted to the Numba wiki.
platform. In this case, please prepend
[WIP] to your pull request’s title. Anaconda Cloud
numba channel so as to get development builds
of the llvmlite library:
$ conda config --add channels numba
Then create an environment with the right dependencies:
$ conda create -n numbaenv python=3.6 llvmlite numpy scipy jinja2 cffi
Note
This installs an environment based on Python 3.6, but you can of course
choose another version supported by Numba. To test additional features,
you may also need to install
tbb and/or
llvm-openmp and
intel-openmp.
To activate the environment for the current shell session:
$ conda activate numbaenv
Note
These instructions are for a standard Linux shell. You may need to adapt them for other platforms.
Once the environment is activated, you have a dedicated Python with the required dependencies:
$ python Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 11:07:29) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import llvmlite >>> llvmlite.__version__ '0.24.0'
Building Numba¶
For a convenient development workflow, we recommend you build Numba inside its source checkout:
$ git clone git://github.com/numba/numba.git $ cd numba $ python setup.py build_ext --inplace
This assumes you have a working C compiler and runtime on your development system. You will have to run this command again whenever you modify C files inside the Numba source tree.
The
build_ext command in Numba’s setup also accepts the following
arguments:
--noopt: This disables optimization when compiling Numba’s CPython extensions, which makes debugging them much easier. Recommended in conjunction with the standard
build_extoption
--debug.
--werror: Compiles Numba’s CPython extensions with the
-Werrorflag.
--wall: Compiles Numba’s CPython extensions with the
-Wallflag.
Note that Numba’s CI and the conda recipe for Linux build with the
--werror
and
--wall flags, so any contributions that change the CPython extensions
should be tested with these flags too. numba.tests.test_usecases
to run all tests in parallel, using multiple sub-processes:
$ python -m numba.runtests -m
For a detailed list of all options:
$ python -m numba.runtests -h
The numba test suite can take a long time to complete. When you want to avoid the long wait, it is useful to focus on the failing tests first with the following test runner options:
The
--failed-firstoption is added to capture the list of failed tests and to re-execute them first:
$ python -m numba.runtests --failed-first -m -v -b
The
--last-failedoption is used with
--failed-firstto execute the previously failed tests only:
$ python -m numba.runtests --last-failed -m -v -b
When debugging, it is useful to turn on logging. Numba logs using the
standard
logging module. One can use the standard ways (i.e.
logging.basicConfig) to configure the logging behavior. To enable logging
in the test runner, there is a
--log flag for convenience:
$ python -m numba.runtests --log
Development rules¶).
Numba uses Flake8 to ensure a consistent
Python code format throughout the project.
flake8 can be installed
with
pip or
conda and then run from the root of the Numba repository:
flake8 numba
Optionally, you may wish to setup pre-commit hooks
to automatically run
flake8 when you make a git commit. This can be
done by installing
pre-commit:
pip install pre-commit
and then running:
pre-commit install
from the root of the Numba repository. Now
flake8 will be run each time
you commit changes. You can skip this check with
git commit --no-verify.
Numba has started the process of using type hints in its code base. This will be a gradual process of extending the number of files that use type hints, as well as going from voluntary to mandatory type hints for new features. Mypy is used for automated static checking.
At the moment, only certain files are checked by mypy. The list can be found in
mypy.ini. When making changes to
those files, it is necessary to add the required type hints such that mypy tests will pass. Only in exceptional
circumstances should
type: ignore comments be used.
If you are contributing a new feature, we encourage you to use type hints, even if the file is not currently in the
checklist. If you want to contribute type hints to enable a new file to be in the checklist, please add the file to the
files variable in
mypy.ini, and decide what level of compliance you are targetting. Level 3 is basic static
checks, while levels 2 and 1 represent stricter checking. The levels are described in details in
mypy.ini.
There is potential for confusion between the Numba module
typing and Python built-in module
typing used for type
hints, as well as between Numba types—such as
Dict or
Literal—and
typing types of the same name.
To mitigate the risk of confusion we use a naming convention by which objects of the built-in
typing module are
imported with an
pt prefix. For example,
typing.Dict is imported as
from typing import Dict as ptD.
Platform support¶
Every commit to the master branch is automatically tested on all of the platforms Numba supports. This includes ARMv7, ARMv8, POWER8, as well as both AMD and NVIDIA GPUs. The build system however is internal to Anaconda, so we also use Azure to provide public continuous integration information for as many combinations as can be supported by the service. Azure CI automatically tests all pull requests on Windows, OS X and Linux, as well as a sampling of different Python and NumPy versions. If you see problems on platforms you are unfamiliar with, feel free to ask for help in your pull request. The Numba core developers can help diagnose cross-platform compatibility issues. Also see the continuous integration section on how public CI is implemented.
Continuous integration testing¶
The Numba test suite causes CI systems a lot of grief:
- It’s huge, 9000+ tests.
- In part because of 1. and that compilers are pretty involved, the test suite takes a long time to run.
- There’s sections of the test suite that are deliberately designed to stress systems almost to the point of failure (tests which concurrently compile and execute with threads and fork processes etc).
- The combination of things that Numba has to test well exceeds the capacity of any public CI system, (Python versions x NumPy versions x Operating systems x Architectures x feature libraries (e.g. SVML) x threading backends (e.g. OpenMP, TBB)) and then there’s CUDA and ROCm too and all their version variants.
As a result of the above, public CI is implemented as follows:
- The combination of OS x Python x NumPy x Various Features in the testing matrix is designed to give a good indicative result for whether “this pull request is probably ok”.
- When public CI runs it:
- Looks for files that contain tests that have been altered by the proposed change and runs these on the whole testing matrix.
- Runs a subset of the test suite on each part of the testing matrix. i.e. slice the test suite up by the number of combinations in the testing matrix and each combination runs one chunk. This is done for speed, because public CI cannot cope with the load else.
If a pull request is changing CUDA or ROCm code (which cannot be tested on Public CI as there’s no hardware) or it is making changes to something that the core developers consider risky, then it will also be run on the Numba farm just to make sure. The Numba project’s private build and test farm will actually exercise all the applicable tests on all the combinations noted above on real hardware!
Things that help with pull requests¶
Even with the mitigating design above public CI can get overloaded which causes a backlog of builds. It’s therefore really helpful when opening pull requests if you can limit the frequency of pushing changes. Ideally, please squash commits to reduce the number of patches and/or push as infrequently as possible. Also, once a pull request review has started, please don’t rebase/force push/squash or do anything that rewrites history of the reviewed code as GitHub cannot track this and it makes it very hard for reviewers to see what has changed.
The core developers thank everyone for their cooperation with the above!
Documentation¶
The Numba documentation is split over two repositories:
- This documentation is in the
docsdirectory inside the Numba repository.
- The Numba homepage has its sources in a separate repository at
Main documentation¶
This documentation is under the
docs directory of the Numba repository.
It is built with Sphinx and
numpydoc, which are available using
conda or pip; i.e.
conda install sphinx numpydoc.
To build the documentation, you need the bootstrap theme:
$ pip install sphinx_bootstrap_theme. | https://numba.readthedocs.io/en/stable/developer/contributing.html | CC-MAIN-2021-10 | refinedweb | 1,721 | 63.59 |
<<
Miguel Gonzalez Rocha2,849 Points
Help with the challenge pls
public static String getTitleFromObject(Object obj)
i dont understand why it takes Object obj if it is no created yet, and as i understand i have to upcast the String but where?
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Hello,
We need to to add the final return ""; because the method requires that it returns a string. The compiler would state that it's possible that the code within the if and else block might not be reachable, the compiler assumes the possibility exists that both cases would be false, so it would skip over them, and java recognizes that this means that neither of those return values would be reached, so it still requires that we return a string value, which we have to with the return ""; line.
Basically, if we ever see our method returning a blank string we'd know that there was bug, as the item checked was neither a String or BlogPost type object, which we assumed that we were, but let's say that somehow we were checking an item that was an int. It would skip over both tests and instead return ""; which would let us know that we've reached a bug in our program.
To sum it up we return the final ""; string because our method that a string be returned to compile correctly, because the compiler recognizes that it's possible that the return statements never be reached if the conditions are not met, however since a return statement will break out out of any method, as soon as one of those conditions are met, we break out of the method before we return "";
Thanks. hope this helps.
Eric Chan4,254 Points
That's very clear explanations! Thanks Rob!
6 Answers
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Hey there Miguel,
This challenge is when we are first introducted to type casting in a context where we do it ourselves, instead of seeing it, great way to learn. If not frustrating, but it does work.
I broke this down in another question, but I'll try to do the same here.
In the TypeCastChecker.java we have the skeleton code for it.
public static String getTitleFromObject(Object obj) { return ""; }
So first things first, our directions want us to check if the object is an instance of a String and return it as a String if it is. We can do this by the first if statement of
if (obj istanceof String) { return (String) obj; }
Secondly it's wanting us to check to see if the object is an instance of a BlogPost, we just modify our code above and check, but we run into troubles, because it's not sure we're calling getTitle() on a BlogPost object, this is easily remedied by type casting the variable like in the second if statement.
else if (obj instanceof BlogPost) { BlogPost myBlogPost = (BlogPost) obj; return myBlogPost.getTitle(); }
After that, your code should look similar to
public static String getTitleFromObject(Object obj) { if (obj instanceof String) { return (String) obj; } else if (obj instanceof BlogPost) { BlogPost myBlogPost = (BlogPost) obj; return myBlogPost.getTitle(); } return ""; } }
Thanks, let me know if this clears things up or not.
Miguel Gonzalez Rocha2,849 Points
well you did gave me the answer but im still confused, im gonna keep watching the videos and if i dont understand with more examples im gonna ask again, thank you for the explanation.
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Sure Miguel, is there anything I can try to better explain?
Miguel Gonzalez Rocha2,849 Points
Can you give an example on how i might need to use it? i understand now what it does but i still cant understand where to use it and why Thanks for the help i really apreciate it :)
Amal Karim5,329 Points
I can't understand why we must test whether obj is a String or not. The title of the method is "getTitleFromObject". So if obj is really a String, then we will NOT return a title from obj, we just return that obj. We can erase the first "if", no?
Benjamin Gooch20,365 Points
I spend probably 30 minutes trying to figure out the second task. It took me a long time to realize you have to store the obj in a BlogPost variable. I kept trying to call the getTitle() method and it kept telling me it couldn't do it due to it being static.
Frustrating, but I finally got it.
Tim Strand22,458 Points
Why does adding the (BlogPost) obj; instead of just obj clear up the compiler error: Object cannot be converted to BlogPost? i dont understand tagging obj with BlogPost since its not coming out of the BlogPost file?
Jacob Martin4,182 Points
Thank you for clearing it up.
Nikita Voloboev4,816 Points
I am curious why do you need to convert obj to String with (String) as you have already check that it is of type String?
if (obj istanceof String) { return (String) obj; }
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Hey there Miguel, the main reason that this would be used would be if we had an arrayList that contained multiple objects like Craig showed in the video. Let's assume it had ints strings and floats. We could use a method like this to determine what the way object was and add it to a new array list that contained just that type. So if it was an int our if statement could create a new array list of just ints and pass that value in. Wed be able to categorize an unknown object array with a method similar to this.
Miguel Gonzalez Rocha2,849 Points
Thank you i just understood how to use them and why they are usefull with this and the Interfaces video where we use upcasting again. Thanks a lot Rob. Im loving more and more the teamtreehouse community.
A Agha3,301 Points
You're awesome Rob Bridges keep doing what you're doing :)
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Will do, thanks. :)
Ben Summers1,306 Points
Great - thanks Rob ... I get it now.
We have passed an Object into the method, which, because it is a superclass, could be any type of object.
So we have to tell the method this Object is a String object.
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Exactly,
The method is only seeing that it is an Object, it doesn't know it is a String, even if we check if it's an instance of one, we still need to nudge it in the right direction.
Good job!
Ben Summers1,306 Points
I'm still baffled, by both the 'if' tests:
If obj is a String, why do we have to type cast the return value to a (String)? Obj is a String, otherwise this code will not execute.
Similarly, why do we have to execute code that typecasts obj to a BlogPost if that code only executes if obj already is a BlogPost?
Thanks.
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Hey Ben,
The reason for that is because the method is expecting a string to be returned, and will throw an error otherwise. based on the assumptions that Craig allowed us we knew the object was either a String or a BlogPost object. Since the method required a return of a String, we'd first check to see what object was passed in, if it was a String object we type cast it to String and return it. Without typecasting the object it'd give an incompatible type error.
We had to typecast the object to a blogPost so that we could have a variable to call the getTitle() method on it, which was the method that returns a String on the object, as the method declares that it must be a String.
Let's say we also were told that the object we were checking might also be a int, so we'd have to add that code to our method.
if (obj instanceof int) { int myInt = (int) obj; return Integer.toString(myInt); }
Would have to be added in our code. Basically the whole point of the exercise was dropping us in an event where we were being given unknown objects, Craig simplified it, but wanted us to return type casts the objects to what they properly were, and return the value as a String, as that is what the method was declared to return.
Thanks.
Ben Summers1,306 Points
Hi Rob - thanks for the time you have taken but the circularity issue that confuses me is in you answer too:
"if it was a String object we type cast it to String and return it"
Why do we have to typecast an object to String when it already is a String? Why can't we just return the String, which is what the method requires. It appears like an unnecessary step to me.
I know I'm being slow, but I want to make sure I'm following what's going on here.
Thanks.
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Hey Ben,
I know it sounds like we're definitely spinning wheels on it. but unfortunately computers aren't smart enough to understand "obvious" yet, to us it's obvious that if the Method requires a string be returned, and we check to see if it is a string, than we should just be able to do it. That makes sense to us.
Unfortunately to a computer it does not, they have us aced on logic and math, but as far as practical sense, you have to baby them along.
To a computer here's what it see's, imagine the disagreement below between you and the computer.
I'm passing you a variable.
Check and see if it's an instance of a String.
Okay, great it is.
Return it.
"Wait, we're only supposed to return strings"
I know we just checked, it's a string
"No this is generic Object that is an instance of a String, it's not a String, just a generic object."
This is where it would throw the uncompatiable types error to us.
We have to tell it to turn the generic object that we know is a String into a String to make it happy.
To put it simply, we have to do it so that Java knows completely what we're doing, even if a generic object like the one passed in is an instance of a String, Java will stubbornly stick by the fact that it's just a Generic object until we type cast it.
Only then would Java understand what we're trying to do, and not toss an error.
Hope this helps.
Glen Hayes5,798 Points
Could someone please help me?
I am getting a missing return statement error, line 27 with the following code for the first part of the instanceof challenge.
Does an if statement require as else statement?
thanksTitleFromObject(Object obj) { if (obj instanceof String) { return (String) obj; }
}
public String getAuthor() { return mAuthor; } public String getTitle() { return mTitle; } public String getBody() { return mBody; } public String getCategory() { return mCategory; } public Date getCreationDate() { return mCreationDate; }
}
Tim Strand22,458 Points
i believe you have to have a return outside your {} basically right now you are telling it if (true/false) {true do this} "false do this" but you are missing the false return value. which in this case would be return "" or something since if its false you dont want to display anything
aneaswileyCourses Plus Student 1,612 Points
So Just trying to make sure that I have this down I'm a Visual Person so hopefully this makes sense. Please let me know anyone if I am misdirected on any of this. TypeCasting with Objects from one class to another is something similar to the way Mail works. In its original form we would usually we would write a letter to a friend but we need to have this letter in an envelope. So we write the specific letter according to the letter classification "LETTER" and then mail it off according to the OBJECT classification of which can contain a letter Every body gets mail and knows what an envelope is. Create an "envelope variable and send the letter according to the ENVELOPE classification. The letter holds specific information that we will send to a friend in another CLASS a different part of the world. We then would tell Java - HEY I want to send this letter in the form of a bigger more obscured form OBJECT-->(in the form of an ENVELOPE hence we create an ENVELOPE object "envelope"). When our friend in a different CLASS gets our letter it is still in the (OBJECT)<-- ENVELOPE envelope form.
At that point your friend in the other Class or other end doesn't know that he will be getting a letter from you but he sorts all inbound mail that comes in because he has a mailbox to receive objects. Therefore he should check all mail with instanceof sort statements to see what TYPE of mail he is getting. Because he could be getting different object types that are still considered an object
Then he sees that this is your "letter" TYPE of "envelop" that you sent (or boolean response from the instanceof return).
He (Your Friend in a different class) immediately creates a place to store the letter so that he could read it as it should be in a letter variable from the LETTER class.
Letter letter;
Then he Casts the Envelope TYPE<-- OBJECT into that letter Variable through the letter class. it goes something like: Letter letter; <-- I have a space to store the object that matches the letter type of object that I received letter = (Convert into THE LETTER CLASS) envelope;<--- the actual object that was created when you put the letter inside.
Rob BridgesFull Stack JavaScript Techdegree Graduate 35,459 Points
Hey there, sounds like you mostly got it I read through what you said and that looked correct.
To use your example, we basically ship our friend multiple things in the mail, he knows that we shipped him something, but until he actually opens his mailbox and looks at each item, he doesn't know what it is until he reaches his hand in and checks (It is at this point that our program would type cast everything based on our code) .
So yes, it sounds like you understand the concept, well done!
Eric Chan4,254 Points
Eric Chan4,254 Points
I have read through all the comments but still confused why we have to put at the end of the code:
return "";
I thought the return statements in the if/else if clause already return the String. Why do we need the above code to end the method?
Thanks for your time~ | https://teamtreehouse.com/community/help-with-the-challenge-pls | CC-MAIN-2022-27 | refinedweb | 2,510 | 72.7 |
The aim of this project is to create an automatic night light IoT LED Strip using the Wia Platform and a Dot One. The Dot One retrieves sunrise and sunset information from your location from the cloud and activates the LED's between those two times at night.
List of items required to create this project:
- Wia Dot One (Buy Yours Here)
- Dot One TFT LCD Screen Module (Buy Yours Here)
- Micro USB Cable (Buy yours here)
- Phone
- Computer
- IRL2203N Mosfet
- 10k Ohm Resistor
- Jumper Wires
- Breadboard
- LED Strip
Step 1:
Create a Wia account with the Dot One connected. If you haven’t done so yet, you can follow this tutorial over here.
Step 2:
Go to this URL, and enter the location where the Sunset Light will be placed. Save the Longitude and Latitude information as we will be needing it later.
Step 3:
Open dashboard.wia.io and select your space. Click on the flows Icon. Create a new flow using the blue "Create a Flow" button. Give your flow a name and press the blue button "Create flow".
Step 4:
Drag the nodes from the left side of the screen so that they look like this. Link them together according to the image shown.
From the "Trigger" tab select the "Timer" Node.
From the "Service" tab select the "HTTP Service" Node
From the "Logic" tab select the "Run Function" Node
From the "Logic" tab select the "Update State" Node
Step 5:
In the Timer Node, select the tickbox beside "Every X Minutes" and from the drop down menu select "Every 15 Minutes".
Step 6:
In the "HTTP" Service Node Select "Method" as "GET" and in the URL Paste this URL.
Replace the "XXXXXXXXXX" with your latitude coordinates from Step 2 and the "YYYYYYYYYY" with the Longitude Coordinates. Update the node using the blue boxx.
Step 7:
In the "Run Function" Node paste this Code into the code editor:
var startTime_temp = JSON.parse(input.body).results.sunrise;
var endTime_temp = JSON.parse(input.body).results.sunset;
var startTime = startTime_temp.substring(11,19);
var endTime = endTime_temp.substring(11,19);
var currentDate = new Date();
var startDate = new Date(currentDate.getTime());
startDate.setHours(startTime.split(":")[0]);
startDate.setMinutes(startTime.split(":")[1]);
startDate.setSeconds(startTime.split(":")[2]);
var endDate = new Date(currentDate.getTime());
endDate.setHours(endTime.split(":")[0]);
endDate.setMinutes(endTime.split(":")[1]);
endDate.setSeconds(endTime.split(":")[2]);
if (startDate < currentDate && endDate > currentDate){
output.body = "Off";
}
else {
output.body = "On";
}
Step 8:
In the "Update State" Node click on the "Update devices from list" and select your device from the list that pops down. In the "Key", type in "LED_Light" and in the value type in "${input.body}". Update the Node by pressing the blue Button.
Step 9:
Click on the Code Icon on the left side of the Wia dashboard and Create a Blocks project. Give your project a name and click on "Blocks Project". Copy the blocks so that the code looks like this:
Alternative Method: Click on the Code Icon on the left side of the Wia dashboard and Create a Code project. Give your project a name and click on "Code Project". Copy the code from underneath
#include <WiFi.h>
#include <Wia.h>
Wia wiaClient = Wia();
void setup() {
WiFi.begin();
delay(2500);
pinMode(15, OUTPUT);
}
void loop() {
if ((wiaClient.getDeviceState("LED_Light")) == "On") {
digitalWrite(15, HIGH);
}
if ((wiaClient.getDeviceState("LED_Light")) == "Off") {
digitalWrite(15, LOW);
}
delay(2500);
}
Step 10:
Click on the rocket icon on the top right side of the screen and select your device from the list below. Click on the blue "Deploy" Button. Upload the code by pressing the left button whilst it is turned on to download new code onto it.
Step 11:
Connect the Dot One to the LED Strip, Mosfet and resistor as shown
Step 12:
Congratuilations!, If wired correctly, you should have a working IoT Enabled Sunset/Sunrise Light
Here's other fun projects you can try out - | https://community.wia.io/d/101-dot-one-controlled-iot-smart-night-lamp | CC-MAIN-2020-10 | refinedweb | 655 | 74.49 |
Things You'll Need:
- An Installation of Windows Standard Edition, or Enterprise edition. Web Edition will not work.
- Windows CD or i386 folder copied to local hard drive
- An Idea of the namespace to be used
- Step 1
Login to the box either locally via console, or through RDP
- Step 2
Go to Start -> Run and type in "dcpromo"
- Step 3
For most cases you will select "Domain Controller for a new domain"
- Step 4
For most cases you will select "Domain in a new forest"
- Step 5).
- Step 6
The next two screens will be where to place file repositories and service folders. You can accept the defaults.
- Step 7.
- Step 8
Select the permission type you would like. There are two options. If you will only be using Windows 2003 Server and Windows XP or newer, then select the Second option. otherwise, you would need to use the first option.
- Step 9
Pick a "Directory Services Restore" password. Hopefully you will never have to use this as its quite messy for the inexperienced. In either case, Remember this password.
- Step 10.
- Step 11
Active Directory will take a while, it could be a couple minutes, or as much as half an hour. Once it is done you will have to reboot.
Diablo2 said
on 6/3/2009 Excellent article. 5 stars!
ajayk said
on 4/4/2008 how to install ads
ajayk said
on 4/2/2008 how to install dhcp
ajayk said
on 4/2/2008 how install ads | http://www.ehow.com/how_2002004_install-active-directory.html | crawl-002 | refinedweb | 252 | 81.43 |
We will now start implementing the Spreadsheet widget, beginning with the header file:
#ifndef SPREADSHEET_H #define SPREADSHEET_H #include #include class Cell; class SpreadsheetCompare;
The header starts with forward declarations for the Cell and SpreadsheetCompare classes.
Figure 4.1. Inheritance tree for Spreadsheet and Cell
The attributes of a QTable cell, such as its text and its alignment, are stored in a QTableItem. Unlike QTable, QTableItem isn't a widget class; it is a pure data class. The Cell class is a QTableItem subclass. In addition to the standard QTableItem attributes, Cell stores a cell's formula.
We will explain the Cell class when we present its implementation in the last section of this chapter.
class Spreadsheet : public QTable { Q_OBJECT public: Spreadsheet(QWidget *parent = 0, const char *name = 0); void clear(); QString currentLocation() const; QString currentFormula() const; bool autoRecalculate() const { return autoRecalc; } bool readFile(const QString &fileName); bool writeFile(const QString &fileName); QTableSelection selection(); void sort(const SpreadsheetCompare &compare);
The Spreadsheet class inherits from QTable. Subclassing QTable is very similar to subclassing QDialog or QMainWindow.
In Chapter 3, we relied on many public functions in Spreadsheet when we implemented MainWindow. For example, we called clear() from MainWindow::newFile() to reset the spreadsheet. We also used some functions inherited from QTable, notably setCurrentCell() and setShowGrid().
public slots: void cut(); void copy(); void paste(); void del(); void selectRow(); void selectColumn(); void selectAll(); void recalculate(); void setAutoRecalculate(bool on); void findNext(const QString &str, bool caseSensitive); void findPrev(const QString &str, bool caseSensitive); signals: void modified();
Spreadsheet provides many slots that implement actions from the Edit, Tools, and Options menus.
protected: QWidget *createEditor(int row, int col, bool initFromCell) const; void endEdit(int row, int col, bool accepted, bool wasReplacing);
Spreadsheet reimplements two virtual functions from QTable. These functions are called by QTable itself when the user starts editing the value of a cell. We need to reimplement them to support spreadsheet formulas.
private: enum { MagicNumber = 0x7F51C882, NumRows = 999, NumCols = 26 }; Cell *cell(int row, int col) const; void setFormula(int row, int col, const QString &formula); QString formula(int row, int col) const; void somethingChanged(); bool autoRecalc; };
In the class's private section, we define three constants, four functions, and one variable.
class SpreadsheetCompare { public: bool operator()(const QStringList &row1, const QStringList &row2) const; enum { NumKeys = 3 }; int keys[NumKeys]; bool ascending[NumKeys]; }; #endif
The header file ends with the SpreadsheetCompare class declaration. We will explain this when we review Spreadsheet::sort().
We will now look at the implementation, explaining each function in turn:
#include #include #include #include #include #include #include #include #include #include using namespace std; #include "cell.h" #include "spreadsheet.h"
We include the header files for the Qt classes the application will use. We also include the standard C++ and header files. The using namespace directive imports all the symbols from the std namespace into the global namespace, allowing us to write stable_sort() and vector instead of std::stable_sort() and std::vector.
Spreadsheet::Spreadsheet(QWidget *parent, const char *name) : QTable(parent, name) { autoRecalc = true; setSelectionMode(Single); clear(); }
In the constructor, we set the QTable selection mode to Single. This ensures that only one rectangular area in the spreadsheet can be selected at a time.
void Spreadsheet::clear() { setNumRows(0); setNumCols(0); setNumRows(NumRows); setNumCols(NumCols); for (int i = 0; i < NumCols; i++) horizontalHeader()->setLabel(i, QChar('A' + i)); setCurrentCell(0, 0); }
The clear() function is called from the Spreadsheet constructor to initialize the spreadsheet. It is also called from MainWindow::newFile().
We resize the spreadsheet down to 0 x 0, effectively clearing the whole spreadsheet, and resize it again to NumCols x NumRows (26x999). We change the column labels to "A", "B", ..., "Z" (the default is "1", "2", ..., "26") and move the cell cursor to cell A1.
Figure 4.2. QTable's constituent widgets
A QTable is composed of many child widgets. It has a horizontal QHeader at the top, a vertical QHeader on the left, a QScrollBar on the right, and a QScrollBar at the bottom. The area in the middle is occupied by a special widget called the viewport, on which QTable draws the cells. The different child widgets are accessible through functions in QTable and its base class, QScrollView. For example, in clear(), we access the table's top QHeader through QTable:: horizontalHeader().
QScrollView is the natural base class for widgets that can present lots of data. It provides a scrollable viewport and two scroll bars, which can be turned on and off. It is covered in Chapter 6.
Cell *Spreadsheet::cell(int row, int col) const { return (Cell *)item(row, col); }
The cell() private function returns the Cell object for a given row and column. It is almost the same as QTable::item(), except that it returns a Cell pointer instead of a QTableItem pointer.
QString Spreadsheet::formula(int row, int col) const { Cell *c = cell(row, col); if (c) return c->formula(); else return ""; }
The formula() private function returns the formula for a given cell. If cell() returns a null pointer, the cell is empty, so we return an empty string.
void Spreadsheet::setFormula(int row, int col, const QString &formula) { Cell *c = cell(row, col); if (c) { c->setFormula(formula); updateCell(row, col); } else { setItem(row, col, new Cell (this, formula)); } }
The setFormula() private function sets the formula for a given cell. If the cell already has a Cell object, we reuse it and call updateCell() to tell QTable to repaint the cell if it's shown on screen. Otherwise, we create a new Cell object and call QTable::setItem() to insert it into the table and repaint the cell. We don't need to worry about deleting the Cell object later on; QTable takes ownership of the cell and will delete it automatically at the right time.
QString Spreadsheet::currentLocation() const { return QChar('A' + currentColumn()) + QString::number(currentRow() + 1); }
The currentLocation() function returns the current cell's location in the usual spreadsheet format of column letter followed by row number. MainWindow::updateCellIndicators() uses it to show the location in the status bar.
QString Spreadsheet::currentFormula() const { return formula(currentRow(), currentColumn()); }
The currentFormula() function returns the current cell's formula. It is called from MainWindow::updateCellIndicators().
QWidget *Spreadsheet::createEditor(int row, int col, bool initFromCell) const { QLineEdit *lineEdit = new QLineEdit(viewport()); lineEdit->setFrame(false); if (initFromCell) lineEdit->setText(formula(row, col)); return lineEdit; }
The createEditor() function is reimplemented from QTable. It is called when the user starts editing a celleither by clicking the cell, pressing F2, or simply starting to type. Its role is to create an editor widget to be shown on top of the cell. If the user clicked the cell or pressed F2 to edit the cell, initFromCell is true and the editor must start with the current cell's content. If the user simply started typing, the cell's previous content is ignored.
The default behavior of this function is to create a QLineEdit and initialize it with the cell's text if initFromCell is true. We reimplement the function to show the cell's formula instead of the cell's text.
We create the QLineEdit as a child of the QTable's viewport. QTable takes care of resizing the QLineEdit to match the cell's size and of positioning it over the cell that is to be edited. QTable also takes care of deleting the QLineEdit when it is no longer needed.
Figure 4.3. Editing a cell by superimposing a QLineEdit
In many cases, the formula and the text are the same; for example, the formula "Hello" evaluates to the string "Hello", so if the user types "Hello" into a cell and presses Enter, that cell will show the text "Hello". But there are some exceptions:
The task of converting a formula into a value is performed by the Cell class. For the moment, the important thing to bear in mind is that the text shown in the cell is the result of evaluating the formula, not the formula itself.
void Spreadsheet::endEdit(int row, int col, bool accepted, bool wasReplacing) { QLineEdit *lineEdit = (QLineEdit *)cellWidget(row, col); if (!lineEdit) return; QString oldFormula = formula(row, col); QString newFormula = lineEdit->text(); QTable::endEdit(row, col, false, wasReplacing); if (accepted && newFormula != oldFormula) { setFormula(row, col, newFormula); somethingChanged(); } }
The endEdit() function is reimplemented from QTable. It is called when the user has finished editing a cell, either by clicking elsewhere in the spreadsheet (which confirms the edit), by pressing Enter (which also confirms the edit), or by pressing Esc (which rejects the edit). The function's purpose is to transfer the editor's content back into the Cell object if the edit is confirmed.
The editor is available from QTable::cellWidget(). We can safely cast it to a QLineEdit since the widget we create in createEditor() is always a QLineEdit.
Figure 4.4. Returning a QLineEdit's content to a cell
In the middle of the function, we call QTable's implementation of endEdit(), because QTable needs to know when editing has finished. We pass false as third argument to endEdit() to prevent it from modifying the table item, since we want to create or modify it ourselves. If the new formula is different from the old one, we call setFormula() to modify the Cell object and call somethingChanged().
void Spreadsheet::somethingChanged() { if (autoRecalc) recalculate(); emit modified(); }
The somethingChanged() private function recalculates the whole spreadsheet if Auto-recalculate is enabled and emits the modified() signal. | https://flylib.com/books/en/2.18.1/subclassing_qtable.html | CC-MAIN-2020-24 | refinedweb | 1,573 | 51.58 |
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de-DE; rv:1.7.5) Gecko/20041108 Firefox/1.0 Build Identifier: Thunderbird 1.0 I would like to see an option to disable the new message tray icon. Reproducible: Always
I believe there is a bug for this filed against the suite, but I'm not having any luck finding it. Not that I'd dupe this to that one; notification issues appear to be product-specific. This applies to Mac as well as Windows, I guess, but *nix doesn't have a tray. If this tray icon is suppressed, do you still expect to be able to see the new message alert slider/popup?
I can disable the slider (gray box with green or blue border and number of messages) that shows up with user_pref("alerts.totalOpenTime", 0); but I cannot disable the icon in the systray (white envelope with green arrow). I would like to disable that one as well.
Attached is a screenshot of how this systray icon I want to disable looks like.
Created attachment 175438 [details] screenshot of how this systray icon I want to disable looks likeCreated attachment 175438 [details] screenshot of how this systray icon I want to disable looks like
Seamonkey bug 133917.
I tried user_pref("mail.server.default.notify.on",false); but it has NO effect in TB 310600 has been marked as a duplicate of this bug. ***
Bug 310600 isn't exactly a duplicate but I guess it can be fixed at the same time. I don't think an extra option should be included in the preferences but I'm of the opinion that the "Show an alert" option should prevent the systemtray icon and the popup from appearing. Both are alerts and by disabling the "Show an alert" option I expect both alerts to stay away. Some tweakers might prefer to have the option to show just one of both alerts but I think this won't be the case for the majority of the users. Because of this I think we shouldn't clutter the UI with yet another option. An extra option for the tweaker could always be provided in the the about:config way.
Bug 133917 has added the backend support necessary for this feature, on the trunk (targeted for TB 3.0). Setting this preference to False: mail.biff.show_tray_icon will suppress the icon. In TB, using a current 3a1 build, you can do this using: Options | Advanced | Config Editor. This bug is now about adding a checkbox in the Options dialog for the feature, altho that may be WontFix'd.
dup of bug 360030?
(In reply to comment #11) > dup of bug 360030? No, that didn't provide a checkbox to en/disable the tray icon.
Can the procedure be re-started for this request? I still don't like the icon! :)
(In reply to comment #13) > Can the procedure be re-started for this request? I still don't like > the icon! See comment 10. That feature was checked in to the trunk as well, so it's available in 2b1; you just have to set the pref via the Config Editor rather than having an explicit checkbox.
Are there plans to add that checkbox (in v2b1) to the actual UI or should I create a request for that?
This is actually a request. Further Thunderbird 2 is released and no new features will be implemented, especially none which result in l10 changes. If someone creates a patch it could come with Thunderbird 3.
Created attachment 694397 [details] Screenshot with the new checkbox added.Created attachment 694397 [details] Screenshot with the new checkbox added.
Created attachment 694400 [details] [diff] [review] patch Mainly I copied most of the code used in the suite edition of this bug. I just add a new checkbox to enable or disable the icon on the notification area only on Windows. Tested on Windows 7.
Comment on attachment 694400 [details] [diff] [review] patch >+++ b/mail/components/preferences/general.xul >@@ -63,16 +66,21 @@ >+#ifdef XP_WIN >+ <checkbox id="newMailNotificationTrayIcon" label="&showTrayIcon.label;" >++ >+#endif I think it would be better for addons to always have the checkbox there, but add hidden="true" if we're not on Windows… Other than that, it seems good to me, so r=me with that fixed. (And I'm going to go ahead and give it a ui-r=me, while I'm here. Normally I'm against adding checkboxes for stuff most people won't use, but for some reason I'm feeling generous today… ;) Thanks, and I apologize for the length of time it took me to get to this review! Later, Blake.
Sorry for the delay. I have been really busy on my everyday job. Today I am going to make needed change and re-attach it so someone could check-in on the tree. Thank you for your review, Blake :-)
Created attachment 728634 [details] [diff] [review] patch with correction will show a checkbox to disable the icon for new messages on the notification area on windows. The UI will be available on all OS but only visible on windows. Thanks for the patch. | https://bugzilla.mozilla.org/show_bug.cgi?id=283425 | CC-MAIN-2017-13 | refinedweb | 866 | 73.88 |
On Tue, 02 Sep 2008, Stephen Smalley wrote:> No, that idea seemingly died because both Al and Miklos thought it was> wrong to add new security hooks to the same code path (vs. moving the> existing ones to the callers),I do think that duplicating hooks is the wrong approach, but it doeshave the minimal impact of all the solutions, and the duplication canbe consolidated later. So in the end this might be the easiest wayforward.What Al is violently opposed to is removing the vfs_foo() API whichseparates the "VFS core", which doesn't know anything abount mounts,from the rest of the VFS.But as Jamie pointed out, we've already sneaked in vfsmounts via ther/o bind mounts patches. I don't see why we would need to strictlyseparate the mount namespace handling from the VFS core.Miklos | http://lkml.org/lkml/2008/9/2/128 | CC-MAIN-2014-15 | refinedweb | 140 | 57.81 |
Create Pages
In this section, we will learn about creating two types of pages in Docusaurus: a regular page and a documentation page.
Create a Regular PageCreate a Regular Page
- In the
website/pages/endirectory of your repository, save a text file called
hello-world.jswith the following contents:
const React = require('react'); const CompLibrary = require('../../core/CompLibrary.js'); const Container = CompLibrary.Container; const GridBlock = CompLibrary.GridBlock; function HelloWorld(props) { return ( <div className="docMainWrapper wrapper"> <Container className="mainContainer documentContainer postContainer"> <h1>Hello World!</h1> <p>This is my first page!</p> </Container> </div> ); } module.exports = HelloWorld;
Use any text editor to make the file, such as Microsoft Visual Studio Code or Komodo Edit.
- Go to and you should be able to see the new page.
- Change the text within the
<p>...</p>to "I can write JSX here!" and save the file again. The browser should refresh automatically to reflect the change.
- <p>This is my first page!</p> + <p>I can write JSX here!</p>
React is being used as a templating engine for rendering static markup. You can leverage on the expressibility of React to build rich web content. Learn more about creating pages here.
Create a Documentation PageCreate a Documentation Page
- Create a new file in the
docsfolder called
doc9.md. The
docsfolder is in the root of your Docusaurus project, one level above
website.
- Paste the following contents:
--- id: doc9 title: This is Doc 9 --- I can write content using [GitHub-flavored Markdown syntax](). ## Markdown Syntax **Bold** _italic_ `code` [Links](#url) > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse > id sem consectetuer libero luctus adipiscing. * Hey * Ho * Let's Go
- The
sidebars.jsonis where you specify the order of your documentation pages, so open
website/sidebars.jsonand add
"doc9"after
"doc1". This ID should be the same one as in the metadata for the Markdown file above, so if you gave a different ID in Step 2, just make sure to use the same ID in the sidebar file.
{ "docs": { "Docusaurus": [ "doc1", + "doc9" ], "First Category": ["doc2"], "Second Category": ["doc3"] }, "docs-other": { "First Category": ["doc4", "doc5"] } }
- A server restart is needed to pick up sidebar changes, so go to your terminal, kill your dev server (Cmd + C or Ctrl + C), and run
npm startor
yarn start.
- Navigate to to see the new documentation page.
You've created your first documentation page on Docusaurus!
Learn more about creating docs pages here. | https://docusaurus.io/docs/en/next/tutorial-create-pages | CC-MAIN-2019-47 | refinedweb | 406 | 60.01 |
Python Program That Analyzes Monthly Sales Figures For Each Division.
- 12th May, 2019
- 13:55 PM
Challenge - Python Program That Analyzes Monthly Sales Figures For Each Division.
Write a Python program that allows the user to enter a series of numbers and places the numbers (not string values) in a list. Each number entered by the user is the monthly sales amount for one division. Use a sentinel-controlled loop to get input from the user and place each value entered into the list as long as the value is not negative. As soon as any negative value is entered, stop the loop (without putting that illegal value into the list).
One objective of this assignment is to apply algorithms we have studied to solve problems. You will do this by writing a function definition to implement each algorithm. Every function must get information only from its parameters, not from "global" variables. Several of these tasks can also be accomplished with built-in functions. In those cases, your code should demonstrate both approaches and show that the results are the same.
Add code to your program to do the following:
- Write a function definition that uses a loop and a string accumulator to produce and return a string result that includes the user-entered sales figures formatted to look similar to this when it is printed:
{$12.95, $1,234.56, $100.00, $20.50}
Notice the dollar signs, commas, digits after the decimal point, and curly braces. Plan this one on paper before you start writing code. Add code that calls this function and prints the result.
- Show the highest number in the list -- the sales leader! Do this in two ways. First, use the built-in 'max' function. Then, write your own 'max2' function definition that accomplishes the same thing by using a loop to find the highest value.
- Show the lowest number in the list -- the sales loser. Do this in two ways. First, use the built-in 'min' function. Then, write your own 'min2' function definition that accomplishes the same thing by using a loop to find the lowest value.
- Show the total sales for the company for the month -- the sum of all the numbers in the list. Once again, write a function definition that uses a loop and an accumulator to compute this sum.
- Show the average of all the numbers in the list. (Be sure to carefully check the result!)
- Ask the user to enter a threshold (a number). Write a function that takes a list and the threshold as parameters, and returns a new list that contains all values in the original list that are greater than or equal to the threshold -- these divisions get awards for high sales! The new list may, of course, be empty.
Python Program -
def display(sales):
sales2=['']*len(sales)
for i in range(0,len(sales)):
sales2[i]='$' + '{:,.2f}'.format(sales[i])
return '{' + ', '.join(sales2) + '}'
def max2(sales):
if len(sales)==0:
return None
m = sales[0]
for sale in sales[1:]:
if sale > m:
m = sale
return m
def min2(sales):
if len(sales)==0:
return None
m = sales[0]
for sale in sales[1:]:
if sale < m:
m = sale
return m
def sum2(sales):
s = 0
for sale in sales:
s += sale
return s
def average(sales):
if len(sales)==0:
return None
s = sum2(sales)
return s / len(sales)
def thresh (sales, threshold):
return [sale for sale in sales if sale >= threshold]
def main():
sales = []
while True:
sale = float (input ('Please input the number to add and enter -1 to stop: '))
if sale == -1:
break
sales.append(sale)
print('')
print (display(sales))
print('')
print ("Max using max function :"+str(max(sales)))
print ("Max using max2 function :"+str(max2(sales)))
print ('')
print ("Min using min function :"+str(min(sales)))
print ("Min using min2 function :"+str(min2(sales)))
print ('')
print ("Sum using sum function :"+str(sum(sales)))
print ("Sum using sum2 function :"+str(sum2(sales)))
print ('')
print ("Average :"+str(average(sales)))
print ("")
threshold = float (input ('Please input a thereshold: '))
sales = thresh (sales, threshold)
print ("result: " + display(sales))
main() | https://www.theprogrammingassignmenthelp.com/blog-details/python-program-for-monthly-sales-figures | CC-MAIN-2019-51 | refinedweb | 683 | 69.11 |
Dialog not resizing back to original size [CLOSED]
On 06/01/2015 at 17:17, xxxxxxxx wrote:
Press the '?', it extends the dialog to the right with a second group. Press it again and that second group disappears. However, it doesn't shrink the dialog back to it's original size.
How would I go about fixing this?
Also, do I need to have c4d.StopAllThreads () in there?
import c4d, os from c4d import gui from os import path #Welcome to the world of Python class dlg ( gui.GeDialog ) : LabelID = 999 mainGroup = 1000 secondGroup = 1020 second = 10205 sText = 1021 buttonGrp = 1005 okBtn = 1006 cancelBtn = 1007 secondBtn = 1008 style = 2000 def CreateLayout ( self ) : self.SetTitle ( 'dlg test' ) self.GroupBegin ( self.mainGroup, c4d.BFH_FIT, 2, 0 ) self.GroupBegin (self.buttonGrp, 0, 3, 0, title = 'first group' ) self.GroupBorderSpace( 8, 8, 8, 8 ) self.AddButton ( self.okBtn, c4d.BFH_SCALEFIT, name = 'OK', initw = 250, inith = 18 ) self.AddButton ( self.cancelBtn, c4d.BFH_SCALEFIT, name = 'Cancel', initw = 250, inith = 18 ) self.AddButton ( self.secondBtn, c4d.BFH_SCALEFIT, name = '?', initw = 18, inith = 18 ) self.GroupEnd () self.GroupEnd () if self.style == 2001: self.GroupBegin ( self.second, c4d.BFH_SCALEFIT, 1, 0, title = 'second group' ) self.GroupBorder( c4d.BORDER_THIN_IN ) self.GroupBorderSpace( 8, 8, 8, 8 ) self.AddStaticText ( self.sText, c4d.BFH_LEFT, name = "after this is closed, resize dialog back to original." ) self.GroupEnd () self.GroupEnd () return True def InitValues( self ) : return True def CoreMessage ( self, id, msg ) : self.LayoutChanged ( c4d.EVMSG_CHANGEDSCRIPTMODE ) return True def Command ( self, id, msg ) : # 'Cancel' Button if id == self.cancelBtn: self.Close () # '?' Button if id == self.secondBtn: if self.style == 2001: self.style = 2000 else: self.style = 2001 self.LayoutFlushGroup ( self.mainGroup ) self.CreateLayout () self.InitValues () self.LayoutChanged ( self.mainGroup ) return True def main() : c4d.StopAllThreads () dialog = dlg () dialog.Open ( c4d.DLG_TYPE_MODAL ) if __name__=='__main__': main()
On 07/01/2015 at 06:49, xxxxxxxx wrote:
Herbie,
I'm afraid I have no good news. There's currently no way to achieve this. Sorry
On 07/01/2015 at 10:23, xxxxxxxx wrote:
Well then.. That's quite the bummer.
It was just a visual annoyance that I was trying to fix. I can get everything to work with the rest of the script.. it just won't look as pretty as I would like :( | https://plugincafe.maxon.net/topic/8411/10988_dialog-not-resizing-back-to-original-size-closed | CC-MAIN-2020-10 | refinedweb | 377 | 62.95 |
Details
- Type:
Sub-task
- Status: Resolved
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: None
- Fix Version/s: HA Branch (HDFS-1623)
-
- Labels:None
- Hadoop Flags:Reviewed
Description
ZKClient needs to support the following capabilities:
- Ability to create a znode for co-ordinating leader election.
- Ability to monitor and receive call backs when active znode status changes.
- Ability to get information about the active node.
Activity
Todd, the goal of this jira is to write a library that could be used by failover controller.
I found that ZK-1080 added support that I intended to add this. Will take a look at it as well.
Hey Suresh, you might also check out
ZOOKEEPER-1095, as ZK-1080 hasn't been committed yet.
Hi,
I have submitted a short design document for this library and a patch that implements the functionality. Both are up for review and comments.
Thanks
please ignore inconsistencies in comments while I fix them.
New patch with inconsistent names fixed across comments and code.
Some comments for the first version of the patch:
- General - How is multithreaded use for this library handled?
- ActiveStandbyElector
-.
- Constructor should check for null - at least for call back passed. Otherwise you will get null pointer exception.
- joinElection() you may want to copy the byte[] data passed or at least document that the data[] must not be changed by the caller.
- #getNewZooKeeper() seems unnecessary and can be removed. Creation of ZooKeeper() can be moved to createConnection() it self.
- Make member variable that are initialized only once in the constructor final.
- activeData could be better name for appData.
- Please check if all the params are documented in methods. For example constructor is missing one of the params in the doc. Same is true with exceptions thrown.
- quitElection() should not check zkClient non null, as terminateConnection already checks it.
- getActiveData() - how about not throwing KeeperException? Also ActiveNotFoundException should wrap the exception caught from ZK.
I have not complete the review. These are some prelimiary comments
>> General - How is multithreaded use for this library handled?
All public methods are synchronized
>.
Done in second patch
>>Constructor should check for null - at least for call back passed. Otherwise you will get null pointer exception.
Done
>>joinElection() you may want to copy the byte[] data passed or at least document that the data[] must not be changed by the caller.
Done
>>#getNewZooKeeper() seems unnecessary and can be removed. Creation of ZooKeeper() can be moved to createConnection() it self.
This is to pass in a mock zookeeper for testing
>>Make member variable that are initialized only once in the constructor final.
Done in second patch
>>activeData could be better name for appData.
All app's can pass in data (which may go into future per app nodes). Only active app's data makes it to the lock. So I think the name is good.
>>Please check if all the params are documented in methods. For example constructor is missing one of the params in the doc. Same is true with exceptions thrown.
Done in second patch
>>quitElection() should not check zkClient non null, as terminateConnection already checks it.
Yeah. I forgot to remove that check after I refactored stuff into the reset() method
>>getActiveData() - how about not throwing KeeperException? Also ActiveNotFoundException should wrap the exception caught from ZK.
Its hard to differentiate exceptions inside KeeperException. There is not much the elector can do about them. The only commonly expected exception would be getting leader data when no leader exists and that has been handled as part of the elector API via a new exception.
Patch that takes care of review comments.
new patch will all changes
- Can ActiveStandbyElector be made package-private? If not, it should get audience annotations (perhaps private, perhaps LimitedPrivate to HDFS? not sure)
- Same with the inner interface
+ * or loss of Zookeeper quorum. Thus enterSafeMode can be used to guard + * against split-brain issues. In such situations it might be prudent to + * call becomeStandby too. However, such state change operations might be + * expensive and enterSafeMode can help guard against doing that for + * transient issues. + */
- I think the above references to enterSafeMode are supposed to be enterNeutralMode, right?
- Also, it can't really guard against split brain, because there is no guarantee on the timeliness of delivery of these messages. That is to say, the other participants in the election might receive becomeActive before this participant receives enterNeutralMode. So, I'm not sold on the necessity of this callback.
+ void notifyFatalError();
Shouldn't this come with some kind of Exception argument or at least a String error message? Right now if we hit it, it won't be clear in the logs which of several cases caused it.
+ /** + * Name of the lock znode used by the library + */ + public static final String lockFileName = "ActiveStandbyElectorLock-21EC2020-3AEA-1069-A2DD-08002B30309D";
- why is this public?
- should also be ALL_CAPS.
- what's with the random UUID in there? Assumedly this library would be configured to be rooted inside some base directory in the tree which would include the namespaceID, etc.
+ * Setting a very short session timeout may result in frequent transitions + * between active and standby states during issues like network outages.
Also should mention GC pauses here – they're more frequent than network blips IME.
+ * @param zookeeperHostPort + * ZooKeeper hostPort for all ZooKeeper servers
Comma-separated? Perhaps better to name it zookeeperHostPorts since there is more than one server in the quorum.
- typo: "reference to callback inteface object"
+ appData = new byte[data.length]; + System.arraycopy(data, 0, appData, 0, data.length);
Could use Arrays.copyOf() here instead
- Rename operationSuccess etc to isSuccessCode – I think that's a clearer naming.
- Make ActiveStandbyElectorTester an inner class of TestActiveStandbyElector. We generally discourage having multiple "outer" classes per Java file. You can then avoid making two "mockZk" objects, and "count" wouldn't have to be static, either. The whole class could be done as an anonymous class, inline, probably.
- Echo what Suresh said about catching exceptions in tests - should let it fall through and fail the test - that'll also make sure the exception that was triggered makes it all the way up to the test runner and recorded properly (handy when debugging in Eclipse for example)
- In a couple places, you catch an expected exception and then verify, but you should also add an Assert.fail("Didn't throw exception") in the try clause to make sure the exception was actually thrown.
+ * active and the rest become standbys. </br> This election mechanism is + * efficient for small number of election candidates (order of 10's) because
Should say "only efficient" to be clear
+ * {@link ActiveStandbyElectorCallback} to interact with the elector + * + */
Extra blank lines inside javadoc comments should be removed
Some general notes/nits:
- Some of the INFO level logs are probably better off at DEBUG level. Or else, they should be expanded out to more operator-readable information (most ops will have no clue what "CreateNode result: 2 for path: /blah/blah" means.
- Some more DEBUG level logs could be added to the different cases, or even INFO level ones at the unexpected ones (like having to retry, or being Disconnected, etc). I don't think there's any harm in being fairly verbose about state change events that are expected to only happen during fail-overs, and in case it goes wrong we want to have all the details at hand. But, as above, they should be operator-understandable.
- Javadoc breaks should be <br/> rather than </br>.
- Constants should be ALL_CAPS – eg LOG rather than {{Log}
- Add a constant for NUM_RETRIES instead of hard-coded 3.
- Should never use e.printStackTrace – instead, use LOG.error or LOG.warn with the second argument as the exception. This will print the trace, but also makes sure it goes to the right log.
>>Can ActiveStandbyElector be made package-private?
Let me read up on all these package annotations and see what makes sense.
>>Also, it can't really guard against split brain
The guarantee is based on setting the correct timeouts. Another instance can only become active after the session timeout. The session timeout is recommended to be at least 3X the zookeeper disconnect timeout. enterNeutralMode is called when zookeeper client disconnects from zookeeper server or when zookeeper servers lose quorum. My understanding is that when there is a network disconnection then zookeeper client will disconnect from the server and post a disconnect event. So if your TCP disconnect timeouts are not set insanely high (> session timeout) then enterSafeMode will be called before session timeout expires and someone else becomes a master. Does this clarify?
>>should also be ALL_CAPS
It public because its a well defined property of the class.
Is the ALLCAPS on static strings a convention? You mean the member name should be all caps or the value? I added the random UID to prevent accidental operation on this file from some admin. It does not hurt and it safer than using just a nicely named file. Anyways, I changed it.
>>Could use Arrays.copyOf()
I first used .clone() and then was pointed to System.ArrayCopy() and now pointed to Array.copyOf(). Could you please point me to any place that lists the pros and cons of different array copying methods (of which there seem to be many)?
>>Rename operationSuccess etc to isSuccessCode
I think the current names read OK with the if() statements.
>>Make ActiveStandbyElectorTester an inner class of TestActiveStandbyElector.
I first wrote it that way. But there is a problem.
Tester_constructor()
>super_constructor()>Tester().getNewZookeeper()->returns mock.
So I need to have mock initialized before constructing the tester object. So I made mock a static member. But then java complained that inner classes cannot have static members.
>>Some of the INFO level logs are probably better off at DEBUG level.
Could you please point me to some place which explains what to log at different log levels?
So if your TCP disconnect timeouts are not set insanely high (> session timeout) then enterSafeMode will be called before session timeout expires and someone else becomes a master.
This still isn't "safe". For example, imagine the NN goes into a multi-minute GC pause just before writing an edit to its edit log. Since the GC pause is longer than the session timeout, some other NN will take over. Without active fencing, when the first NN wakes up, it will make that mutation to the edit log before it finds out about the ZK timeout.
It sounds contrived but we've had many instances of data loss bugs in HBase due to scenarios like this in the past. Multi-minute GC pauses are rare but do happen.
It public because its a well defined property of the class.
But it implies that external consumers of this class may want to directly manipulate the znode – which is exposing an implementation detail unnecessarily.
Is the ALLCAPS on static strings a convention? You mean the member name should be all caps or the value?
Yes, it's a convention that constants should have all-caps names. See the Sun java coding conventions, which we more-or-less follow:
So I need to have mock initialized before constructing the tester object. So I made mock a static member. But then java complained that inner classes cannot have static members.
I'm not quite following - you already initialize the non-static mockZk in TestActiveStandbyElector.init()?. Then if it's a non-static inner class, it can simply refer to the already-initialized member of its outer class.
Could you please point me to some place which explains what to log at different log levels?
I don't think we have any formal guidelines here.. the basic assumptions I make are:
- ERROR: unrecoverable errors (eg some block is apparently lost, or a failover failed, etc)
- WARN: recoverable errors (eg failures that will be retried, blocks that have become under-replicated but can be repaired, etc)
- INFO: normal operations proceeding as expected, but interesting enough that operators will want to see it.
- DEBUG: information that will be useful to developers debugging unit tests or running small test clusters (unit tests generally enable these, but users generally don't). Also handy when you have a reproducible bug on the client - you can ask the user to enable DEBUG and re-run, for example.
- TRACE: super-detailed trace information that will only be enabled in rare circumstances. We don't use this much.
About the GC pause scenario (and others like it). Lets not mix up election with operation safety. What this library provides is a signal about whether one is a leader or not. By itself, that does not solve the problems of whether that signal was properly processed or not. E.g. a potential solution to the GC pause (or any NN hung case) would be to not have the NN participate in leader election directly. A failover controller (whose design ensures 0 or cheap GC pauses) could handle the leader election and terminate hung NN's when its are no longer a master.
Let me address some of the comments in a subsequent patch. I need to learn a little more Java before I can do it to my liking.
Uploading new patch that address review comments.
Adding patch with audience.private and stability.evolving annotations for the elector class
granting the ASF license this time for the previous patch on class annotations.
Adding patch with functional test using real ZooKeeper server.
Sorry for the spam. There were some unsupported characters that somehow showed up only when building from the top level hadoop project. Fixing that and adding some more comments.
Uploading new patch with the following minor changes:
- Fixed build failure due to unsupported characters
- Fixed many lines longer than 80 columns. Other coding conventions fixed "{" to be on the same line after if and not new line.
- Added apache license banner to the new file TestActiveStandbyElectorRealZK.java
- Added javadoc to the the test classes to briefly describe what is being tested.
Bikas can you please address the following comments:
- TestActiveStandbyElectorRealZK.java
- ThreadRunner.zkClient hides the zkClient from the outside class.
- Please add javadoc to the classes
- Please add comments in the tests to describe the test that is being done.
Fixed review comments
+1 for the patch. Minor update. Changes the logger to commons.logging.
I committed the patch. Thank you Bikas.
Just wondering if Curator would've been a better choice here, instead of writing our own?
From previous discussions on HDFS-2185 it seemed that writing a simple library for our own needs was a choice no one disagreed on. It also makes sense because this library could be enhanced more painlessly for future needs.
From my reading of the curator code, it brings in a fair bit of complexity because it builds a general ZK framework on top on which recipes are implemented. Secondly, it seemed that the leader election recipe worked by electing a leader, that holds onto leadership via not returning from a blocking call. When that call returns then leadership is given up. I might be wrong but it was not obvious to me how this would handle environmental errors which cause the leadership to be lost because of external errors.
Integrated in Hadoop-Hdfs-HAbranch-build #59 (See)
HADOOP-7992. Add ZKClient library to facilitate leader election. Contributed by Bikas Saha.
suresh :
Files :
- /hadoop/common/branches/
HDFS-1623/hadoop-common-project/hadoop-common/CHANGES. HDFS-1623.txt
- /hadoop/common/branches/
HDFS-1623/hadoop-common-project/hadoop-common/pom.xml
- /hadoop/common/branches/
HDFS-1623/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/ActiveStandbyElector.java
- /hadoop/common/branches/
HDFS-1623/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestActiveStandbyElector.java
- /hadoop/common/branches/
HDFS-1623/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ha/TestActiveStandbyElectorRealZK.java
Hey Suresh. I've been thinking about the design for the ZK-based failover controller but have yet to post a design. Let me write something up and post it to
HDFS-2185today. It sounds like we should coordinate work. | https://issues.apache.org/jira/browse/HADOOP-7992?focusedCommentId=13179177&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2015-11 | refinedweb | 2,681 | 58.08 |
Details
- Type:
Sub-task
- Status:
Closed
- Priority:
Minor
- Resolution: Fixed
- Affects Version/s: 4.2.1
-
- Component/s: Documentation
- Labels:None
- Patch Submitted:Yes
- Number of attachments :
Description
The FAQ documents how to get console and debug output from an installer ( ). But it's not so easy to get console output from an uninstaller, at least under Windows.
When the uninstaller is called using
java -jar -DTRACE=TRUE uninstaller.jar
console output is not visible.
The uninstaller uses the SelfModifier class to start a new java VM and the console output of the second VM is not visible.
One possible solution is to write a class that starts the uninstaller code by bypassing SelfModifier:
import com.izforge.izpack.uninstaller.Uninstaller;
public class IzPackUninstallerStarter {
public static void main (String args[]){ Uninstaller.uninstall (args); }
}
Activity
Added a sample class that can be used to start an uninstaller so that console output is visible. (Console output is otherwise not visible on Windows). It bypasses the SelfModifier class.
When the class is included in the uninstaller JAR, the following command can be used:
java -cp uninstaller.jar IzPackUninstallerStarter
I have updated the FAQ with a link to this issue as it fits better here.
Added a patch to implement a "-d" (direct) option switch for Uninstaller.java.
This would make it easier to get console output from the uninstaller.
With this patch, the uninstaller can be called as:
java -jar uninstaller.jar -d
Marked as iixed as Christian has updated the issue.
Would you have a piece of documentation for this? | http://jira.codehaus.org/browse/IZPACK-331 | CC-MAIN-2014-42 | refinedweb | 257 | 57.98 |
in future posts is not just to show how to solve them. Anyone with access to google can search for one of the 100 already implemented solutions. The idea here is two show some key concepts that you can apply to any dynamic problem.
So lets start with the well known Edit distance problem. Basically, given two strings A and B, the edit distance measures the minimum number of operations required to transform one string into the other. In the most common version of this problem we can apply 3 different operations:
- Insert a new character into one of the strings
- Delete an existing character
- Replace one character by another
For example, given the strings A = “cat” and B = “cars”, editDistance(A,B) = 2 because the minimum number of transformations that we need to make is replace the “t” in A by “r” and then remove the “s” from B. After that, both strings are equal to “car”. Notice that in this case another possibility would have been to replace the “t” by an “r” but then insert an “s” into A, making both strings equal to “cars”. Similarly we could change both into “cat” or “cats” and the edit distance is still 2.
So how would we go about solving this problem? Lets try to solve a much smaller and simpler problem. Imagine we have the two previous strings again, this time represented as an array of chars in the general form:
A = [A0, A1, A2,…, An]
B = [B0, B1, B2,…, Bm]
Notice that the lengths of A and B (n and m respectively) might be different.
We know that in the end, both strings will need to have the same length and match their characters on each position. So, if we take just the first character of A and B, what choices do we have? We have 3 different transformations that we can apply so we have 3 choices as well:
- We can replace the first character of A by the first character of B. The cost of doing this replacement will be 1 if the characters are different and 0 if they are equal (because in that case we don’t need to do anything). At this point we know that both strings start with the same character so we can compute the edit distance of A[1..n] = [A1,…, An] and B[1..m] = [B1,…, Bm]. The final result will be the cost of transforming A[0] into B[0] plus the edit distance of the remaining substrings.
- The second choice we have is inserting a character into A to match the character in B[0], which has a cost of 1. After we have done this, we still need to consider the original A string because we have added a new character to it but we haven’t process any of its original characters. However, we don’t need to consider B[0] anymore because we know that it matches A[0] at this point. Therefore, the only thing we need to do now is to compute the edit distance of the original A and B[1..m] = [B1,…, Bm]. The final result will be this value plus 1 (the cost of inserting the character into A).
- The last case is symmetrical to the previous one. The third transformation we can apply is simply to delete A[0]. This operation has a cost of 1 as well. After doing this, we have consumed one character of A but we still have all the original characters of B to process. So we simply need to compute the edit distance of A[1..n] = [A1,…, An] and B. Again, the final value of the edit distance will be this value plus 1 (the cost of deleting A[0].
So which of the three choices should we pick initially? Well, we don’t really know which one will be better in the end so we have to try them all. The answer to our original problem will be the minimum value of those three alternatives.
The previous description is the key to solving this problem so read it again if it is not clear. Notice that, the last step on each of the three alternatives involves computing the edit distance of 2 substrings of A and B. This is exactly the same problem as the original one we are trying to solve, i.e., solving the edit distance for 2 strings. The difference is that after each decision we take, the problem becomes smaller because one or both input strings become smaller. We are solving the original problem by solving smaller sub-problems of exactly the same type. The fact that the sub-problems become smaller on each step is crucial to be sure that we’ll terminate the algorithm at some point. Otherwise, we could keep going solving sub-problems indefinitely.
So when do we stop solving sub-problems? We can stop as soon as we get to a case which is trivial to solve: a base case. In our case that is when one or both input strings are empty. If both strings are empty then the edit distance between them is 0, because they are already equal. Otherwise, the edit distance will be the length of the string that is not empty. For example, to transform “aab” into “” we can either remove the 3 characters from the first string or insert them into the second string. In any case, the edit distance is 3.
What we have done so far is defining the solution to our problem in terms of the solution to a smaller sub-problem of the same type and identified the base case when we already know what the result is. This should be a clear hint that a recursive algorithm can be applied.
But first, lets translate the three choices discussed previously describing the relationship between sub-problems into something that will be more helpful when trying to code this. The recurrence relation can be defined as:
The first case of the previous formula is when we replace A[0] by B[0], the second one is when we delete A[0] and the last one is when we insert into A. The base cases are:
Notice that the case where both strings are empty is already covered by the first base case because length(A) == length(“”) == 0.
Translating this definition into a recursive algorithm is relatively straightforward:
public class BruteForceEditDistance implements EditDistance { public int editDistance(String word1, String word2) { if (word1.isEmpty()) return word2.length(); if (word2.isEmpty()) return word1.length(); int replace = editDistance(word1.substring(1), word2.substring(1)) + Util.replaceCost(word1, word2, 0, 0); int delete = editDistance(word1.substring(1), word2) + 1; int insert = editDistance(word1, word2.substring(1)) + 1; return Util.min(replace, delete, insert); } }
The Util class has some useful methods that we’ll use on the different implementations of the algorithm and it looks something like this:
public class Util { /** * Prevent instantiation */ private Util(){} public static int replaceCost(String w1, String w2, int w1Index, int w2Index) { return (w1.charAt(w1Index) == w2.charAt(w2Index)) ? 0 : 1; } public static int min(int... numbers) { int result = Integer.MAX_VALUE; for (int each : numbers) { result = Math.min(result, each); } return result; } }
The code looks concise and it gives the expected answer. But as you can probably imagine, given that we are talking about dynamic programming, this brute force approach is far from efficient. As with the fibonacci example that we saw on the last post, this algorithm computes the same answer multiple times causing an exponential explosion of different paths that we need to explore.
To see this, lets consider the sequence of calls that are made when we invoke this method with word1 = “ABD” and word2 = “AE”:
And that is only for two strings of length 3 and 2. Imagine what that picture looks like when you have proper words or even sentences. In my laptop, for any two strings with 10 or more characters the method never finishes. This approach clearly won’t scale.
So, can we apply dynamic programming to this problem? Remember the two basic properties of a dynamic problem that we discussed in the previous post: overlapping sub-problems and optimal substructure. As we just saw on the example of the previous figure, the edit distance problem clearly has overlapping sub-problems because we are solving smaller sub-problems of the same type to get to the final solution and we need to solve the same sub-problems multiple times.
What about optimal substructure? Can we compute the optimal solution if we have optimal solutions for the sub-problems? Of course! In our case we are trying to minimize the number of transformations, so if we have the optimal solution to the three cases we consider (replace, insert and delete) then we get the minimum from those 3 and that’s our optimal solution.
Remember from the previous post that we could have a top-down dynamic programming approach where we memoize the recursive implementation or a bottom-up approach. The latter tends to be more efficient because you avoid the recursive calls. More importantly, the choice between these two can be the difference between a working and a non-working algorithm if the number of recursive calls you need to make to get to the base case is too large. If this is not a problem, then the choice of which one to use usually depends on personal preference or style. Here’s a possible top-down algorithm first:
public class DPMemoizedEditDistance implements EditDistance { public int editDistance(String word1, String word2) { return editDistance(word1, word2, new HashMap<StringTuple, Integer>()); } private int editDistance(String word1, String word2, Map<StringTuple, Integer> computedSolutions) { if (word1.isEmpty()) return word2.length(); if (word2.isEmpty()) return word1.length(); StringTuple replaceTuple = new StringTuple(word1.substring(1), word2.substring(1)); StringTuple deleteTuple = new StringTuple(word1.substring(1), word2); StringTuple insertTuple = new StringTuple(word1, word2.substring(1)); int replace = Util.replaceCost(word1, word2, 0, 0) + transformationCost(replaceTuple, computedSolutions); int delete = 1 + transformationCost(deleteTuple, computedSolutions); int insert = 1 + transformationCost(insertTuple, computedSolutions); int minEditDistance = Util.min(replace, delete, insert); computedSolutions.put(new StringTuple(word1, word2), minEditDistance); return minEditDistance; } private int transformationCost(StringTuple tuple, Map<StringTuple, Integer> solutions) { if (solutions.containsKey(tuple)) return solutions.get(tuple); int result = editDistance(tuple.s1, tuple.s2, solutions); solutions.put(tuple, result); return result; } /** * Helper class to save previous solutions * */ private class StringTuple { private final String s1; private final String s2; public StringTuple(String s1, String s2) { this.s1 = s1; this.s2 = s2; } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this,obj); } } }
Lets see what is going on here. First of all, we are using a Map to store the computed solutions. Since the input to our method are two Strings, we created an auxiliary class with the two Strings that is going to serve as the key to the Map. Our public method has the same interface as before, receiving the 2 inputs and returning the distance. In this memoized version we create the Map here and delegate the calculation to the private method that will make the necessary recursive calls. This private method will use the computedSolutions Map to avoid doing duplicated work. The rest of the algorithm works exactly as the brute force approach we saw before. On each step, we compute (or get the result if it was already computed) the edit distance for the three different possibilities: replace, delete and insert. Now after computing these distances, we save them, take the minimum of them, save the result for the original input and return that.
This algorithm is a huge improvement over the naive recursive one we saw before. Just to give an example, the same invocation that never ended before now takes 0.075 seconds to complete. The good thing about this approach is that we are able to reuse the recursive method that we already had before with some minor modifications. The bad part is that we are doing a lot of comparisons and manipulations of Strings and this tends to be slow.
Since the two strings that we receive as input might be large, lets try to use a bottom-up approach:
public class DPBottomUpEditDistance implements EditDistance { public int editDistance(String word1, String word2) { if (word1.isEmpty()) return word2.length(); if (word2.isEmpty()) return word1.length(); int word1Length = word1.length(); int word2Length = word2.length(); //minCosts[i][j] represents the edit distance of the substrings //word1.substring(i) and word2.substring(j) int[][] minCosts = new int[word1Length][word2Length]; //This is the edit distance of the last char of word1 and the last char of word2 //It can be 0 or 1 depending on whether the two are different or equal minCosts[word1Length - 1][word2Length - 1] = Util.replaceCost(word1, word2, word1Length - 1, word2Length - 1); for (int j = word2Length - 2; j >= 0; j--) { minCosts[word1Length - 1][j] = 1 + minCosts[word1Length - 1][j + 1]; } for (int i = word1Length - 2; i >= 0; i--) { minCosts[i][word2Length - 1] = 1 + minCosts[i + 1][word2Length - 1]; } for (int i = word1Length - 2; i >= 0; i--) { for (int j = word2Length - 2; j >= 0; j--) { int replace = Util.replaceCost(word1, word2, i, j) + minCosts[i + 1][j + 1]; int delete = 1 + minCosts[i + 1][j]; int insert = 1 + minCosts[i][j + 1]; minCosts[i][j] = Util.min(replace, delete, insert); } } return minCosts[0][0]; } }
Here we create a matrix to hold the values of the edit distances of the different substrings. Instead of keeping references to all the different substrings, like we did on the memoized version, we just keep 2 indices. So minCosts[i][j] is the value for the edit distance between word1[i..n] and word2[j..m]. Given this structure, what is the smallest problem for which the solution is trivial? The one that considers the two last characters of each String: if both characters are equal then their edit distance is 0, otherwise is 1.
Lets follow the algorithm through the original example of “cat” and “cars” to better understand how it works. Suppose word1= and word2 =. Then, our matrix will have a size of 3×4 with all places initially set to 0:
Next we compare the two last characters of both Strings, so “t” and “s”. Since they are different we update minCosts[2][3] with 1:
Once we have that value, we can calculate all the other values for the last row and last column. For instance, what does minCosts[2][2] mean? According to our definition is the edit distance between word1[2..2] and word2[2..3], which in our case means the edit distance between “t” and “rs”. But since we already know that the edit distance between “t” and “s” is 1 (because we can look for that value on the matrix) any extra letter we add to the second string while leaving the first one fixed can only increase the distance by 1. So minCosts[2][2] is equal to minCosts[2][3] + 1, minCosts[2][1] is equal to minCosts[2][2] + 1 and minCosts[2][0] is equal to minCosts[2][1] + 1.
The same reasoning applies if we leave the column fixed and move up through the rows. After this two initial loops our matrix looks like this:
Now we can easily fill in our matrix by following the recurrence formula we defined in the beginning. For each cell we will need the value of the cell to its right, the cell directly below and the cell on its right diagonal. So we can traverse the matrix from bottom to top and from right to left. Applying the recurrence formula to minCosts[1][2] for example, we get that its value is 2. With this value we can calculate minCosts[1][1], minCosts[1][0] and the values for the first row. Our final matrix is:
So now that we have all our matrix filled up, what is the answer to our original problem? Remember once again that minCosts[i][j] is the value for the edit distance between word1.substring(i) and word2.substring(j). Therefore, since word1.substring(0) == word1, our final answer is the value sitting at minCosts[0][0].
What are the advantages of this bottom-up approach against the memoized version? First, we don’t need the recursive calls. Our implementation is a completely iterative method that just traverses a matrix. Second, we don’t need to keep track of all the possible substrings and operate on them. We simply use the indices of the matrix to represent the substrings which is considerably faster.
To conclude this post, lets recap what we did in order to solve this problem:
- We identified that we could solve the original problem by splitting it into smaller sub-problems of the same type
- We assumed that we somehow knew what the answers to the sub-problems were and thought about how we would use those answers to get to the answer for the original problem
- From the previous step we defined a general recurrence formula that represented the relationships between the different sub-problems. This recurrence formulation is usually the most important part of solving a dynamic programming formula. Once we have it, translating that into the algorithm is usually straightforward
- We implemented a naive recursive solution and we identified that we were solving the same sub-problems over and over again
- We modified the previous solution to save and reuse the results by using a memoized recursive method
- We identified that the recursive calls could be an issue for long strings and so we developed a bottom-up approach. In this version we defined a matrix to hold the results and we figured in which way we needed to fill it by using the exact same recurrence formula defined before
You can find all the implementations we saw here, together with automated tests for each one showing the differences in execution time on
In the next posts we’ll see that this same steps can be applied with minor modifications to a huge amount of different problems. Once you get familiar with the basic tips and tricks of dynamic programming most problems are quite similar.
Cheers!!! | http://www.javacodegeeks.com/2014/03/easy-to-understand-dynamic-programming-edit-distance.html | CC-MAIN-2015-35 | refinedweb | 3,050 | 62.48 |
Get the mobile number from a contact in a list component
I tried to create a list view that shows only the mobile phone numbers of my contacts. So i declared a detail filter that allows only contacts with mobile numbers. This works fine.
But in the component of the list view i can not differ between mobile and other phone numbers, so always the first number of the contact is shown. How can I show only mobile numbers? I have no idea how this can be done in QML.
@ListView {
id: mainList
anchors.fill: parent
clip: true
model: contactModel.contacts
delegate: listDelegate
ContactModel { id: contactModel filter: DetailFilter { detail: ContactDetail.PhoneNumber field: PhoneNumber.PhoneNumber value: PhoneNumber.Mobile } sortOrders: [ SortOrder { detail: ContactDetail.Name field: Name.LastName direction: Qt.AscendingOrder }, SortOrder { detail: ContactDetail.Name field: Name.FirstName direction: Qt.AscendingOrder } ] } Component { id: listDelegate ListItem { id: listItem Column { anchors.fill: listItem.paddingItem ListItemText { id: nameItem mode: listItem.mode role: "Title" text: displayLabel } ListItemText { id: numberItem mode: listItem.mode role: "SubTitle" text: phoneNumber.number //<- here i want to get the mobile number, not just the first available number } } } } ScrollDecorator { flickableItem: mainList }
}@
According to
you can access the phoneNumbers property of the contact, which is an array of all the phone number elements (). From here, I think you can iterate over all numbers, to find which number has a subtype of PhoneNumber.Mobile
Thanks for the reply.
But how can i iterate over this list in QML? I thought QML didn't work this way. The only thing i saw were conditional assignments.
In good old C++, i would define a functor object that finds me the right number, but in QML i have no idea whats the best approach.
QML can use good old Javascript. You can create a javascript function that does that, and then call it as your variable assignment.
@function findMobilePhoneNumber(phoneNumbers) {
for ( var i=phoneNumbers.length-1; i>=0; --i ){
// Check for phoneNumber subtype, exit loop when finding the mobile one
}
}@
Hehe, good old Javascript. I tried that but it appears that the phoneNumbers haven't subtypes at all.
This:
@
...
ListItemText {
id: numberItem
mode: listItem.mode
role: "SubTitle"
text: Helper.findMobilePhoneNumber(phoneNumbers) //<- have changed that
}
...
function findMobilePhoneNumber(phoneNumbers) {
console.log("phonenumbers length " + phoneNumbers.length );
for ( var i=phoneNumbers.length-1; i>=0; --i ){
console.log("subtypes length " + phoneNumbers[i].subTypes.length );
}
}@
leads to:
@phonenumbers length 2
subtypes length 0
subtypes length 0
phonenumbers length 1
subtypes length 0
...@
Did I miss something?
That looks about right, not sure why the subTypes would be empty. Maybe try the same without your DetailFilter (just in case it might be doing strange things). Hopefully someone who's used this before can help you out.
Hi,
maybe this is relevant to new users on iOS & Android as well.
You can query and display the mobile numbers from a contact with this code using V-Play:
import VPlayApps 1.0 App { AppListView { anchors.fill: parent model: nativeUtils.getContacts() delegate: SimpleRow { text: modelData.name detailText: modelData.phoneNumber } } }
You can find more details about it here:
Cheers, Chris | https://forum.qt.io/topic/6363/get-the-mobile-number-from-a-contact-in-a-list-component | CC-MAIN-2018-30 | refinedweb | 511 | 62.54 |
import "github.com/google/uuid"
Package uuid generates and inspects UUIDs.
UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services.
A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to maps or compared directly.
dce.go doc.go hash.go marshal.go node.go node_net.go sql.go time.go util.go uuid.go version1.go version4.go
Domain constants for DCE Security (Version 2) UUIDs.
const ( Invalid = Variant(iota) // Invalid UUID RFC4122 // The variant specified in RFC4122 Reserved // Reserved, NCS backward compatibility. Microsoft // Reserved, Microsoft Corporation backward compatibility. Future // Reserved for future definition. )
Constants returned by Variant.
var ( NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) Nil UUID // empty UUID, all zeros )
Well known namespace IDs and UUIDs
ClockSequence returns the current clock sequence, generating one if not already set. The clock sequence is only used for Version 1 UUIDs.
The uuid package does not use global static storage for the clock sequence or the last time a UUID was generated. Unless SetClockSequence is used, a new random clock sequence is generated the first time a clock sequence is requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1)
NodeID returns a slice of a copy of the current Node ID, setting the Node ID if not already set.
NodeInterface returns the name of the interface from which the NodeID was derived. The interface "user" is returned if the NodeID was set by SetNodeID.
SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to -1 causes a new sequence to be generated.
SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes of id are used. If id is less than 6 bytes then false is returned and the Node ID is not set.
SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. If name is "" then the first usable interface found will be used or a random Node ID will be generated. If a named interface cannot be found then false is returned.
SetNodeInterface never fails when name is "".
SetRand sets the random number generator to r, which implements io.Reader. If r.Read returns an error when the package requests random data then a panic will be issued.
Calling SetRand with nil sets the random number generator to the default generator.
A Domain represents a Version 2 domain
A Time represents a time as the number of 100's of nanoseconds since 15 Oct 1582.
GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and clock sequence as well as adjusting the clock sequence as needed. An error is returned if the current time cannot be determined.
UnixTime converts t the number of seconds and nanoseconds using the Unix epoch of 1 Jan 1970.
A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC 4122.
FromBytes creates a new UUID from a byte slice. Returns an error if the slice does not have a length of 16. The bytes are copied from the slice.
Must returns uuid if err is nil and panics otherwise.
MustParse is like Parse but panics if the string cannot be parsed. It simplifies safe initialization of global variables holding compiled UUIDs.
New creates a new random UUID or panics. New is equivalent to the expression
uuid.Must(uuid.NewRandom())
NewDCEGroup returns a DCE Security (Version 2) UUID in the group domain with the id returned by os.Getgid.
NewDCESecurity(Group, uint32(os.Getgid()))
NewDCEPerson returns a DCE Security (Version 2) UUID in the person domain with the id returned by os.Getuid.
NewDCESecurity(Person, uint32(os.Getuid()))
NewDCESecurity returns a DCE Security (Version 2) UUID.
The domain should be one of Person, Group or Org. On a POSIX system the id should be the users UID for the Person domain and the users GID for the Group. The meaning of id for the domain Org or on non-POSIX systems is site defined.
For a given domain/id pair the same token may be returned for up to 7 minutes and 10 seconds.
NewHash returns a new UUID derived from the hash of space concatenated with data generated by h. The hash should be at least 16 byte in length. The first 16 bytes of the hash are used to form the UUID. The version of the UUID will be the lower 4 bits of version. NewHash is used to implement NewMD5 and NewSHA1.
NewMD5 returns a new MD5 (Version 3) UUID based on the supplied name space and data. It is the same as calling:
NewHash(md5.New(), space, data, 3)
NewRandom returns a Random (Version 4) UUID.
The strength of the UUIDs is based on the strength of the crypto/rand package.
A note about uniqueness derived from the UUID Wikipedia entry:
Randomly generated UUIDs have 122 random bits. One's annual risk of being hit by a meteorite is estimated to be one chance in 17 billion, that means the probability is about 0.00000000006 (6 × 10−11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate.
NewRandomFromReader returns a UUID based on bytes read from a given io.Reader.
NewSHA1 returns a new SHA1 (Version 5) UUID based on the supplied name space and data. It is the same as calling:
NewHash(sha1.New(), space, data, 5)
NewUUID returns a Version 1 UUID based on the current NodeID and clock sequence, and the current time. If the NodeID has not been set by SetNodeID or SetNodeInterface then it will be set automatically. If the NodeID cannot be set NewUUID returns nil. If clock sequence has not been set by SetClockSequence then it will be set automatically. If GetTime fails to return the current NewUUID returns nil and an error.
In most cases, New should be used.
Parse decodes s into a UUID or returns an error. Both the standard UUID forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
ParseBytes is like Parse, except it parses a byte slice instead of a string.
ClockSequence returns the clock sequence encoded in uuid. The clock sequence is only well defined for version 1 and 2 UUIDs.
Domain returns the domain for a Version 2 UUID. Domains are only defined for Version 2 UUIDs.
ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 UUIDs.
MarshalBinary implements encoding.BinaryMarshaler.
MarshalText implements encoding.TextMarshaler.
NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is not valid. The NodeID is only well defined for version 1 and 2 UUIDs.
Scan implements sql.Scanner so UUIDs can be read from databases transparently Currently, database types that map to string and []byte are supported. Please consult database-specific driver documentation for matching types.
String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx , or "" if uuid is invalid.
Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in uuid. The time is only defined for version 1 and 2 UUIDs.
URN returns the RFC 2141 URN form of uuid, urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid.
UnmarshalBinary implements encoding.BinaryUnmarshaler.
UnmarshalText implements encoding.TextUnmarshaler.
Value implements sql.Valuer so that UUIDs can be written to databases transparently. Currently, UUIDs map to strings. Please consult database-specific driver documentation for matching types.
Variant returns the variant encoded in uuid.
Version returns the version of uuid.
A Variant represents a UUID's variant.
A Version represents a UUID's version.
Package uuid imports 16 packages (graph) and is imported by 3579 packages. Updated 2020-07-02. Refresh now. Tools for package owners. | https://godoc.org/github.com/google/uuid | CC-MAIN-2020-40 | refinedweb | 1,351 | 67.65 |
Design APIs 10x Faster
Free. Runs everywhere.
Throughout web and mobile software, you’ll find APIs to exchange data. They are now a foundational element of the development process. Many organizations have adopted an API-first approach, where this interface that programmers see is built before one that users see.
The most forward-thinking companies will prototype their API designs before committing them to permanent code. While this can happen with any language, Python is easy to read and has straightforward frameworks to help build REST APIs. In this tutorial, we’ll look at two Python API frameworks, as well as a code-free way to create mock servers.
Before diving into Python examples, it’s important to understand the overall API design process. Your goal is to quickly create an interface. You want our API consumers (such as a frontend web team) to envision what’s possible, even before live data is flowing through the code. You’ll get early feedback that could lead to important updates to your API that could have been major changes if you waited until the API was “complete.”
This design-first API process is covered in the API Design Guide, which says design-second APIs are an oxymoron. In other words, anyone creating an API is designing one. Unfortunately, in code-first APIs, the design is a guess that gets harder to change.
Keep in mind, even as you stub out the endpoints in this tutorial, we’ll be using mock data. It’s meant as a representation of your API-in-progress. It’s up to you whether you iterate upon it for your eventual production API.
Most REST APIs use resource endpoints and HTTP methods to help communicate actions. In this first example, let’s create a
/companies endpoint and perform a simple GET request to retrieve a list of companies.
There are many ways you can stub out your APIs in Python. This post includes the same examples in two frameworks, so you can compare their approaches and decide which to use.
We’ll cover them in that order, since Flask examples are typically shorter.
Firstly, make sure you have Flask installed. It’s easiest to use Python package manager, pip:
pip install flask
Now open up a new text file and copy-paste these contents:
from flask import Flask, json companies = [{"id": 1, "name": "Company One"}, {"id": 2, "name": "Company Two"}] api = Flask(__name__) @api.route('/companies', methods=['GET']) def get_companies(): return json.dumps(companies) if __name__ == '__main__': api.run()
The code includes a hard-coded array of two company objects to use as results. Next, we initialize Flask and declare a route for our endpoint. When a consumer visits
/companies using a GET request, the list of two companies will be returned.
Save the code as
flaskapi.py and then run it from the command line:
python flaskapi.py. Follow the local URL provided, and tack on our endpoint, such as
Your results should be something like:
[ { "id":1, "name":"Company One" }, { "id":2, "name":"Company Two" } ]
Now let’s see how the same example looks in Falcon.
Like Flask, Falcon can be installed using pip. At the same time, you can install gunicorn, an HTTP server:
pip install falcon gunicorn
Unlike Flask, Falcon does not have a built-in server. Now open up a new text file and copy-paste these contents:
import falcon, json class CompaniesResource(object): companies = [{"id": 1, "name": "Company One"}, {"id": 2, "name": "Company Two"}] def on_get(self, req, resp): resp.body = json.dumps(self.companies) api = falcon.API() companies_endpoint = CompaniesResource() api.add_route('/companies', companies_endpoint)
There’s a bit more to the boilerplate for Falcon. It uses a class for each resource and connects routes to instances of a resource. Due to the use of a class, it makes more sense to declare the hard-coded array of companies within the company resource class. The result is the same as our previous example, returning the JSON version of the company list.
Save the code as falconapi.py and then run it using gunicorn:
gunicorn falconapi:api. Follow the local URL provided, and tack on our endpoint, such as
Your results should be identical to the previous example:
[ { "id":1, "name":"Company One" }, { "id":2, "name":"Company Two" } ]
Now let’s see what it looks like when you want to add a company using the POST method.
Rare is the API with only one endpoint and request method. To get a better feel for creating REST APIs with Python, let’s see how we can expand an API using Flask and Falcon.
Open
flaskapi.py in your text editor and find the line after the last
return. We’ll add a new copy of the same endpoint:
@api.route('/companies', methods=['POST']) def post_companies(): return json.dumps({"success": True}), 201
This will look for a POST to
/companies with company data in the body of the request. Rather than handling the data (since this is just mocking the endpoints), we return success and include a 201 status code. In the GET example a status code wasn’t required because 200 is Flask’s default.
You can copy existing routes to add other endpoints. Edit the path and method to match your requirements. Flask does not restrict how you declare your endpoints, but you’ll find it easier if you keep them logically grouped.
By contrast, Falcon organizes your API with a separate class for each endpoint. HTTP methods are declared with specific functions within the class.
Open
falconapi.py and define a new function below the existing
on_get function:
def on_post(self, req, resp): resp.status = falcon.HTTP_201 resp.body = json.dumps({"success": True})
To handle a POST, we define an
on_post function. As with our Flask example, we’ll simply return success, along with a 201 status code. Falcon also assumes a 200 and has helper constants for common statuses.
Both Flask and Falcon provide fast ways to prototype a REST API in Python. If you are practicing design-first APIs, you can create mock servers before you write any code. All you’ll need is an OpenAPI document of your new API. For design-first organizations, these machine-readable descriptions serve as a source of truth for what’s possible with an API.
You can use an open source command line utility like Prism API Server to stage a mock API. It will consume your OpenAPI document to determine the endpoints, methods, and data supported by the API. Then it serves mock data and validates the API description.
Stoplight also provides hosted mock API servers which connects Prism to your API design and testing process. It’s easy to make sample calls against your mock API right from the browser. Then you can share them with your team and even connect your server to the frontend before you write any backend code.
No matter how you create your REST API, whether through code or generated from an OpenAPI document, collaboration is important. Mock APIs help you get feedback early. You can learn more in our Mock API Server Guide. | https://stoplight.io/blog/python-rest-api/ | CC-MAIN-2019-39 | refinedweb | 1,187 | 64.71 |
Board of Governors of the Federal Reserve System
International Finance Discussion Papers
Number 791, January..
Keywords: China, exports, deflation, prices
*The authors are Deputy Associate Director, Economist, and
Economist, respectively, in the International Finance Division of
the Federal Reserve Board. The views expressed in this paper are
solely the responsibility of the authors and should not be
interpreted as reflecting the views of the Board of Governors of
the Federal Reserve System or of any person associated with the
Federal Reserve System. We would like to thank David Howard,
Carolyn Evans, Jon Faust, Caroline Freund, Jane Haltmaier, Bill
Helkie, Karen Johnson, Deb Lindner, Catherine Mann, Jaime Marquez,
Michael Prell, Trevor Reeve, John Rogers, Nathan Sheets, Beth Anne
Wilson, and participants in the International Finance Workshop for
helpful comments and advice. James Chavez and Craig Evers provided
able research assistance. Correspondence should be addressed to:
Steven B. Kamin (steven.kamin@frb.gov),
Mario Marazzi (mario.marazzi@frb.gov), or
John W. Schindler (john.schindler@frb.gov),
Board of Governors of the Federal Reserve System, Washington DC
20551, USA. Return to text
In the past few years, as the issue of deflation has grown in
prominence, observers increasingly have pointed to China as a
source of downward pressures on global prices.1 Such concerns have been prompted by
several factors. First, as indicated in Chart 1, Chinese exports
have continued to grow strongly in recent years, even as world
trade decelerated with the global economic slowdown, leading to
increases in China's share of world markets. Second, China has run
sustained current account surpluses, contributing to a substantial
accumulation of international reserves and leading observers to
assert that China is adding more to world supply than it is to
world demand. Third, notwithstanding vigorous economic growth,
consumer prices in China had been roughly flat or declining for
several years (although they have picked up in recent months) ;
with China's exchange rate fixed to the dollar, this has supported
the view that Chinese export prices, measured in dollars, must have
been declining as well. Finally, but perhaps most importantly,
while China exports an increasingly wide range of products, it has
made especially deep inroads into particular sectors-toys, sporting
goods, apparel, and consumer electronics, among others. In
consequence, considerable anecdotal evidence has emerged of
competition from Chinese exports leading to downward price pressure
and lost market share on the part of producers outside of
China.
The view that China's export surge has contributed importantly
to declines in global inflation, and adds to the risk of global
deflation, is not universally
shared.2 Critics of
this view argue that it is unlikely that China could have a
pronounced deflationary effect on the global economy. First, as
large as China's economy is in dollar terms, and as rapidly as it
has grown, it still accounts for only about 5 percent of global
exports and GDP (Table 1); therefore, it seems unlikely that it
could restrain global activity and prices much by itself.3 Second, China's record of very high
export growth is by no means exceptional in East Asia; as shown in
Chart 2, Hong Kong and Korea also posted very high export growth in
the 1980s and 1990s, but no one at the time suggested that they
contributed to global deflation. Third, China's rapid export growth
has been associated with equally rapid import growth; thus China is
contributing to global demand as well as supply. In fact, concerns
have been raised that Chinese imports are boosting global commodity
prices.4 Finally,
while relatively large at $35 billion, China's current account
surplus in 2002 was unexceptional as a share of Chinese GDP (2.9
percent, Table 2) and minuscule as a share of global GDP (0.1
percent).
So far, neither side of the debate over China's impact on global
inflation, and, more generally, the global economy, has prevailed.
This, in part, reflects a lack of clarity in the discussion as to
whether and how, in principle, China could ``export deflation''.
Commentators rarely spell out their assumptions regarding the
channels through which Chinese export growth might affect global
inflation, the extent to which Chinese goods compete with goods
produced in other countries, or the likely responses of monetary
policies outside of China to deflationary effects of Chinese
exports. To clarify these issues, this paper develops a simple
analytical framework to help think about the impact on global
consumer prices of a step-up in Chinese productivity and
exports.
Perhaps more important than any theoretical ambiguities,
however, the continued debate over the impact of China on global
inflation trends reflects the paucity of empirical evidence bearing
directly on this issue. We are not aware of any research that has
measured the impact of Chinese export performance on foreign (i.e.,
non-Chinese) prices at an aggregate (i.e., national as opposed to
sectoral) level.5
To address this gap in our knowledge, this paper utilizes such
data as are available to assess the impact of China's exports on
the prices (mainly import prices) of its trading partners. We
utilize two main sources of data on import prices. The relatively
more reliable data are U.S. import prices, dis-aggregated by
end-use category. These data are not available on a bilateral
basis, so we cannot directly identify the effect of changes in
Chinese export prices on U.S. import prices. However, we do have
data on the share of imports in each category purchased from China.
Therefore, to gain a sense of the impact of Chinese exports on U.S.
import prices, we can assess whether those sectors experiencing the
largest increase in the share of purchases from China are also
those experiencing the greatest declines in import prices.
The data on U.S. import prices are considered relatively
reliable, since they are adjusted for differences in quality. For
most countries, however, such data are not available. Therefore, we
also draw on a set of export and import unit values that are
available for a large number of countries, drawn from the
International Trade by Commodity Statistics (ITCS) database of the
OECD. Because unit values are not adjusted for differences in
quality, they are considered less reliable than actual price
estimates, but they should at least be indicative of movements in
trade prices. Moreover, these unit values are available on a
bilateral basis, and hence provide the only direct reading
available on the prices paid for Chinese exports by its trading
partners. Using these data, we analyze changes in import unit
values in 26 countries for which sufficient data are available and
gauge the extent to which these changes could be attributed to
differences in the behavior of Chinese export prices relative to
the export prices of other countries.
Our basic conclusions are as follows. First, the different
approaches we've taken to assess the impact of Chinese exports on
global prices all concur that this impact is likely to have been,
while non-negligible, fairly modest. To summarize the results of
our approaches: (1) Our theoretical model suggests, plausibly
enough, that the effect of higher Chinese productivity-one possible
source of Chinese export growth-on the CPIs of its trading partners
should be proportional to China's share in global output; with that
share equal to only about 5 percent, a back-of-the-envelope
calculation would predict Chinese productivity growth to have
reduced global inflation on the order of only 0.3 percentage point
annually in recent years. (2) We identified a statistically
significant impact across sectors of the share of U.S. imports from
China on U.S. import prices, suggesting that the roughly half
percentage point average annual rise in China's share of U.S.
imports since 1993 has lowered overall U.S. import price inflation
by about 0.8 percentage point per year; given the relatively low
share of imports in U.S. GDP, however, the ultimate impact on the
U.S. consumer prices has likely been quite small. (3) Using the
OECD ITCS database, we estimate that Chinese exports lowered
average annual import unit-value inflation in a large set of
economies since 1993 by about 1/10 to 1/4 percentage point, in the
neighborhood of the prediction of our theoretical model, and by 1
percentage point in the United States. Moreover, we should note
that all of these approaches gauge only the effects of higher
Chinese exports on the prices of its trading partners; to the
extent that rising Chinese imports have bolstered aggregate demand
among China's trading partners, this should offset to some extent
the disinflationary effect of China's exports.
Second, China's exports have likely restrained the import prices
of its trading partners through various means: (1) replacement of
more expensive imports from other countries with cheaper goods from
China, (2) greater declines in Chinese prices compared with those
of imports from other countries; and (3) the effect of competition
from China in lowering the prices of imports from other countries.
Our decomposition of changes in import unit value based on the ITCS
data suggested channels (1) and (2) were both important. Although
our decomposition of the ITCS data does not shed much light on
channel (3), our regression analysis does not point to this effect
as having been very large, at least for U.S. import prices.
Finally, our analysis suggests that, at least in the United
States, the downward pressure on import prices stemming from
Chinese imports has had little discernable impact on domestic
producer prices. Specifically, we identified no statistically
significant correlation between the share of U.S. imports in a
particular sector coming from China and the rate of PPI inflation
in that sector. Although producer prices exclude the prices of
imports, this is surprising, given numerous accounts of Chinese
competition reducing price margins for domestic producers. We offer
three ways of rationalizing our result: Chinese goods may in
general not be very substitutable with U.S. goods; the share of
Chinese goods in many U.S. markets may not be large enough to allow
a discernable effect on pricing; and increases in the share of U.S.
imports coming from China may merely be offsetting reductions in
shares from other countries, as export platforms in other of our
trading partners move to China.
Before proceeding, several additional points should be
emphasized. First, it is generally understood that in the long run,
inflation is determined primarily by monetary policy. However, this
does not preclude Chinese exports restraining inflation in its
trading partners over some shorter interval, until that
disinflationary effect is recognized and steps are taken to offset
it. Second, our research does not attempt to gauge the effects of
Chinese exports on other aspects of economic performance besides
inflation, e.g., output or employment. Most economists believe that
greater trade leads to higher incomes and prosperity in the long
run, even if there are adjustment costs for some segments of the
economy in the short run, but such effects lie beyond the scope of
this paper.
The plan of the paper is as follows. Section II describes our
theoretical analysis of the impact of Chinese export growth on
global prices. Section III focuses on the impact of imports from
China on U.S. import prices, while Section IV focuses on their
impact on U.S. producer prices. Section V addresses the role of
Chinese exports on the behavior of import unit values for a wide
range of countries.
Discussions of China's possible impact on global inflation
trends frequently are muddied by a lack of clarity in various
respects. First, some observers downplay the possibility that
Chinese exports could induce global deflation. Aggregate prices,
they argue, are in the final analysis influenced by monetary
policy, and any downward pressures on prices induced by a surge in
Chinese exports could be reversed by policy loosening on the part
of the world's monetary authorities.6 This argument, however, may overstate
the control by central banks over national inflation rates in the
short- and medium-term, and thereby oversimplifies the monetary
policy decision. In practice, it may take time for deflationary
pressures to become apparent and elicit a policy response, and it
will also take time for changes in monetary policy to counteract
those pressures.
A second area of confusion concerns which Chinese prices are
likely to affect the prices of China's trading partners. The fact
that the Chinese CPI was falling while its exchange rate against
the dollar remained fixed could be taken to mean that China's
export prices must have been falling and China was thus exporting
its deflation abroad, and analysts frequently are unclear on this
point. Yet, the dollar prices of much of China's exports are likely
set in global markets, and trends in those prices could well differ
from trends in Chinese consumer prices.
Finally, discussions of the impact of Chinese exports on global
prices often fail to specify the channels through which this impact
may occur. On the supply side, cheaper imports from China might
push down CPIs and/or producer prices without adversely affecting
domestic activity and profits. On the demand side, lower Chinese
prices could reduce the market share of domestic producers and thus
depress domestic wages and producer prices.
To help clarify our thinking about the impact of Chinese exports
on global price trends, we borrow from standard textbook analyses
of international trade to fill in some of the conceptual gaps
described above. We develop a very simple framework that
incorporates an explicit, albeit rudimentary, monetary policy
assumption. Our model focuses on how the prices of two goods-those
of China and of the rest of the world-are set by global supplies
and demands. And, finally, it incorporates both supply-side and
demand-side channels through which increases in Chinese production
can lead to lower global consumer price inflation.
Observers have suggested several complementary explanations for
the on-going boom in Chinese exports, including productivity growth
stemming from market-oriented reforms, heavy direct foreign
investment into China, the advantage of low wages, and a highly
competitive exchange rate. We do not attempt to distinguish among
these explanations here. Rather, we assume an exogenous increase in
Chinese productivity and focus on the effect of resultant higher
exports on prices in the rest of the world.
To develop the simplest possible framework, we assume a world
comprised of two countries: China (C) and the rest of the world
(RW). Each country produces a single distinct good, which is
consumed in both countries and the price of which is determined by
global supply and demand. There is a single global currency-this is
not that unrealistic an assumption, given that China's exchange
rate is fixed against the currency of its most prominent trading
partner, the United States. However, capital controls allow the
money supply in each country to be determined exclusively by that
country's monetary authority.
The velocity of money in each country is assumed to be fixed and
equal to unity, so that nominal expenditures in each country are
equal to that country's (exogenous) money supply:
E = M(1)
E = M(2)
E : nominal
expenditures in country i (C, RW)
M: nominal money
supply in country i (C, RW)
For algebraic convenience later on, we assume that the shares of
expenditures devoted to Chinese goods and rest-of-world goods are
identical in China and in the rest of the world:
PD
E
M (3)
PD
E
M (4)
PD
E
M (5)
PD
E
M(6)
P : price of good
produced by country i (C, RW)
Dj : demand by
country j (C, RW) for the good of country i (C,RW)
share of
expenditures spent on goods from China
The share factor
is assumed to depend on the relative price of Chinese and
rest-of-world goods:
(P/P, `(
0
(7)
The supply of each country's good S is assumed to depend on two
factors: an exogenous productivity parameter S* (reflecting
technology, capital, and other endowments) and the relative price
of the two goods:
S = S( (P/P
; S (8)
S/(P/P
0, S/ S 0
S = S( (P/P
; S
(9)
S/(P/P
0 ,
S/S
0
These functions are derived in Appendix A. The rationale for the
productivity parameter is obvious: increases in productivity, all
else equal, raise the supply of the good.
The rationale for the relative price term is slightly more
complicated. We assume competitive full-employment labor markets in
both countries, with labor supplies that are positively related to
real consumption wages. In the rest of the world, for example,
higher Chinese prices raise the RW cost of living, induce upward
pressure on RW wages, and thus, in the absence of adjustment of the
RW product price, would lower the supply of RW goods, S . The higher the share of
consumption devoted to Chinese goods , the greater this effect will be. Analogous
considerations hold for the supply of Chinese goods S.
Equilibrium in the goods market entails the supplies of both
Chinese goods and rest-of-world goods equaling their respective
demands:
PS = PD
+ PD
M
M
MM
(10)
PS = PD
+
PD
M
M =
(M+
M (11)
This is a system of two equations in two unknowns -
P and P - and hence for given Chinese and
rest-of-world money supplies, this yields determinate outcomes for
the two goods prices.
We now consider the impact of a positive, exogenous shocks to
Chinese productivity S* on the prices of both goods, assuming domestic
money supplies are left unchanged. This is accomplished by totally
(log-) differentiating equations (10) and (11) and solving for
reduced forms of the rate of change of P and P as functions of the rate of
change of S*.
Skipping many laborious derivations, which are sketched out in
Appendix B, we first consider the global consumer price index P,
which depends on the prices of both types of goods in the model.
Because the shares of expenditures devoted to Chinese goods and
rest-of-world goods are identical for consumers in China and in the
rest of the world, the consumer price index is identical as
well:
P = P
P
(12)
Our first key result is quite straightforward:
%P = -
(%S*) (13)
Equation (13) shows that the response of global consumer prices
to an increase in Chinese productivity (where % denotes percentage change) is
equal to the increase in Chinese productivity itself, %S*, multiplied by (1) the elasticity of Chinese
supply with respect to productivity,
, and
(2) the share of Chinese goods in total expenditures . The simplicity of this result
should not be surprising: with the global money supply-and hence
total nominal expenditures-held constant, any increase in Chinese
production will have to lower global prices by the same proportion
as global production rises.
Simple as it is, however, this result provides a more formal
rationale for the view that, given its small size in the global
economy, increases in Chinese production are unlikely, by
themselves, to induce substantial declines in global prices. Assume
the Chinese share in global consumption is roughly similar to its
share in global production, so = .05; the elasticity of Chinese supply with
respect to Chinese productivity growth is equal to unity; and labor
productivity growth in China is running at 6 percent annually
(although estimates of productivity growth are generally quite
uncertain). Equation (13) then implies that Chinese productivity
growth has been lowering global consumer price inflation by 0.3
percentage point per year, a non-negligible amount, but certainly
not enough to raise concerns about global deflation.
It has been suggested that the impact of China on global prices
might be greater than that implied by its share in global
production, if China can produce goods more cheaply than its
foreign competitors at the margin. That is, even if China's share
in output currently is small, the threat of being able to supply
more goods and at lower prices may suffice to restrain the prices
of goods produced outside China. However, this threat is likely to
be credible only if China has enormous amounts of excess capacity,
so that it can indeed raise its production and market share
sufficiently to lower global prices as shown in equation (13).
China may indeed have extensive amounts of underutilized low cost
labor, and certain sectors are currently believed to be running
below full capacity. Nevertheless, it is far from clear that China
could further boost production by a significant share of global GDP
in the very near term.
Finally, we would underscore the dependence of the result in
equation (13) on the assumption that money supplies remain
constant. Clearly, any disinflationary effect of China on its
trading partners can be offset through looser monetary policy on
the part of the latter's central banks. Alternatively, a loosening
of Chinese monetary policy, by increasing demand for both Chinese
goods and imports from the rest of the world, would also moderate
the disinflationary effect of higher productivity growth.
Less straightforward than the impact of a Chinese productivity
increase on aggregate global prices are its separate impacts on the
prices of Chinese and rest-of-world goods:
%P
%S*)
(14)
%P
%S*)
(15)
: elasticity
of the share with
respect to relative prices P/P
: elasticity
of Chinese supply with respect to relative prices P/P
(also, the negative of the elasticity of rest-of-world supply
with respect
to relative prices P/P
Daunting as they may appear, equations (14) and (15) help
illuminate the channels through which higher Chinese productivity
lowers global prices, as shown in equation (13).
In the first channel, higher Chinese productivity, by reducing
the prices of Chinese goods, directly lowers CPIs in China and
elsewhere. Consider a case in which supply curves in China and the
rest of the world are unresponsive to relative prices, so
= 0, and in
which the expenditure share is unresponsive to relative prices as well, so
= 0; the
latter case corresponds to that of unit price elasticities of
demand for Chinese and rest-of-world goods, so movements in their
prices elicit exactly offsetting changes in their demanded
quantities. In that case, equations (14) and (15) can be
re-written:
%P
(%
S*) =
(%S*)
(14a)
%P
(
(%S*) =
0 (15a)
In this extreme case, both the supply and demand for goods
produced outside China are unaffected by the rise in Chinese
production, so that the price of rest-of-world goods remains
unchanged. In consequence, the prices of Chinese goods fall by the
exact extent that production rises, and the fall in global prices
indicated in equation (13) results entirely from the decline in the
price of Chinese goods in the CPI.
In a second channel, lower Chinese prices reduce global prices
by lowering production costs in the rest of the world. Consider a
slightly less restrictive case than above in which supplies of
goods are allowed to respond to relative prices 0) but the expenditure
shares remain invariant ( = 0):
%P
(
%S*)
(14b)
%P
(
%S*)
(15b)
As equations (14b) and (15b) make clear, once supply effects are
introduced, the increase in Chinese productivity leads to a smaller
decline in the prices of Chinese goods (compared with equation 14a)
but some decline (as opposed to no decline) in the price of goods
produced outside China. However, this latter decline does not
involve any disruption of activity on the part of non-Chinese
producers. The fall in their prices occurs as lower Chinese prices
reduce the cost of living abroad-this leads to a lower nominal wage
(albeit not a lower real wage, measured against overall consumer
prices) and allows non-Chinese producers to sell more of their
goods at lower prices.
In the final channel, lower Chinese prices lower the prices of
rest-of-world goods by diverting demand from them. Consider a case
in which supplies do not respond to relative prices ( = 0) but the share of
expenditures devoted to Chinese and non-Chinese goods is allowed to
respond to relative prices (
0):
%P
%S*)
(14c)
%P
%S*)
(15c)
Consider, first, the case where a lower ratio of
Chinese/non-Chinese prices raises the share of expenditures devoted
to Chinese goods:
0. This
corresponds to a case where the price elasticity of demand for
Chinese goods exceeds one, as might prevail if Chinese and
non-Chinese goods are highly substitutable with each other. In this
instance, the price of non-Chinese goods unambiguously declines,
albeit not as much as the price of Chinese goods. This decline in
non-Chinese goods prices exclusively reflects competition from
Chinese goods for market share, and corresponds to the scenario in
which higher Chinese production detracts from production activity
overseas.
Yet, this is not the only scenario that is possible. If Chinese
and non-Chinese goods are not very substitutable and the price
elasticity of demand for Chinese goods is accordingly fairly
inelastic, reductions in Chinese prices will cause declines in the
share of expenditures devoted to Chinese goods, consistent with
0. Under
these circumstances, as indicated in equation (15c), the prices of
rest-of-world goods could actually rise in response to lower
Chinese prices. This occurs because a reduced share of expenditures
on Chinese goods corresponds to a higher share devoted to
non-Chinese goods-the higher demand drives up the prices of the
latter category.7
The model highlights three channels through which Chinese
productivity growth and lower export prices would lower foreign
(non-Chinese) consumer prices: (1) direct effects on foreign
(non-Chinese) CPIs stemming from lower costs of import goods; (2)
indirect effects working through lower foreign production costs, as
the lower CPIs mentioned above depress nominal wages;8 and (3) effects on the demand for and
price of foreign products resulting from lower Chinese export
prices. Only the third channel leads to loss of markets, profits,
and activity on the part of foreign producers, and whether or not
this actually takes place is ambiguous a
priori: if the demand for Chinese exports is highly elastic,
lower Chinese prices will reduce the share of income spent on
foreign products; however, if the demand for Chinese exports is
highly inelastic, lower Chinese prices might merely reduce
expenditures on imports from China and raise expenditures on
domestic goods. Identifying the elasticity of demand for Chinese
goods would therefore represent a high priority for further
research.
The simple framework described above does not distinguish
between consumer prices, output prices, and import prices. In
practice, however, such distinctions are likely to be important. In
this section, we assess whether the expansion of China's exports
has led to a significant reduction in U.S. import prices.
Chart 3 presents data on the inflation rates (percent changes in
year-average price levels) for the U.S. Consumer Price Index (CPI),
the CPI for goods, and the U.S. Import Price Index; the upper panel
compares inflation rates for all items, whereas the bottom panel
removes the effect of oil prices. The chart makes clear that U.S.
import price inflation has generally stayed well below consumer
price inflation. Import price inflation also indicates some
downward tendency over the 1990s. This makes it a prima facie candidate to help explain the decline
in CPI inflation, although one would not want to push that
hypothesis too strongly in the absence of further
investigation.9 To what
extent the declining tendency in U.S. import inflation is
attributable to China is difficult to say, as import prices are not
available by country of origin, but only for broad regional
aggregates. Chart 4 depicts U.S. import inflation by region of
origin; China is included in ``other countries'', accounting for
about 16 percent of U.S. imports from these countries over the past
decade. The chart does not present strong evidence that China has
been pushing down U.S. import prices. In most years, prices of
imports from the ``other countries'' are not falling discernibly
faster than those of imports from other regions. The panels in
Chart 5 present similar data, but divided into non-manufactured and
manufactured categories. For manufactured goods, prices of goods
imported from the ``other countries'' region do appear to have been
particularly weak, especially since 1998, although it is difficult
to say how much of this owes to China's export performance.
If we had data on import prices and import volumes by country of
origin, it would be relatively straightforward to compute the
contribution of imports from China to changes in aggregate U.S.
import prices. As noted above, such data are not available.
However, we do have data on the prices of imports, aggregated
across all countries of origin, but dis-aggregated by end-use
sector, e.g., sporting goods, apparel, consumer electronics.
Additionally, data are available on the share of nominal imports
accounted for by imports from China, also broken down by end-use
sector. In principle, if Chinese export prices are lower than those
of other countries and/or falling more rapidly, then those types of
goods with particularly high or rising shares of imports from China
should be experiencing particularly low rates of price inflation.
This, in turn, should result in negative correlations, across
end-use sectors, between import price inflation, on the one hand,
and the level and/or change in shares of imports purchased from
China, on the other.
To test this hypothesis, we estimate the following equation:
%P
(16)
P : price of US
imports in sector i in year t
: share of
U.S. imports in sector i coming from
region j (j = C, RW) in year t
Equation (16) represents a cross-sectional regression equation,
to be estimated across end-use import sectors i. For each
observation, the rate of import price inflation in sector i, over a
particular period from t-n to t, is matched against the change in
the share of that type of import accounted for by China,
, and the
initial level of the Chinese share, Share
.
We would stress that equation (16) is not a structural
behavioral equation, as the coefficients on the share variables
likely reflect a mixture of channels through which Chinese exports
may affect U.S. import prices. First, these coefficients likely
reflect the direct arithmetic effect of these shares on the average
price of imports. If Chinese goods are cheaper than those imported
from other countries, then the larger the increase in the Chinese
share (and thus the more that cheap Chinese goods are substituted
for expensive goods from other countries), the more will the
average price of U.S. imports decline. And if prices of imports
from China are falling more rapidly (or rising more slowly) than
those of imports from other countries, than the higher China's
share in U.S. imports, the greater the restraint on average U.S.
import prices.10
Second, the coefficients on the share variables will likely
reflect these variables' correlation with other measures of Chinese
export performance that affect U.S. import prices. In sectors where
prices of imported Chinese goods are especially low or falling
especially fast, for example, this will directly restrain average
U.S. import prices for those goods. In such sectors, moreover,
Chinese competition will likely induce downward pressure on the
prices of goods imported from other countries, thus restraining
U.S. import prices indirectly as well. Because those sectors are
likely to be ones where the share of Chinese goods in U.S. imports
is high and/or rising, however, this correlation will likely cause
the coefficients on the share and/or change-in-share variables to
become more negative, compared with what their arithmetic effect on
U.S. import prices alone would dictate.11 12
Thus, the estimation results for (16) should be interpreted as
summarizing associations in the data between shares of Chinese
imports and U.S. import prices rather than estimates of a
structural equation. Even those associations, however, could be
spurious and misleading if competitive conditions (due to
globalization or changes in market structure) in a given sector
both reduced prices and induced manufacturers to source their
products from a low-wage country, say China. In this case, both
%P and Share
would be
correlated with a third variable-competitive conditions-and this
could lead the coefficient on Share
to be more
negative than would be implied by the actual effect of Chinese
exports alone on U.S. import prices. To address this concern, we
add lagged import price inflation as an explanatory variable, as
indicated in equation (17); this controls for other factors -
globalization, market structure, etc. - that tend to lower
inflation in a particular sector, so that the coefficient on
represents
the genuine impact of additional imports from China on import
prices in that sector.
%P
%P(17)
Finally, it is possible that declines in Chinese export prices
could have induced sufficient declines in the prices of other
countries' exports so that the latter's shares in U.S. imports
remained unchanged. Thus, in principle, China could have depressed
U.S. import prices without any change in the China-share variables,
causing equation (17) to underestimate the impact of Chinese
exports on U.S. import prices. In practice, however, this scenario,
while perhaps applicable to homogenous commodities such as oil,
would appear unlikely to apply to the differentiated manufactures
that China tends to export.
The data used in our analysis are based on the five-digit
end-use13 sectoral
classification scheme for U.S. imports during the 1993-2002 period.
For each sector, U.S. import price levels are collected from the
International Price Program of the Bureau of Labor Statistics
(BLS). However, price data are not available for all five-digit
end-use sectors. Currently, the BLS publishes only 93 import price
series for five-digit end-use sectors out of a total of nearly 140
sectors. Moreover, the price series have different start dates and
as a result many sectors had to be dropped.14 In the end, we were left with 74
sectors. These 74 sectors accounted for over three quarters of the
value of all U.S. merchandise imports during the 1993-2002 period.
Chart 6 illustrates the year-average inflation rate in the overall
U.S. import price index published by the BLS and compares it with
the rate of change of the U.S. import price index we constructed
from the 74 available sectors-by and large, the two inflation rates
track each other reasonably closely.
To calculate the import shares, for each sector, annual U.S.
import values are drawn from data collected on a Census basis by
the Department of Commerce. Chinese import shares for each sector
are then calculated by dividing the U.S. import value from China
(in year t and sector i) by the overall U.S. import value (in year
t and sector i).
Table 3 and Chart 7 display some sample statistics of the data;
a comprehensive tabulation of the data is presented in Appendix C.
During the 1993-2002 period, average annual import inflation for
most sectors was close to zero-in the -1 percent to +1 percent
range. However, extremely negative inflation rates in high-tech
sectors (where hedonic pricing is employed) bring the
equally-weighted mean over all sectors into the deflationary
range.
At the same time, most of the sectors experienced an increase in
the share of U.S. imports coming from China during the 1993-2002
period. The increases were particularly pronounced in consumer
goods sectors, such as home entertainment equipment, toys and
furniture, but increases occurred in many other sectors as
well.
Chart 8 presents scatterplots of sectoral rates of import price
inflation against sectoral increases in China's import share (the
top panel) and against initial levels of China's import share (the
bottom panel). Regression lines indicating the bivariate
relationship between the variables are also shown. The scatterplots
provide some, albeit not especially strong, evidence of a negative
correlation between sectoral import inflation rates and the level
and changes in China's import share.
The first column of Table 4 indicates the results of regressing
average annual import inflation during 1993-2002, by sector, on
both the average annual change in China's import share over that
period and the initial level of that share. The coefficient on the
change in share is negative, as expected, and is significantly
different from 0. Contrary to expectations, the coefficient on the
initial level of the share is positive, albeit insignificantly
different from zero.
The second column of Table 4 presents similar estimates to those
in the first column, but includes a lagged dependent variable to
serve as a control variable for the effects of competition and/or
market structure, as described above. (Owing to data limitations,
the import inflation variable on the left-hand-side is now measured
only from 1997 to 2002, and the time periods over which the
right-hand-side variables are measured have been adjusted
accordingly.) However, the coefficient on lagged inflation is
essentially zero, suggesting it is unlikely to be acting as a
control variable in the manner described in Section III.1.
To look into this further, we examined the relationship between
sectoral inflation rates in the 1993-97 and 1997-2002 periods. As
shown in the scatterplot in Chart 9, there is generally a positive
relationship between inflation rates in the two periods, but this
is obscured by several outliers. In particular, prices of green
coffee-which barely figure in imports from China-rose by 21 percent
in the 1993-97 period and then fell by 22 percent in the 1997-2002
period.
Returning to Table 4, the third column indicates the results of
estimating the same regression as in column (2), but with the
observation for coffee imports removed. The coefficient on lagged
inflation now becomes positive and highly significant, while that
on changes in China's import share remains negative and
significant. At -0.79, the coefficient indicates that a one
percentage point rise in the Chinese import share of a given sector
during 1997-2002 was associated, on impact, with 0.79 percentage
point lower annual import inflation in that sector. Surprisingly,
the coefficient on the initial level of China's import share
remains positive, but is not significantly different from zero.
These results would suggest that imports from China have indeed
depressed U.S. import price inflation to some extent.15 The estimated long-run impact of
higher Chinese import shares on U.S. import inflation, based on
equation (3), is about -1.3 (calculated as: -.791/[1 - .384]).
Considering that the share of imports from China in total U.S.
imports grew by an average rate of about 0.6 percentage point
annually over the past decade, this coefficient suggests, as a
back-of-the-envelope estimate, that imports from China might have
depressed overall U.S. import inflation by about 0.8 percentage
point annually. This represents a far from negligible impact on
U.S. import prices, and moreover, prices in many sectors were
likely affected to a considerably greater degree.16 Even so, with merchandise imports
accounting for only about 11 percent of U.S. GDP and merchandise
imports of consumer goods accounting for less than 10 percent of
U.S. consumption, the direct effect of imports from China on U.S.
consumer price inflation in recent years would likely have been
quite small, on the order of 0.1 percentage point or less.17
While direct effects of Chinese imports on U.S. consumer prices
were likely quite small, the analytical framework described in
section II describes two other channels through which Chinese
imports could affect U.S. prices. One channel operates through the
demand side, with Chinese imports competing for market share with
U.S. products, thereby lowering the demand for and prices of U.S.
products. A second channel is through the supply side; lower
Chinese import prices could lower the cost of living and thus
restrain nominal wages and production costs, more likely, they
could reduce the costs of imported intermediate inputs-an effect
not explicitly incorporated into the theoretical model described in
Section II.18
As one means of gauging the extent to which Chinese imports have
affected U.S. producer prices, we perform an analysis similar to
that which we applied to U.S. import prices: we examine the
correlation between movements in the producer price index (PPI) for
selected categories of goods and in the shares of Chinese imports
in total U.S. imports of the same goods category. Specifically, we
estimate regressions similar to equation (17) above:
%PP
%PP
(18)
Here, PP refers
to the level of producer prices in sector i at time t. The
motivation for equation (18) is similar to that described in
section III above. Lagged PPI inflation serves as a control to
ensure that the estimated coefficients on the share variables do
not reflect their correlation with other, omitted variables that
might be affecting producer price inflation.
Unlike the U.S. import prices and import shares analyzed in
Section III, the BLS producer price index (PPI) is not available,
disaggregated by end-use sector. However, both the PPI and imports
shares are available, disaggregated on the basis of the 4-digit
Standard Industrial Classification (SIC) system, revision 1987;
import data come from the U.S. International Trade Commission.
Because these data are available on a more disaggregate basis than
under the end-use classification system, we have been able to
compute changes in import shares and corresponding PPI inflation
for 388 sectors (accounting for over 80 percent of U.S. merchandise
imports), compared with only 74 sectors under the
less-disaggregated end-use system. Moreover, as manufacturing and
non-manufacturing sectors are broken out in the SIC system, this
allows us to focus on China's impact on producer prices within the
manufacturing sector alone.
Chart 10 presents scatterplots of both changes and levels of
Chinese imports shares, by SIC sector, against rates of PPI
inflation. These scatterplots indicate little correlation between
Chinese import shares and PPI prices.
The lack of correlation between Chinese import shares and PPI
inflation is confirmed by the regression estimates shown in Table
5. Regardless of whether or not lagged inflation is included as an
explanatory variable, and whether the analysis is performed on all
sectors or only
those identified in the SIC system as manufacturing sectors, the
estimated coefficients on the share and change-in-share variables
are very small and not significantly different from zero.19
The lack of correlation between Chinese import shares and U.S.
PPI inflation is surprising, considering that, as described in
Section III, we estimated a statistically significant correlation
between Chinese import shares and U.S. import prices. It is
possible that producer prices are most sensitive to import prices
(and hence Chinese import shares) in sectors for which imports
account for a large fraction of the domestic market; because the
regressions shown in Table 5 do not control for the share of total
imports in the domestic market, they may be failing to identify the
effect of China's share of those imports. To address this concern,
we augmented our equation (18) with a measure of import
penetration, IPR:20
PP
%PP
)(IPR
(IPR
(19)
IPR : import
penetration ratio for sector i = (imports/(domestic shipments + imports - exports
In the second line of equation (19), the Chinese share and
change-in-share variables are interacted with initial levels of the
import penetration ratio for that sector. The import penetration
ratio represents the share of total imports of a good in the
domestic market-shipments of domestic producers plus imports less
exports-for that good. Thus, Chinese import shares are weighted by
the prominence of imports in the domestic market.21
Data for domestic shipments on a basis comparable to that for
producer prices and Chinese import shares are available, from the
U.S. Census Bureau, for 38 3-digit SIC sectors-covering roughly 40
percent of both U.S. merchandise imports and manufacturing
shipments-over a time span ending in 2000. The first column of
Table 6 presents our re-estimation of equation (18) using the
3-digit SIC data. The results, which indicate no effect of Chinese
import shares on producer prices, are similar to those (Table 5,
column 4) based on the 4-digit SIC data. The second column of Table
6 presents estimation results for equation (19); the Initial Share
and Initial Share*IPR variables were dropped because their
coefficients were positive and insignificant. Even so, the
remaining Share
variable is still insignificant, while the Share*IPR variable is only
significantly different from zero at the 15 level. Moreover, even
if the latter variable was significant, its coefficient estimate,
taking into account that the average value of the IPR was only
about 20 percent in 1995, implies that the roughly 0.6 percentage
point annual rise in the share of Chinese imports in total imports
during the past decade or so led to only 3/10 percentage point less
producer price inflation.
In column 3 of Table 6, we have deleted the insignificant
Sharevariable and added the Initial
IPR variable by itself; the motivation is to capture effects of
total imports on producer prices, as distinct from effects related
primarily to Chinese import shares. Addition of the IPR variable,
while not significant itself, substantially reduces the size and
significance of the coefficient on the ShareIPR variable. When the latter
variable is dropped from the equation (column 4), the IPR term
becomes borderline significant. With the IPR term averaging about
20 percent, its coefficient implies that overall import penetration
lowered producer price inflation by 8/10 percentage point annually.
This is a sizeable effect.22 However,
with Chinese imports comprising only about 4 percent of total
imports in this sample in 1995, this implies that, through their
contribution to total import penetration, Chinese imports
apparently depressed producer price inflation by a negligible
extent.
Our empirical work suggests that even though the rising share of
Chinese goods in U.S. imports has restrained import prices
somewhat, it has had little effect on U.S. producer prices. This is
surprising, given assertions that competition from China is
depressing prices and reducing profit margins.23 We offer several explanations for our
seemingly contradictory findings.
First, products imported from China may not generally compete
with U.S. products. As discussed in Section II.2, above, if U.S.
and Chinese goods are not very substitutable with each other, lower
Chinese prices may have little impact on U.S. producer
prices.24 Of
course, even if most U.S. products do not compete with Chinese
goods, there would likely be at least a limited range of U.S.
products that are indeed exposed to Chinese competition, and firms
in these sectors could certainly experience adverse
effects.25
Second, even if many Chinese products are broadly substitutable
with U.S. products, Chinese imports may represent a small enough
share of the U.S. market in most sectors such that their impact on
prices is limited. Although Chinese imports have grown to about 11
percent of total U.S. merchandise imports, they still represent
only about 1 percent of U.S. GDP. This is consistent with our data
for 38 3-digit SIC categories described above: with an average
import penetration ratio of 20 percent and an average China share
in imports of 4 percent, this implies an average share of Chinese
imports in the domestic market of a little less than 1 percent. Of
course, there would likely be some U.S. producers who were indeed
affected by competition from Chinese products, even if U.S.
producer prices more generally were not.
Finally, increases in the shares of Chinese goods in U.S.
imports in a sector may overstate the extent to which overall
imports in that sector have risen. As indicated in Chart 11,
increases in China's share in several major end-use
categories-consumer goods, capital goods-have been associated with
declines in the overall Asian share of U.S. imports in those
categories. This may have been the result of China out-competing
its neighbors for market share. In a related development, non-China
Asian economies have shifted from exporting directly to the United
States to exporting to China; China then further processes these
goods and re-exports them to the United States.26 Under these circumstances, increases
in imports from China may not reflect increases in the overall
supply of imported goods and hence may be less likely to compete
with and lower the prices of U.S.-produced goods.
In this section, we attempt to go beyond the data for the United
States alone and gauge the impact of Chinese exports on the import
prices of a broad group of countries. As noted in the introduction,
sectorally disaggregated import prices are not available on a
consistent basis for many countries. However the OECD's
International Trade by Commodity Statistics (ITCS) database
contains disaggregated export and import unit values on a
consistent basis.
Unit values are merely the value of imports or exports, divided
by a measure of their quantity (e.g., number of units, kilograms,
etc.). Because these measures of quantity are not adjusted for
differences in quality or other characteristics, unit values are
considered less reliable than actual price surveys. However, for
most types of goods these data should be at least indicative of
movements in trade prices. Moreover, the data are available at a
high degree of disaggregation, making it more likely that unit
values will be computed for comparable goods, and hence that they
will be accurate.
We use the ITCS database to compute the contribution of Chinese
exports to trends in import unit values among the 26 countries in
the database for which sufficient data are available. Unlike in our
analysis of U.S. import prices, where data on import shares were
available by trading partner but data on import prices were not,
the ITCS database makes available, for each sector and
disaggregated by trading partner, data on both shares of imports
and on import unit values. Therefore, for each sector in a given
country, we can separate import inflation into the part
attributable to China and that attributable to the country's other
trading partners. This calculation is then aggregated across
sectors to compute China's effect on a country's overall import
inflation.
The ITCS database is a subset of the United Nations COMTRADE
database, and it contains data from 33 economies (the OECD plus
China, Taiwan, and Hong Kong) at a highly disaggregated level. For
each economy we pulled data for 1993 and 2001 on the value and
quantity of their imports from the world and from China for each of
roughly 2500, 5-digit, SITC Rev. 3 commodity categories.27 (We picked up only two years of data,
owing to data storage and handling constraints; even only two years
implies on the order of 2 million observations.) Using these data,
we calculated, for each economy, imports from China and imports
from the rest of the world in each category, and then calculated
the corresponding unit values.
These sectoral unit values were then used to construct overall
import unit value indices for each country for 1993 and 2001. To do
this we calculated a Laspeyres index for each country, the formula
for which is:
The resulting indices are shown in Table 7, alongside similarly
constructed import unit value indices from the IMF's International
Financial Statistics. While the correlation between these two
measures of unit values-the correlation coefficient is .43-is not
perfect, they generally capture similar broad trends.31 This is further seen in Chart 12,
where the calculated Laspeyres indices are shown against the IFS
indices in a scatterplot. The points, while not tightly bunched
around the 45-degree line, are generally close to it.
For each country, we first computed the contribution of Chinese
exports to the rate of growth of import unit values over 1993 -
2001 in each of roughly 2,500 sectors, depending upon the country.
We employed a decomposition equivalent to that shown in footnote
[11] and reproduced below, for convenience:32
%P = %P(P/P (21)
+ Share[(P - P
/P]
The first term in (21) represents the contribution of a
country's other trading partners to import unit-value inflation in
sector i, while the second two terms represent the impact of China
on unit-value inflation. By construction, China is considered to
have no impact on import inflation if its export unit values are
the same as those of a country's other trading partners (the second
term) and if its export unit values rise at the same rate as the
other trading partners (the third term).
Equation (2) below indicates that a Laspeyres index for import
unit values can be expressed as an average of sectoral ratios of
current- to initial-period unit values, weighted by initial-period
shares of that sector in total nominal imports.
Table 8a presents our decompositions of the average annual
growth of import unit values during 1993 - 2001 for the 26
countries in the ITCS database for which sufficient data were
available.33 The
first column shows the overall inflation rate in each country's
calculated import unit value index. The second column represents
the import inflation attributable to the country's other trading
partners, corresponding to the first term in equation (21) above.
The third column represents the total contribution of Chinese
exports to the country's import inflation-this includes both the
contribution resulting from increases in China's share in imports
(the second term in equation 21) and that resulting from different
growth rate of Chinese and non-Chinese unit values (the third term
in equation 21).
Table 8a indicates that, from country to country, the
contribution of imports from China to import inflation has varied
considerably. Not surprisingly, this contribution is highest for
economies with whom China has the strongest trading links: Japan,
Korea, and the United States. Even for these economies, however,
the estimated disinflationary impact of China has been relatively
moderate: Chinese imports are calculated to have depressed average
annual import unit-value inflation by about 1 percentage point
below what it otherwise would have been. On average for all of the
countries in the sample, the contribution of China to import
deflation has been much smaller: from 1/10 (median) to 1/4 (mean)
percentage point. Hence, our calculations provide little support
for the view that China has exerted strong deflationary pressures
on global trade prices.
Now we take this analysis a step further by breaking the China
effect down into the two components shown in equation (21). Recall
that the second and third terms of (21) collectively represent as
the China effect. The second term in (21) could be referred to as
the China share effect, or the effect that China has had on import
unit values by virtue of its increasing import share (as cheaper
Chinese goods replace more expensive goods imported from other
countries). The third term could be referred to as a China price
effect, resulting from the unit values of Chinese goods growing at
a different rate than those of goods imported from other
countries.
In Table 8a, our calculations of the China price and China share
effect are shown in columns four and five. Across countries,
neither components appears to dominate the overall China effect.
The price effect is generally negative, with Japan, Korea, and the
United States-China's largest trading partners-having especially
large negative values. The share effect is more consistently
negative and a bit more evenly distributed across countries. Thus
China's influence on global import inflation apparently is working
both through the change in its export unit values and the change in
its share of other countries' imports.34
The remaining columns of Table 8a indicate that China's import
share increased for every country except Portugal and Sweden. The
countries for whom the increase was largest-Australia, Japan,
Korea, and the United States-are those for whom the overall China
effect was largest.
One final consideration is that our decomposition analysis only
identifies the direct effect of Chinese exports on the average
import unit values paid by its trading partners. It does not
capture any effects that Chinese exports might have in competing
with and lowering the prices of the exports of other countries. How
much our estimated contributions of China to import price
inflation, shown on Table 8a, may be understated is difficult to
say.
It is worth noting, however, that our estimate of China's
contribution to the United States' import price inflation, in
Section III, is not subject to this problem: the estimated
coefficients on the China shares would capture both direct effects
of Chinese exports and indirect effects working through the export
prices of other countries. Even so, the estimated effect, based on
the regression analysis of Section III, of China on U.S. import
inflation-about -0.8 percentage point annually-is actually somewhat
smaller than the effect on U.S. inflation measured using the ITCS
data-about 1 percentage point. This suggests that the downward bias
resulting from the omission of third-country competition effects
may not be too great.
As a check on the robustness of our regression results from
Section III, which were based on U.S. BLS data, we re-estimated
equation (17) using the data on import inflation and China trade
shares for the United States contained in the ITCS database. Table
9 displays the results of
this regression.35 The
results are broadly similar to those for the regressions based on
U.S. BLS data, shown in Table 4: a negative and significant
coefficient on the change in China shares (albeit the magnitude of
the coefficient is smaller) and a positive and insignificant
coefficient on the level of the China share. Multiplying the
average annual change in the China share between 1993 and 2001 (0.6
percentage points) by its coefficient, this implies a reduction in
overall U.S. import inflation of 0.1 percentage points annually.
This is smaller than both the -0.8 percentage point impact derived
from the regression in Section III and the -1 percentage point
estimate from the decomposition exercise in Section V.2, although
still in the same general ballpark. These results reinforce our
assessment that the effect of Chinese competition in lowering the
prices of goods imported from other countries probably has not been
very large.
Anderson, Jonathan (2002), "Five Great Myths About China and the
World," GS Global Economics Website,.
Becker, Elizabeth and Edmund L. Andrews (2003), "Currency of
China is Emerging as Tough Business Issue," New York Times, August 25.
Campa, Jose and Linda S. Goldberg (1997), "The Evolving External
Orientation of Manufacturing: A Profile of Four Countries," FRBNY Economic Policy Review, July.
Chan-Lau Jorge A. and Stephen Tokarick (1999), "Why Has
Inflation in the United States Remained So Low? Reassessing the Importance of Labor Costs and
the Price of Imports," International Monetary Fund Working Paper 99/149, November.
Clark, H., Higgin, M., and K. Yi (2003), `The Chinese Juggernaut: How Has it Affected the
World Economy?' presentation at Federal Reserve Bank of New York, March 17.
Cox, W. Micheal, and Jahyeong Koo (2003), ``China: Awakening
Giant,'' Federal Reserve Bank of Dallas, Southwest Economy, September/October.
Day, Phillip (2003), "China's Trade Lifts Neighbors,"
The Wall Street Journal, August 18.
Economic Analytical Unit (2003), ``China's Industrial Rise: East
Asia's Challenge,'' Department of Foreign Affairs and Trade, Australian Government.
Fels, Joachim (2003), "The China Syndrome," Morgan Stanley Global Economic Forum, February 8.
Gamber, Edward N. and Juann H. Hung (2001), "Has the Rise in
Globalization Reduced U.S. Inflation in the 1990s?" Economic Inquiry, Vol. 39, No. 1, 58-73.
Hanke, Steve H. (2003), "John Snow is Wrong about China Exporting Deflation," Cato Institute
Daily Commentary,., October 3.
Hogan, Vincent (1998), "Explaining the Recent Behavior of
Inflation and Unemployment in the United States," International Monetary Fund Working Paper 98/145, September.
Hu, Angang (2003), "Is China the Root Cause of Global
Deflation?" China and the World Economy, No. 3, November.
Ihrig, Jane and Jaime Marquez (2003), "An Empirical Analysis of
Inflation in OECD Countries" Board of Governors of the Federal Reserve System, International Finance Discussion
Paper No. 765, May.
International Monetary Fund (2003), "Deflation: Determinants, Risks, and Policy Options - Findings of an Interdepartmental Task Force", Washington, D.C., April.
Jenkins, Paul (2003), "Canada and the Global Economy: Trends in Asia and Elsewhere," speech to Association of Professional Economists of British Columbia, Victoria, British Columbia, April 3,
Kilman, Scott (2003), ``U.S. Crop Prices Soar As China Fuels
Demand,''The Wall Street Journal, November 13.
Kynge, James and Dan Roberts (2003), "Cut-throat Competitors," Financial Times, FT.com, February 4.
Kuroda, Haruhiko and Masahiro Kawai (2002), ``Time for a Switch to Global Reflation,''Financial Times, FT.com, December 1.
Lardy, Nicholas (2003), ``United States-China Ties: Reassessing the Economic Relationship,'' Testimony before the House Committee on International Relations, October 21.
Larhart, Justin (2003), "The China Syndrome," CNNmoney,
money.cnn.com, May 30.
Leggett, Karby and Peter Wonacott (2002), ``Surge in Exports
From China Gives a Jolt to Global Industry,''The Wall Street Journal, October 10.
Morrison, Kevin and Christopher Swann (2003), ``Raw Material
Prices Fuel New Inflation Fears,''Financial Times, October 27.
Noland, Marcus and Adam Posen (2002), ``The Scapegoats for
Japanese Deflation,''Financial Times, December 5.
Revenga, Ana L. (1992), ``Exporting Jobs? The Impact of Import
Competition on Employment and Wages in U.S. Manufacturing,'' Quarterly Journal of Economics, Vol. 107, No.
1, 255-284.
Roach, Stephen (2002a), "The China Factor," Morgan Stanley Global Economic Forum, October 14.
Roach, Stephen (2002b), "Stop Bashing China," Morgan Stanley Global Economic Forum, December 13.
Swagel, Phillip (1995), "Import Prices and the Competing Goods Effect," Board of Governors of
the Federal Reserve System, International Finance Discussion Paper No. 508, April.
Taylor, John B. (2003), "China's Exchange Rate Regime and its Effects on the U.S. Economy,"
Testimony before the House Committee on Financial Services, October 1.
Testa, William (2003), "Midwest Manufacturing and Trade with
China," Federal Reserve Bank of Chicago, Chicago Fed Letter, November.
Tootell, Geoffrey M.B. (1998), "Globalization and U.S. Inflation," Federal Reserve Bank of Boston,
New England Economic Review, July/August.
U.S. International Trade Commission (2003), ``Shifts in U.S. Merchandise Trade 2002,''Washington, D.C., July.
Valleta, Rob (2003), "Is Our IT Manufacturing Edge Drifting Overseas?" Federal Reserve Bank of San Francisco
Economic Letter, October 10.
Wolf, Martin (2003), ``The world must learn to live with a wide-awake China,'' Financial Times, November 12.
World Bank (2002), "China is Becoming the World's Manufacturing Powerhouse," Transition Newsletter.
Yam, Denise (2002), "China: Exporting More Deflation," Morgan Stanley Global Economic Forum, September 16.
Young, Jeffrey (2003), ``China: Part of Japan's Solution, Not Problem,'' NikkoSalomonSmithBarney,Japan: Issues and
Prospects, February 20.
($ Billions)
(Percent of GDP)
Sources: IMF World Economic Outlook 2003, Haver, and CEIC.
*Compounded annual growth of year-average price level from 1993
to 2002.
** Difference between 2002 and 1993 import shares, divided by
9.
*** Weighted by share of each sector in total imports for
74-sector sample.
**** Includes sectors not covered in the 74-sector sample.
variable
(1)
(2)
(excluding gr. coffee)
(3)
(0.004)
(0.006)
(0.004)***
(0.422)**
(0.555)**
(0.384)**
(0.046)
(0.047)
(0.033)
(0.108)
(0.087)**
Standard errors in parenthesis. *, ** and *** indicate significance at the 10, 5 and 1 percent levels respectively.
1993-2001
All sectors (1)
Manufacturing (2)
1997-2001
All sectors (3)
Manufacturing (4 )
(0.001)***
(0.002)
(0.078)
(0.091)
(0.079)
(0.104)
(0.009)
(0.010)
(0.056)***
(0.005)
(0.166)***
(0.167)*
(0.165)*
(0.161)*
(0.196)
(0.199)
(0.043)
(0.020)
(0.016)*
(1.126)
(1.230)
Country
2001
Kamin-Marazzi-Schindler
IFS
KMS/IFS
Data are taken from IFS Yearbook, 2002 and IFS November 2003. * Data start in 1994; 1994=100 for our calculation and for IFS
** Data end in 2000.
Effect
** Data start in 1994.
*** Data end in 2000.
Categories where China's share is positive in 1993 and
2001
(Annual Average Percent Change)*
** Data start in 1994. *** Data end in 2000.
(0.064)***
(0.007)
Subscript i indicates a 5-digit SITC sector.
In China, producers solve the following problem:
Next, we assume labor supply depends on the real consumption wage:
Assume a supply shock in China
Recall the
goods market clearing condition in China:
Next, we solve for Chinese inflation by plugging equation 8
into equation 6:
Chart 1 (top left panel -- $ trillions)
Chart 1 (top right panel -- $ Billions)
Chart 1 bottom left panel ($ Billions)
Chart 1 (bottom right panel -- 4-quarter percent change)
Chart 2 (Merchandise Exports -- $ Billions)
Chart 3 : U.S. Price Indices: Annual
Inflation Rates (Year-average over preceding year-average)
Chart 4: U.S. Import Price Inflation by Locality of Origin (Year-average over preceding year-average)
Chart 5: (top panel) BLS Import Inflation by
Locality (Year-average over preceding year-average)
U.S. Import Inflation by Locality of Origin:
Manufactured Goods
Europe
U.S. Import Inflation by Locality of Origin:
Manufactured Goods
Industrialized Countries
Other countries
Canada
Year
U.S. Import Inflation by Locality of Origin:
Non-Manufactured Goods
U.S. Import Inflation by Locality of Origin:
Non-Manufactured Goods
Industrialized Countries
Other Countries
Chart 6: U.S. Import Price
Inflation (Year-average over preceding year-average)
Chart 7: Import Price Inflation
1993-2002: Distribution by End-Use Category (Average percent change
in year-average price levels)
Chart 8: (top panel) BLS Import Prices vs.
China's Share of U.S. Imports (by End-Use Category 1993-2002) Inflation vs. Change in Shares
Chart 9: Annual Import Inflation
1993-1997 Vs. Annual Import Inflation 1997-2002
Chart 10: PPI vs. China's Share of
U.S. Imports (by SIC Category 1993-2001)
Chart 11: Shares of U.S. Imports
from Asia by Major Enduse Categories*
* 2003 projections are
based on growth of 2003 January-July trade over the year-ago
period.
**Asian LDCs are defined
as China, Hong Kong, Indonesia, Korea, Malaysia, Philippines,
Singapore, Taiwan, and Thailand.
***Total Asia is defined
as the nine Asian LDCs plus Japan.
Chart 12: Comparison of Calculated
Import Unit Values with IFS Import Unit Values -- See table 7.
1. Roach (2002a) refered to Asia as
``an exporter of deflation to the rest of the world. And China is
leading the way.'' See also Kuroda and Kawai (2002), World Bank
(2002), Yam (2002), Leggett and Wonacott (2002), Becker and Andrews
(2003), Kynge and Roberts (2003), and Lahart (2003), among
others. Return to text
2. See, among others, Anderson
(2002), Noland and Posen (2002), Clark, Higgins, and Yi (2003),
Fels (2003), Hanke (2003), Hu (2003), and Jenkins
(2003). Return to text
3. Roach (2002b), among others,
cites the low share of imports from China in U.S. GDP as a reason
why these imports are unlikely to impact the general price
level. Return to text
4. See, among other, Morrison and
Swann (2003) and Kilman (2003). Return to
text
5. While some research (IMF, 2003)
has looked into the impact of China's CPI inflation on foreign
inflation, it is generally understood that it is Chinese exports
and export prices that are most likely to be influencing foreign
prices. Anderson (2002) provides a broad-ranging and insightful
analysis of China's impact on foreign activity and prices, but does
not provide estimates of aggregate effects. Young (2003) takes a
general look at China's impact on prices in Japan, but does not
come up with estimates of the effect. Return to text
6. See Fels (2003) and Jenkins
(2003). Return to text
7. Various analysts have noted that
macroeconomic activity in China's trading partners could benefit
from improved terms of trade against China, particularly in sectors
that do not compete much with imports from China; see Fels (2003),
Jenkins (2003), Testa (2003), Wolf (2003), EAU (2003), and IMF
(2003). Return to text
8. A variant on this channel would
be a reduction in non-labor production costs, such as might arise
if imported intermediate goods from China were cheaper than those
produced domestically or imported from other
countries. Return to text
9. There is no consensus on the role
of import prices in the decline in U.S. inflation during the 1990s.
See, among others, Hogan (1998), Tootell (1998), Chan-Lau and
Tokarick (1999), Gamber and Hung (2001), and Ihrig and Marquez
(2003). Return to text
10. More formally, we express the
import price in end-use sector i, P , as a weighted average of the prices of imports
from China, P, and
from the rest of the world (excluding the United States)
P; the weights
are shares of U.S. imports from China and the rest of the
world.
P = ShareP + ShareP = ShareP + (1- ShareP
Totally differentiating and expressing in percent changes:
%P = %P(P/P
+ Share[%P(P/P - %P(P/P] Return to
text
11. These considerations imply that
in addition to the direct, arithmetic linkages between import
inflation %P and
the share variables Share and Share described in footnote 11, the share variables
may affect import inflation indirectly via their effect on prices
of goods imported from other countries, %P. Return to
text
12. An offsetting factor, however,
is that in cases where Chinese prices are falling more rapidly than
those of other exporters, this will by itself depress China's share
in the value of U.S. imports. Quantity shares would thus be more
useful here than value shares; unfortunately, data on U.S.
bilateral trade volumes are not available. Return to text
13. For the sake of robustness, the
SITC classification scheme was also employed. The results obtained
were essentially identical. Return to
text
14. One notable exception was in
computer trade (i.e. sector 21300). Despite a lapse in the price
data in 1994, we decided the computer sector was too important to
drop from our regressions. As a result, we have decided to treat
the computer sector (both import shares and prices) as starting in
1995 in all of our import price regressions. All variables used are
on an annualized basis. Thus, this problem will not affect our
results too much, as long as the relationship between computer
prices and imports did not change much between the 1993-1995 and
1995-2002 periods. Return to text
15. Because many Chinese exports to
the United States are exported first to Hong Kong and then
re-exported to the United States, it is likely that measured
Chinese exports, by themselves, under-estimate total Chinese
exports to the United States. Therefore, we also estimated the
regressions shown in Table 4 using the combined share of Chinese
and Hong Kong exports to the United States as the explanatory
variable. However, the regressions results remained essentially
unchanged. Return to text
16. Declines in import prices likely
weighed on consumer prices of goods where imports figured
prominently; however, the CPI and import prices are disaggregated
on very different bases, so it is difficult to compare sectoral
movements in consumer and import prices. Return to text
17. Estimates of the short-term
coefficient on import price inflation in Phillips curve equations
for the U.S. economy range from 0 (or insignificant) to somewhat
over 0.1, with several in the range of 0.04 - 0.07. See Hogan
(1998), Tootell (1998), Chan-Lau and Tokarick (1998), Gamber and
Hung (2001), and Ihrig and Marquez (2003). Return to text
18. Testa (2003) notes that "imports
can consist of intermediate components that become embodied in
domestic production of a final good. To the extent that such
components are most cheaply sourced overseas, they may keep
domestic production competitive for the final good in the domestic
market ..." Campa and Goldberg (1997) calculate that imported
inputs accounted for about 8 percent of the value of U.S.
manufacturing production in 1995. Return
to text
19. The use of the combined China +
Hong Kong share of U.S. imports instead of China alone did not
alter these results significantly. Return
to text
20. This analysis follows closely on
that described in Gamber and Hung (2001). Return to text
21. Our specification is based on
the premise that the greater the share of total imports in the
domestic market for a good, the greater will be the impact of
import prices on domestic producer prices of that good; with the
share of Chinese imports in total imports having been shown, in
Section III, to affect overall import prices, we thus interact it
with the IPR as shown in equation (19). An alternative approach
would be to estimate the impact on producer prices of the
penetration of imports from China alone in domestic markets;
however, in separate regressions (not shown) we found that neither
this share-(imports from China)/(domestic shipments + imports -
exports)-nor its rate of change was significant in equations for
sectoral producer price inflation. Return
to text
22. Prior findings on the effects of
overall imports and import prices on producer prices have been
mixed. Gamber and Hung (2001) find significant and sizeable effects
of import prices on producer prices, whereas Swagel (1995)
generally does not. Revenga (1992) finds significant effects of
import prices on wage rates. Return to
text
23. See Leggett and Wonacott (2002)
and Becker and Andrews (2003). Return to
text
24. Anderson (2002) argues that
China's deflationary effect on foreign producer prices is limited
to the labor-intensive light manufacturing in which China has the
greatest comparative advantage; even in this area, he adds, the
impact on foreign prices has been relatively small. Focusing on
high-tech products, Valletta (2003) notes "at this time, China's IT
sector focuses primarily on assembly of less-advanced products at
low cost, which does not threaten the U.S. dominance in
leading-edge technology and innovative products." Return to text
25. Testa (2003) notes that
notwithstanding its low share in the total U.S. market, "China has
become a dominant player in individual product categories,
especially those that are very labor intensive. In particular, our
estimates suggest a Chinese market share for the U.S. of over
one-half for certain categories of dolls and stuffed toys, fur and
leather apparel, and women's handbags." Cox and Koo (2003) also
document China's prominence in selected import
categories. Return to text
26. See, among others, Anderson
(2002), Lardy (2003), Taylor (2003), Day (2003), and U.S.
International Trade Commission (2003). Return to text
27. The number of categories
reported varies from country to country, as does the date range.
Thus, results for some countries do not cover the same date range,
and other countries had to be dropped due to insufficient
data. Return to text
28. The indices are largely robust
to the thresholds chosen so long as the upper and lower thresholds
are moved symmetrically and until there arise extreme values, where
the inclusion or exclusion of a single observation can make a large
difference in the overall value of the index. The upper threshold
eliminated on the order of 200 categories per country and the lower
threshold about 230, though both numbers varied considerably across
countries. Return to text
29. We believe that such large
changes are most likely reflective of errors in the data rather
than actual large price swings, and because some of the those
observations had a large influence on the calculation of the China
effect, it was necessary to find an objective way of deleting them.
We intentionally erred on the side of eliminating too many rather
than too few observations to ensure that whatever remained was
predominantly error free. Return to
text
30. In addition to calculating price
indices using Laspayres indices, we recalculated the indices using
Paasche indices. The results were broadly similar after accounting
for the known downward bias in Paasche indices. Return to text
31. The reasons our calculations
might not agree with the numbers reported in IFS include: (1) some
countries report import price indices in IFS as opposed to import
unit value indices, (2) the method used to calculated the indices
used in IFS vary from country to country and include Laspeyres,
Paasche, and Fischer formulas, and (3) some countries may have
changed the way they calculate the indices over time. Return to text
32. In practice, we sometimes used a
variant of this equation to decompose the growth rates of import
unit values between time t-n (1993) and t (2001):
[(P
- P
/P]
[(P
- P
/P]]
Unlike equation (21), this formulation permits us to calculate
China's contribution to import unit value growth when it has not
exported anything in the first period, and hence %P is undefined. Return to text
33. All of the annual averages were
calculated by dividing the overall effect found for the period by
the length of the sample (eight years in most cases, but seven
years for Korea, Poland, and Sweden). The mathematically correct
formula involves raising the growth in unit values to the 1/8th
power, but this simple average maintains the additivity of the
results, and hence the ability to break down the overall effect and
the China effect into their components. Using the mathematically
correct way of calculating the average would make them slightly
smaller. Return to text
34. Calculation of the China price
effect and China share effect is slightly more complicated when
China's share is zero in either 1993 or 2001. In those cases, the
China price effect is zero, because no unit-value change can be
calculated. If China's share is positive in either period, however,
the China share effect can be calculated using the following
formula:
,
which comes from the derivation of (21) and was mentioned
earlier in footnote 33. In addition to the calculations shown in
Table 8a, we redid the analysis using only those categories of
goods for which China's share was positive in both 1993 and 2001,
thus obviating the need to use this alternate formula to calculate
the China share effect. The results from that analysis were broadly
similar and are shown in Table 8b. Return
to text
35. We have not included a lagged
dependent variable, as the 1997 data we pulled for this purpose
resulted in a negative and improbably precise coefficient on this
term. Return to text
This version is optimized for use by screen readers.
A printable pdf version is available. | http://www.federalreserve.gov/pubs/ifdp/2004/791/ifdp791.htm | CC-MAIN-2016-36 | refinedweb | 13,122 | 50.77 |
I. […]
I cant find a way to save the checkbox state when using a Cursor adapter. Everything else works fine but if i click on a checkbox it is repeated when it is recycled. Ive seen examples using array adapters but because of my lack of experience im finding it hard to translate it into using […]
I have a listView with about 20 items (dynamic items). I want to animate these items first they show up to user. something like Google+ cards. There are some points that I want to achieve: items animate only when the user starts to see them. items animate only once. (not every time user sees them) […]
I want to do a very simple thing. I have a listview in my application which I dynamically add text to. But, after a certain point, I would like to change the color of the text inside the listview. So, I made a XML defining my custom list item, and subclassed the ArrayAdapter. But, whenever […]
For each list view with difference row layout template, I must create each custom adapter, which do the same thing: load xml row layout, get control (TextView, ImageView, etc..) by id, display data… something like this: public class CommentAdapter extends BaseAdapter { protected Activity activity; protected static LayoutInflater layoutInflater = null; protected List<Comment> lst; public […]
I’m trying to implement an UIAutomator testcase with a general method to perform a click on a ListView item (regardless of the type of viewgroup holding the listitem). Currently I have following code, but it keeps on clicking the first item. public void clickListViewItem(int index) throws UiObjectNotFoundException { UiObject listview = new UiObject(new UiSelector().className(“android.widget.ListView”)); if(index […]
Are the views that get scrolled off of ScrollView automatically cached by the drawing cache? I’m not quite sure i understand the API documentation.
I am using a couple of ListView elements in my app. In all cases, it doesn’t highlight the selected item when I click/touch it, but I can use the trackball to scroll up and down, and can see the orange highlighted color then. How do I fix this? For e.g., one of them is a […]
I have a problem with changing the background of a view in a ListView. What I need: Change the background image of a row onClick() What actually happens: The background gets changed (selected) after pressing e.g. the first entry. But after scrolling down the 8th entry is selected too. Scroll back to the top the […]
I use section adapter for the whole listview.Now in this image,there is a edittext which is not editable.I want to make this edittext editable. | http://babe.ilandroid.com/android/listview/page/10 | CC-MAIN-2018-26 | refinedweb | 447 | 72.26 |
Hi, i am replying to a thread called "Data.List permutations" on ghc- users and a thread called "powerSet = filterM (const [True, False]) ... is this obfuscated haskell?" on haskell cafe. On 04.08.2009, at 19:48, Slavomir Kaslev wrote: > A friend mine, new to functional programming, was entertaining > himself by > writing different combinatorial algorithms in Haskell. He asked me > for some > help so I sent him my quick and dirty solutions for generating > variations and > permutations: On the haskell cafe thread it was observed that you can implement the permutations function in a non-deterministic favour. The ideas behind these implementations closely resemble implementations of corresponding functions in Curry. We can generalise your implementation to an arbitrary MonadPlus. The idea is that the MonadPlus represents non-determinism. `inter` non- deterministically inserts an element to every possible position of its argument list. inter x [] = [[x]] >> inter x yys@(y:ys) = [x:yys] ++ map (y:) (inter x ys) interM :: MonadPlus m => a -> [a] -> m [a] interM x [] = return [x] interM x yys@(y:ys) = return (x:yys) `mplus` liftM (y:) (interM x ys) >> perm [] = [[]] >> perm (x:xs) = concatMap (inter x) (perm xs) permM :: MonadPlus m => [a] -> m [a] permM [] = return [] permM (x:xs) = interM x =<< permM xs Alternatively we can implement permM by means of foldM. permM :: MonadPlus m => [a] -> m [a] permM = foldM (flip interM) [] A standard example for the use of non-determinism in Curry is a perm function that looks very similar to `permM` with the slight difference that you do not need the monad in Curry. An alternative to this definition is to define a monadic version of insertion sort. First we define a monadic equivalent of the `insertBy` function as follows: -- insertBy :: (a -> a -> Bool) -> a -> [a] -> [a] -- insertBy _ x [] = [x] -- insertBy le x (y:ys) =-- if le x y-- then x:y:ys -- else y:insertBy le x ys insertByM :: MonadPlus m => (a -> a -> m Bool) -> a -> [a] -> m [a] insertByM _ x [] = return [x] insertByM le x (y:ys) = do b <- le x y if b then return (x:y:ys) else liftM (y:) (insertByM le x ys) Note that this function is very similar to interM, that is, we have interM = insertByM (\_ _ -> return False `mplus` return True) On basis of `insertBy` we can define insertion sort. -- sortBy :: (a -> a -> Bool) -> [a] -> [a] -- sortBy le = foldr (insertBy le) [] In the same manner we can define a function `sortByM` by means of `insertByM`. sortByM :: MonadPlus m => (a -> a -> m Bool) -> [a] -> m [a] sortByM le = foldM (flip (insertByM le)) [] Now we can define a function that enumerates all permutations by means of `sortByM`. permM :: MonadPlus m => [a] -> m [a] permM = sortByM (\_ _ -> return False `mplus` return True) Interestingly we can also define permM by means of monadic counterparts of other sorting algorithms like mergeSort. Although there were some arguments on haskell cafe that this would not work for other sorting algorithms it looks like this is not the case. At least the corresponding implementation of perm by means of mergeSort in Curry works well for lists that I can test in reasonable time. Cheers, Jan | http://www.haskell.org/pipermail/haskell-cafe/2009-August/064911.html | CC-MAIN-2014-23 | refinedweb | 524 | 53.14 |
need to sort by domain before submitting to MTA
Bug Description..
[http://
that should be recips not r.sort fyi
I have been using this patch for recent years to solve the problem against distribution. This speeds up delivery when using sendmail as the MTA significantly.
SMTPDirect.py
def domsort(uida, uidb):
## sort by domain
## usage foo.sort(domsort)
i = uida.rfind('@')
if i >= 0:
doma = uida[i+1:]
i = uidb.rfind('@')
if i >= 0:
domb = uidb[i+1:]
return cmp(doma, domb)
}
# Need to sort by domain name. if we split to chunks it
is possible
# some well-known domains will be interspersed as we sort by
# userid by default instead of by domain. (jared mauch)
r.sort(domsort) | https://bugs.launchpad.net/mailman/+bug/266119 | CC-MAIN-2015-22 | refinedweb | 120 | 69.28 |
A relaxed chat room about all things Scala (2 & 3 both). Beginner questions welcome. applies
Hi, I've noticed that getting the name of method parameters seems to have changed between 2.13.4 and 2.13.5.
When I have a method
def listCars(`airport-code`: String): Seq[String] = ???
and try to get the names via
classOf[RentalStation].getMethod("listCars", classOf[String]).getParameters.map(_.getName)
Previously it returned "airport-code" for the parameter and now it seems to return "airport$minuscode". My guess is the internal representation has changed and therefore the java reflection no longer works as expected. Is there any other way to solve this than a bandaid-solution using
.replaceAll() ?
(This is not my code, so please don't explain to me that reflection is bad, I know that. I'm just trying to upgrade this very commonly used library)
2.12.13
com.vividsolutions.jts.geom.Geometry. But now, in my updated code, it’s called
org.locationtech.jts.geom.Geometry. Thus it fails to find an
Encoder[Geometry]. I was wondering if I could somehow tell the JVM that the first one is actually at the second one.
hello! In scala 2 I could have a type class to prove that another type class instance cannot exist:
sealed trait Negative[A] object Negative { implicit def negative[T](implicit t: T): Negative[T] = new Negative[T] {} @implicitAmbiguous("Cannot negate ${T}") implicit def positive[T]: Negative[T] = new Negative[T] {} }
What's the canonical way of achieving this in Scala 3?
dbg!, not exactly. You can get something close by building it with
scala> @implicitNotFound("oops, it's a subtype!") type <:!<[A,B] = NotGiven[A <:< B] // defined alias type <:!<[A, B] = util.NotGiven[A <:< B] scala> summon[String <:!< Int] val res2: util.NotGiven[Nothing] = scala.util.NotGiven@10c23a76 scala> summon[String <:!< Object] 1 |summon[String <:!< Object] | ^ | oops, it's a subtype!
foo ${A} bardoesn't work on type aliases, hm. | https://gitter.im/scala/scala?at=60ac13f578e1d6477d62037e | CC-MAIN-2021-39 | refinedweb | 325 | 51.75 |
Sometimes we have to serialize objects, e.g. to send them over a network, store and restore them locally or for any other reason. Now it can be useful if we would know after the deserializing process, if the object has been restored correctly. Especially if you have objects which have internal states or if you must manage multiple instances of a class. A possible solution to this problem is using the
System.Guid struct to identify the objects. But in this way, you cannot be sure that the internal states, etc. were deserialized correctly (see Background for explanation).
A commonly used technique in the Internet is to provide a MD5 - Hash String so the receiver can compare if the file has been transmitted without any modifications.
The .NET Framework gives us a struct to uniquely identify our objects, the
System.Guid struct in the mscorlib.dll. This struct can be used to give each class its own identifier. And that's the crux of the matter. What we need is not an identifier for the class, we need an identifier for each instance of the class. Implicitly this identifier must also represent some internal values like state. Otherwise our recipient of the object cannot be sure, that he has received / deserialized the same object. Also our recipient cannot "create" a GUID on his own. Once it is created by the sender, it is not reproducible.
We must also provide a functionality, which can be executed by both, sender and recipient, to identify an object. This identifier must also implicit regard on the fields which are relevant for this object. And these relevant fields can be different for each class!
The idea I had was to use MD5 hashes for that. Each object has a built-in function called
.GetHashCode(). This method returns an
Integer, although according to the name of the method, you would expect a
string. That's because these
HashValues are intended to be used as Keys in e.g. a
HashTable.
But fortunately, there exists a class named
MD5CryptoServiceProvider in the
System.Security.Cryptography namespace. Unfortunately, this class is not easy to use. The main problem for most programmers could be that the class only accepts a byte-array as input and not a reference to an object. So I decided to wrap all the needed functionality into a generator class. This class could then generate the Hash for me, and I have to write just one line of code.
The codefile above contains a class called
MD5HashGenerator. This class has a
static method
.generateKey(Object sourceObject), which does the "magic" for you. Include the class into your project, and use it as follows:
To use the class (as a publisher), you have to do the following things:
Serializable(). Mark all variables which should not be serialized as
NonSerializable().
staticmethod
MD5HashGenerator.generateKey(Object sourceObject). You get the MD5 - Hash for the object as a
String.
If you are the receiver, then:
staticmethod
MD5HashGenerator.generateKey(Object sourceObject)on the deserialized object.
We want to serialize a class which has a
string, an
int and a
DateTime. The
dateTime member is set at creation time, so it is different for each instance of the class. As mentioned above, the class must be tagged as serializable. It (could) look like this:
using System; using System.Runtime.Serialization; [Serializable] public class SimpleClass { private string justAString; private int justAnInt; private DateTime justATime; /// <summary> /// Default Constructor. The fields are filled with some standard values. /// </summary> public SimpleClass() { justAString = "Some useless text"; justAnInt = 345678912; justATime = DateTime.Now; } }
Because we use the system method
DateTime.Now to initialize the field
justATime, each instance of the class should be different. It is important to "mark" the class as
Serializable, because this is asked by the
MD5HashGenerator-class.
The generator class uses the
BinaryFormatter for serialization, so all fields (whether they are
private or not are automatically included in the serialization process). But exclude handles and pointers, if you are using them. See [1] for details.
The class which "publishes" the object must then do the following things:
... SimpleObject simpleObject = new SimpleObject(); string simpleObjectHash = MD5HashGenerator.generateKey(simpleObject); //Now serialize the simpleObject e.g. with a XmlSerializer and //store the hash somewhere ...
Now the "consumer" can deserialize the
SimpleObject and also call
MD5HashGenerator.generateKey(simpleObject) on the deserialized object. He can then compare the hashstrings and decide if it's the same object.
The code of the
MD5HashGenerator.generateKey(Object SourceObject) method looks like this:
public static String GenerateKey(Object sourceObject) { String hashString; //Catch unuseful parameter values if (sourceObject == null) { throw new ArgumentNullException("Null as parameter is not allowed"); } else { //We determine if the passed object is really serializable. try { //Now we begin to do the real work. hashString = ComputeHash(ObjectToByteArray(sourceObject)); return hashString; } catch (AmbiguousMatchException ame) { throw new ApplicationException("Could not definitely decide if object is serializable. Message:"+ame.Message); } } }
Let's have a deeper look at the following line of code:
hashString = ComputeHash(ObjectToByteArray(sourceObject));
As mentioned above I used the
MD5CryptoServiceProvider class to generate the
Hashstring. I encapsulated the use of the method in the
ComputeHash(byte[] objectAsBytes) method. Here's the implementation:
private static string ComputeHash(byte[] objectAsBytes) { MD5 md5 = new MD5CryptoServiceProvider(); try { byte[] result = md5.ComputeHash(objectAsBytes); //(); } catch (ArgumentNullException ane) { //If something occurred during serialization, //this method is called with a null argument. Console.WriteLine("Hash has not been generated."); return null; }
As you can see, the
MD5CryptoServiceProvider class wants a
byte array as input. It does not accept an object directly. What you get out of it is not a
string as we would like to have, but a
byte array. Therefore I added the conversion from
byte array to Hex. The conversion is done by using the
Byte.ToString() method. The method accepts a formatstring as input. And "
X2" here means that each byte is converted into a two-char-string-sequence (e.g. 01011100 => 5C or 00000111 => 07).
Now there is still the question as to how to convert an object into a
byte array. We know that our object is serializable. So we can serialize it into the memory (using a
MemoryStream and a
BinaryFormatter) and getting out of the memory the needed
byte array. Because the whole thing should be thread-safe, we lock the
Serialization of the object.
private static readonly Object locker = new Object(); private static byte[] ObjectToByteArray(Object objectToSerialize) { MemoryStream fs = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); try { //Here's the core functionality! One Line! //To be thread-safe we lock the object lock (locker) { formatter.Serialize(fs, objectToSerialize); } return fs.ToArray(); } catch (SerializationException se) { Console.WriteLine("Error occurred during serialization. Message: " + se.Message); return null; } finally { fs.Close(); } }
Generating MD5-hashes can be useful, if you must have a procedure both sides can execute to ensure the uniqueness and changeless serialization / deserialization of objects. The most difficult part for me was to convert an object into a
byte array and the conversion of a
byte array to an Hex -
String. Using Guids is also a possibility. But the Guid is created when the object is initialized and the consumer cannot "recreate" the Guid to ensure that no changes on the object were done. He just knows that he has received the same object the producer has created.
What I didn't do is all the security issues. Using only MD5 Hashes is not reliable enough. If you need strong security, provide RSA - encrypted channels or other encryption methods.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/MD5_hash_generation.aspx | crawl-002 | refinedweb | 1,252 | 50.23 |
My wife and I are currently planning on moving from London, England, to Sweden. To that effect, much of the contents of our home is already in storage, and most of this is books. We sent 86 tea chests full of books to the warehouse, and we still have plenty more to go.
Many people really like our books, many people like to borrow them, and for many reasons it would be quite cool to be able to put the details of books we have into an RSS feed. When we unpack the books, we will most likely scan their barcodes and order our library (we're geeky like that), so we will have all sorts of data available.
So, the challenge is to design an RSS module for both 1.0 and 2.0 that can deal with books.
The first thing to think about is precisely what knowledge we already have about the thing we are trying to describe. With books, we know a great deal:
The title
The author
The publisher
The ISBN number
The subject
The date of publication
The content itself
There are also, alas, things that we might think we know, but which we in fact do not. In the case of books, unless we are dealing with a specific edition in a specific place at a specific time, we do not know the number of pages, the price, the printer, the paper quality, or how critics received it. We might think we doafter all, I bought most of these books, and I can touch them and pick them upbut for the sake of sharable data these are not universally useful values. They will change with time and are not internationally sharable. Remember that once it has left your machine, the data you createin this case each item is lost to you. As the first author, it is your responsibility to create it in such a way that it retains its value for as long as possible with as wide an audience as possible.
So, rule 1 of module design is: decide what data you know , and what data you do not know .
Rule 2 of module design is: if possible , use another module's element to deliver the same information .
This is another key point. It is much less work to leverage the efforts of others, and when many people have spent time introducing Dublin Core support to desktop readers, for example, we should reward them by using Dublin Core as much as possible. Module elements need to be created only if there is no suitable alternative already in the wild.
So, to reexamine our data:
Titles can be written within the core title element of either 1.0 or 2.0, or within the dc:title element of the Dublin Core module. One should always strive to use the core namespace first, so title it is.
Here we have the first core split between 1.0 and 2.0. In 2.0, we can use the core author element. There is no such thing in 1.0, so we are forced to use the dc:creator element of Dublin Core. Because one should always strive to use the core namespace first, RSS 2.0 users should use author . But because we want to have as simple a module specification as possible, we might like to use the same element in both module versions. One way of doing this would be to import the RSS 2.0 namespace into the 1.0 feed and use author in both. However, this cannot be done. RSS 2.0's root namespace is "". We can't import that, as we don't have a namespace URI to point to. We could possibly use the URL of the 2.0 specification document as the URI, declare xmlns:rss2=" ", and then use rss2:author , but because the URI is different, technically this does not refer to the same vocabulary as the one used in RSS 2.0. As we will see, using the same elementeven if it is in a slightly different syntaxis very useful indeed for the authors of RSS applications. So, for the sake of simplicity, I'm opting for dc:creator . We also have the option of using dc: contributor to denote a contributor.
Publishers are lovely people and happily have their very own Dublin Core element, dc:publisher .
ISBN numbers are fantastically useful here. Because the ISBN governing body ensures that each ISBN number is unique to its book, this can serve as a globally unique identifier. What's more, we can even turn an ISBN into a URI by using the format urn:isbn:0123456789. For RSS 1.0, this will prove remarkably useful, as we will discuss in a moment. Meanwhile, denoting the ISBN is a good idea. Let's invent a new element. Choosing book as the namespace prefix, let's call it book:isbn .
A book's subject can be a matter of debate especially with fiction so it may not be entirely sane to make this element mandatory or to trust it. Nevertheless, we do have ways of writing it. RSS 2.0's core element category may help here, as would dc:subject , especially when used with RSS 1.0 mod_taxonomy .
All of these schemes, however, rely on being able to place the subject within a greater hierarchy. Fortunately, library scientists are hard at work on this, and there are many to choose from. For our purposes, we will use the Open Directory hierarchyjust to provide continuity throughout this book.
Again, here we have a clash between the extended core of RSS 2.0 and RSS 1.0's use of Dublin Core. Within RSS 2.0 we have pubDate available, and within RSS 1.0 we rely on dc:date . Given that Dublin Core is more widely recognized within the RDF world and perfectly valid within the RSS 2.0 world, it saves time and effort to standardize on it. This is a good example of rule 3: as you cannot tell people what they can't do with your data , you must make it easy for them to do what they want .
We have the content itself. The core description does not work here we're talking about the content, not a pr cis of it, and we certainly do not want to include all of the content, so content:encoded is out too. We really need an element to contain an excerpt of the book, the opening paragraph, for example.
Hurrah! We can invent a new element! Let's call it book:openingPara .
So, out of all the information we want to include, we need to invent only two new elements: book:isbn and book:openingPara . This is not a bad thing: modules do not just consist of masses of new elements slung out into the public. They should also include guidance as to the proper usage of existing modules in the new context. Reuse and recycle as much as possible.
To summarize, we now have:
<title/> <dc:author/> <dc:publisher/> <book:isbn/> <dc:subject/> <dc:date/> <book:openingPara/>
Before creating the feed item , we need to decide on what the link will point to. Given that my book collection is not web-addressable in that way, I'm going to point people to the relevant page on Fleishman's book-price comparison site.
For an RSS 2.0 item, we can therefore use Example 11-1.
<item> >
As you can see in this simple strand of RSS 2.0, the inclusion of book metadata is easy. We know all about the book, and a mod_Book -compatible reader can allow us to read the first paragraph and, if it appeals, to click on the link and buy it. All is good.
With RSS 1.0, we must make a few changes. First, we need to assign the book a URI for the rdf:about attribute of item . This is not as straightforward as you might think. We need to think about precisely what we are describing. In this case, the choice is between a specific bookthe one that is sitting on my desk right nowand the concept of that book, of which my specific book is one example.
The URI determines this. If I make the URI catalogue /0765304368, then the item refers to my own copy: one discreet object.
If, however, I make the URI urn:isbn:0765304368, then the item refers to the general concept of Cory Doctorow's book. For our purposes here, this is the one to go for. If I were producing an RSS feed for a lending library, it might be different. Example 11-2 makes these changes to mod_Book in RSS 1.0.
<item rdf: >
The second thing to think about is the preference for all the element values within RSS 1.0 to be rdf:resource s and not literal strings. To this end, we need to assign URIs to each of the values we can. It is possible within RSS 1.0 to keep extending all the information you have to greater and greater detail. At this point, you must think about your audience. If you foresee people using the feed for only the simplest of taskssuch as displaying the list in a reader or on a sitethen you can stop now. If you foresee people using the data in deeper, more interesting applications, then you need to give guidance as to how far each element should be extended.
For the purposes of this chapter, we need to go no further, but for an example we will anyway. Example 11-3 expands the dc:author element via RDF and the use of a new RDF vocabularyFOAF, or Friend of a Friend (see).
<?xml version="1.0"?> <rdf:RDF xmlns: <item rdf: <title>Down and Out in the Magic Kingdom</title> <link></link> <dc:author rdf: > <dc:author rdf: <foaf:Person> <foaf:name>Cory Doctorow</foaf:name> <foaf:title>Mr</foaf:title> <foaf:firstName>Cory</foaf:firstName> <foaf:surname>Doctorow</foaf:surname> <foaf:homepage rdf: <foaf:workPlaceHomepage rdf: </foaf:Person> </dc:author> </rdf:RDF>
Because only you, as the module designer, know the scope of the data you want to put across, you must document your module accordingly . Speaking of which . . .
You must document your module. It is obligatory . The place to do this is at the address you are using as the namespace URI. Without documentation, no one will know precisely what you mean, and no one will be able to support your module. Without support, the module is worthless on the wider stage. | https://flylib.com/books/en/1.115.1.54/1/ | CC-MAIN-2019-09 | refinedweb | 1,778 | 73.37 |
We’ll discuss:
Getting started with React
What is UNPKG, NPM, CDN?
Why use a module bundler? What is Rollup?
Importing libraries using ES6 module syntax
Using JSX (javaScript XML) for SVG graphics
Deriving graphics coordinates programmatically
For our face, here’s where we left off last time.
We used some CSS to make those scroll bars go away, and to set the margin to 0.
<style> body { margin: 0; overflow: hidden; } </style>
We used
<svg> to make the background
<circle>. This big yellow circle. And these two circles for the eyes.
<svg width="960" height="500"> <circle cx="480" cy="250" r="245" fill="yellow" stroke="black" stroke-</circle> <circle cx="350" cy="180" r="50"></circle> <circle cx="600" cy="180" r="50"></circle> </svg>
But I was feeling a little frustrated that we couldn’t use math to figure out these coordinates. But I noted down these thoughts of what math we would want to use for defining these various coordinates.
<!-- height / 2 - strokeWidth / 2 centerX - eyeOffsetX -->
Getting started with React
What I’m gonna do next is use React to define this DOM structure, and we’ll pretty much be able to copy-paste our HTML into JSX, which sort of lets you write HTML inside JavaScript, but it also lets you sort of inject math or arbitrary JavaScript expressions.
The next step here is to use the React library. And the way VizHub works with libraries is that we can just include the <script> tag on the page, and then write some JavaScript that imports from that library.
The way I like to figure out the path for libraries is to use unpkg. If I just type unpkg.com/react and hit Enter, it gives me the common JS build. But let me just poke around here and see if I can get the browser build. The UMD (Universal Module Definition.) build is what we need. I think I’ll use this one. React production.min that weighs 13 kilobytes.
If I click through to View Raw, then it gives me this URL which I can use in a
<script> tag in my program here. So in the
<head> is where I’m gonna load this. I’m gonna make a new script tag begin script
<script> end script
</script> and then the source
src attribute of this script tag will be that URL from unpkg.com.
<script src=""></script>
So now, we can access the React global by writing some JavaScript ourselves. Inside the
<script> tag, we can write some JavaScript like
console.log("Hello JavaScript!");
<script> console.log('Hello JavaScript!'); </script>
Now if I open the Developer tools with Ctrl+Shift + J, we see the output – Hello JavaScript.
What I really want to do is check that React is loading in here. And it should be a global variable called React in uppercase. So if I say
console.log(React), there it is. There’s all this stuff. All the exports of React in a single global.
What is UNPKG, NPM, CDN?
Let me just stop and explain what is unpkg is all about. Nowadays, npm – Node Package Manager is the de-facto place where JavaScript libraries are hosted. You can go to npmjs.com and search for all sorts of libraries like React or D3. Each package has its own page here. If you were using node.js, you would say npm i — or npm install d3. But if you’re working in the browser like we are, you would use a CDN – a Content Distribution Network. A Content Distribution Network, also called Content Delivery Network, is where instead of just a single server serving the files, it’s a bunch of servers that are close to the people consuming them. It’s pretty much an efficient way of getting the files to your browser.
Unpkg is an open source project that is a global content delivery network, or CDN. For everything on NPM, it has this URL scheme where you can specify a package, a version, and a file.
unpkg.com/:package@:version/:file
And they give this example of React.
unpkg.com/react@16.7.0/umd/react.production.min.js
So that was a little detour of what unpkg is, and why we’re using it.
Why use a module bundler? What is Rollup?
The next step is to get to a place where we can start to use JSX with React. For that, we need a module bundler, and Vizhub uses rollup internally. Rollup is this open source project that understands JavaScript modules. It can combine modules together into a single output file that’s typically called a bundle. There’s a plugin for this that understands JSX, and transpiles the JSX into JavaScript, which needs to be done in order to really use React.
To get this going, we need to just create a file called
index.js. To create a new file I’m going to click this little + over here in the bottom-left corner, and click new file, and then I’ll call it index.js and hit enter.
We can take our
console.log(React) out of here, and put it into the
index.js. Notice that
bundle.js got created automatically. It gets created automatically from the content of
index.js, and again this is using rollup internally. Now that we have
bundle.js, we can change our
<script> tag such that it just loads the content of bundle.js.
Importing libraries using ES6 module syntax
We can say
<script src=“bundle.js”></script>, and now that we’re using this module bundler we can actually say
import React from “react”; the package, using this syntax. So now if we take a look at the console, it’s printing out just the same as it was.
The next step here is to get that React boilerplate going, which I can never remember. So I’m just gonna Google for it. All right this is the React boilerplate, and I forgot we need ReactDOM as well. So I’m going to
import ReactDOM from ‘react-dom’. And to use that we need to include another <script> tag on our page. And to figure out the URL I’m gonna go back to unpkg and just type react-dom, and again we’re getting the wrong build. So if I just poke around here, I can find the right build for the browser. The UMD
react-dom-production.min.js is the one that we want. And if we click View Raw, we get this URL that we can then use in our page. So we can say
<script src=""></script> Now we should be able to say
console.log(reactDOM), and it should print out something. Ok great, that worked.
So now we can start using React for DOM manipulation. Now it’s all coming back to me. This is what the boilerplate looks like. We get a
rootElement where we say
document.getElementById(‘root’) and then we call
ReactDOM.render(<App />, rootElement); our app component into the root element. But first, we need this to be in place.
document.getElementById is going to look for an element on the
index.html page with this id of
root, which is not there yet. So let me just create that.
<div id=“root”></div>. So now we’ve got a div on the page that will come back for this query
document.getElementById(‘root’).
Using JSX (JavaScript XML) for SVG graphics
But now we need an app component, so let me just create that right now. It’s just going to be a function that returns some JSX, and this is what JSX looks like. I’ll say..
const App = () => ( <h1>Hello JSX</h1> )
All right, it worked!
If you’re new to JavaScript, there is a lot going on here.
const is a way of defining variables, so we’re defining App as a variable whose value is a function, and this syntax here is the arrow syntax for creating functions. And if the body of a function is in parenthesis, it’s the same thing as a traditional, curly braces function body, and then saying return this JSX.
const App = () => { return ( <h1>Hello JSX</h.
I’m going to start by putting the first of our circles into JSX.
If I delete this
<h1> and then paste that HTML, we get this useful error message – Unterminated JSX Contents. That means that we’re missing the closing
</svg> tag, so we can add it, and that error should go away. And in JSX, this circle needs to be a self-closing thing, so I can just put a slash before the closing tag – and that problem should go away.
And boom! We have our circle. But now it’s getting created from JSX, not just HTML.
Let me just fix the indentation there so now we can start doing things programmatically. I’m gonna start by extracting width and height into variables outside of this app. I’m going to just make some variables.
const width="960"
const height="500"
But since these are quoted, they’re gonna be strings and that’s not what we want. So I’m gonna just gonna remove these quotes around these things.
const width=960
const height=500
Now we can do math on these, and we won’t get confusing results. Now that these variables exist, we can use them in our JSX in place of these strings. So I’m going to delete that 960, and then in JSX we can use curly braces to sort of escape out into JavaScript so whatever I put inside of these curly braces, it can be any JavaScript. So I’m gonna do the same for height.
<svg width={width} height={height}>
And now we can define all these numbers in terms of width and height. What did we want cx to be? Let me go back to my comments and just bring those over here into our index.js.
In JavaScript, the comments look like this.
//
Deriving graphics coordinates programmatically
I had this notion that there should be a variable called
centerX, so let’s go ahead and define that.
const centerX= well to put in the center it needs to be
width/2. Now, instead of 480, I could say
cx={centerX}. Just like that, we can do the same for
cy.
centerY= height / 2 . And then we can set
cy to be
centerY.
cy={centerY}
And what should the radius be? I think that was this comment here –
r should be equal to this stuff –
height / 2 - strokeWidth / 2. We don’t have
strokeWidth defined, so let me just define that –
strokeWidth is going to be.. well it’s
10 down here, so let me remove that defined
strokeWidth to be
10 here.
const strokeWidth = 10. And then define the stroke-width attribute to be the value of the
strokeWidth variable.
strokeWidth={strokeWidth}
Okay so
height/2 is
centerY, so we can simplify the radius to be
CenterY - strokeWidth/2 and then I can just take this expression here and set that to be the value for
r.
Now things sort of magically cascade, so I could change the value of
strokeWidth to say
30, and notice how the circle still goes right exactly up to the edge. That’s because all of this is defined mathematically, programmatically. So far so good.
Now let’s make our eyes. I think I’ll change that back to 20. Going back to our
index.html, I’m gonna take just one of our eyes – I think it’s the left eye. I’m gonna paste that right here next to that first of our circles. And there’s our left eye. All right, so what is this
350? That’s the x-coordinate of our eye. And that’s what this thought was –
centerX - eyeOffsetX. So we should be able to say
cx={centerX - eyeOffsetX}. But we don’t have
eyeOffsetX defined, so I’m gonna go ahead and make a new variable, and set it to say 50.
const eyeOffsetX = 50; So now I’m going to take this idea and make it a reality.
The
cx of our left eye should be
centerX - offsetX.
cx={centerX - offsetX}
All right, see that?! Maybe we need a little more of an offset, let’s say 90.
const eyeOffsetX = 90
All right! now it’s moving around. Actually, I’m noticing, we could simplify this to just make it a self-closing circle tag there. So now let’s deal with
cy. This should be quite similar. I guess it should just be
cy={centerY - eyeOffsetY}, and we don’t have that variable quite yet, so let me just make a new variable
eyeOffsetY –
const eyeOffsetX = 90, and there we have it.
So let me just test if we increase this to say
110. Our eye moves up a little bit. Let’s keep it at say
100.
All right the last remaining thing is the radius of this eye, and I just want to make it so that we could control the radius of both eyes by setting one variable value. So I’m just gonna make this defined by a variable as well. I’ll call it
eyeRadius. And we can define
eyeRadius to be
50.
const eyeRadius = 50;
<circle cx={centerX - eyeOffsetX} cy={centerY - eyeOffsetY} r={eyeRadius} >
Okay, now we should be able to pretty elegantly create the other eye. So I’m going to copy-paste that, and the only difference should be, instead of subtracting
eyeOffsetX from
centerX, we should be adding it. So I’ll just change that minus to a plus, and boom! We’ve got two eyes!
<circle cx={centerX + eyeOffsetX} cy={centerY - eyeOffsetY} r={eyeRadius} >
And now if we want to make both eye smaller, we could just change the
eyeRadius and be done with it.
//filename: index.js import React from 'react'; import ReactDOM from 'react-dom'; const width = window.innerWidth; const height = window.innerHeight; const centerX = width / 2; const centerY = height / 2; const strokeWidth = 20; const eyeOffsetX = 90; const eyeOffsetY = 100; const eyeRadius = 40; const mouthWidth = 20; const mouthRadius = 140;} /> </g> </svg> ); const rootElement = document.getElementById('root'); ReactDOM.render(<App />, rootElement);
<!DOCTYPE html> <html> <head> <title>Smiley Face Part II</title> <style> body { margin: 0; overflow: hidden; } </style> <script src=""></script> <script src=""></script> </head> <body> <div id="root"></div> <script src="bundle.js"></script> </body> </html>
That’s all for Let’s Make a Face Part II. Stick around for the next episode, where we’re going to add the mouth of our face finally using D3. | https://datavis.tech/datavis-2020-episode-6-lets-make-a-face-part-ii-with-react/ | CC-MAIN-2020-45 | refinedweb | 2,462 | 83.66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.