class IPAddr
IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and IPv6 are supported.
Example¶ ↑
require 'ipaddr' ipaddr1 = IPAddr.new "3ffe:505:2::1" p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff> p ipaddr1.to_s #=> "3ffe:505:2::1" ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000> p ipaddr2.to_s #=> "3ffe:505:2::" ipaddr3 = IPAddr.new "<IP_ADDRESS>/24" p ipaddr3 #=> #<IPAddr: IPv4:<IP_ADDRESS>/<IP_ADDRESS>>
Constants
- IN4MASK
32 bit mask for IPv4
- IN6FORMAT
Format string for IPv6
- IN6MASK
128 bit mask for IPv6
- RE_IPV4ADDRLIKE
Regexp internally used for parsing IPv4 address.
- RE_IPV6ADDRLIKE_COMPRESSED
Regexp internally used for parsing IPv6 address.
- RE_IPV6ADDRLIKE_FULL
Regexp internally used for parsing IPv6 address.
Attributes
Returns the address family of this IP address.
Public Class Methods
Creates a new ipaddr object either from a human readable IP address representation in string, or from a packed #in_addr value followed by an address family.
In the former case, the following are the valid formats that will be recognized: “address”, “address/prefixlen” and “address/mask”, where IPv6 address may be enclosed in square brackets (`[' and `]'). If a prefixlen or a mask is specified, it returns a masked IP address. Although the address family is determined automatically from a specified string, you can specify one explicitly by the optional second argument.
Otherwise an IP address is generated from a packed #in_addr value and an address family.
The IPAddr class defines many methods and operators, and some of those, such as &, |, include? and ==, accept a string, or a packed #in_addr value instead of an IPAddr object.
# File lib/ipaddr.rb, line 470 def initialize(addr = '::', family = Socket::AF_UNSPEC) if !addr.kind_of?(String) case family when Socket::AF_INET, Socket::AF_INET6 set(addr.to_i, family) @mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK return when Socket::AF_UNSPEC raise AddressFamilyError, "address family must be specified" else raise AddressFamilyError, "unsupported address family: #{family}" end end prefix, prefixlen = addr.split('/') if prefix =~ /\A\[(.*)\]\z/i prefix = $1 family = Socket::AF_INET6 end # It seems AI_NUMERICHOST doesn't do the job. #Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil, # Socket::AI_NUMERICHOST) @addr = @family = nil if family == Socket::AF_UNSPEC || family == Socket::AF_INET @addr = in_addr(prefix) if @addr @family = Socket::AF_INET end end if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6) @addr = in6_addr(prefix) @family = Socket::AF_INET6 end if family != Socket::AF_UNSPEC && @family != family raise AddressFamilyError, "address family mismatch" end if prefixlen mask!(prefixlen) else @mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK end end
Creates a new ipaddr containing the given network byte ordered string form of an IP address.
# File lib/ipaddr.rb, line 105 def IPAddr::new_ntoh(addr) return IPAddr.new(IPAddr::ntop(addr)) end
Convert a network byte ordered string form of an IP address into human readable form.
# File lib/ipaddr.rb, line 111 def IPAddr::ntop(addr) case addr.size when 4 s = addr.unpack('C4').join('.') when 16 s = IN6FORMAT % addr.unpack('n8') else raise AddressFamilyError, "unsupported address family" end return s end
Public Instance Methods
Returns a new ipaddr built by bitwise AND.
# File lib/ipaddr.rb, line 124 def &(other) return self.clone.set(@addr & coerce_other(other).to_i) end
Returns a new ipaddr built by bitwise left shift.
# File lib/ipaddr.rb, line 139 def <<(num) return self.clone.set(addr_mask(@addr << num)) end
Compares the ipaddr with another.
# File lib/ipaddr.rb, line 338 def <=>(other) other = coerce_other(other) rescue nil else @addr <=> other.to_i if other.family == @family end
Returns true if two ipaddrs are equal.
# File lib/ipaddr.rb, line 149 def ==(other) other = coerce_other(other) rescue false else @family == other.family && @addr == other.to_i end
Returns a new ipaddr built by bitwise right-shift.
# File lib/ipaddr.rb, line 134 def >>(num) return self.clone.set(@addr >> num) end
Checks equality used by Hash.
# File lib/ipaddr.rb, line 348 def eql?(other) return self.class == other.class && self.hash == other.hash && self == other end
Returns a network byte ordered string form of the IP address.
# File lib/ipaddr.rb, line 238 def hton case @family when Socket::AF_INET return [@addr].pack('N') when Socket::AF_INET6 return (0..7).map { |i| (@addr >> (112 - 16 * i)) & 0xffff }.pack('n8') else raise AddressFamilyError, "unsupported address family" end end
Returns true if the given ipaddr is in the range.
e.g.:
require 'ipaddr' net1 = IPAddr.new("<IP_ADDRESS>/24") net2 = IPAddr.new("<IP_ADDRESS>") net3 = IPAddr.new("<IP_ADDRESS>") p net1.include?(net2) #=> true p net1.include?(net3) #=> false
# File lib/ipaddr.rb, line 172 def include?(other) other = coerce_other(other) if ipv4_mapped? if (@mask_addr >> 32) != 0xffffffffffffffffffffffff return false end mask_addr = (@mask_addr & IN4MASK) addr = (@addr & IN4MASK) family = Socket::AF_INET else mask_addr = @mask_addr addr = @addr family = @family end if other.ipv4_mapped? other_addr = (other.to_i & IN4MASK) other_family = Socket::AF_INET else other_addr = other.to_i other_family = other.family end if family != other_family return false end return ((addr & mask_addr) == (other_addr & mask_addr)) end
Returns a string containing a human-readable representation of the ipaddr. (“#<IPAddr: family:address/mask>”)
# File lib/ipaddr.rb, line 375 def inspect case @family when Socket::AF_INET af = "IPv4" when Socket::AF_INET6 af = "IPv6" else raise AddressFamilyError, "unsupported address family" end return sprintf("#<%s: %s:%s/%s>", self.class.name, af, _to_string(@addr), _to_string(@mask_addr)) end
Returns a string for DNS reverse lookup compatible with RFC3172.
# File lib/ipaddr.rb, line 317 def ip6_arpa if !ipv6? raise InvalidAddressError, "not an IPv6 address" end return _reverse + ".ip6.arpa" end
Returns a string for DNS reverse lookup compatible with RFC1886.
# File lib/ipaddr.rb, line 325 def ip6_int if !ipv6? raise InvalidAddressError, "not an IPv6 address" end return _reverse + ".ip6.int" end
Returns true if the ipaddr is an IPv4 address.
# File lib/ipaddr.rb, line 252 def ipv4? return @family == Socket::AF_INET end
Returns a new ipaddr built by converting the native IPv4 address into an IPv4-compatible IPv6 address.
# File lib/ipaddr.rb, line 286 def ipv4_compat if !ipv4? raise InvalidAddressError, "not an IPv4 address" end return self.clone.set(@addr, Socket::AF_INET6) end
Returns true if the ipaddr is an IPv4-compatible IPv6 address.
# File lib/ipaddr.rb, line 267 def ipv4_compat? if !ipv6? || (@addr >> 32) != 0 return false end a = (@addr & IN4MASK) return a != 0 && a != 1 end
Returns a new ipaddr built by converting the native IPv4 address into an IPv4-mapped IPv6 address.
# File lib/ipaddr.rb, line 277 def ipv4_mapped if !ipv4? raise InvalidAddressError, "not an IPv4 address" end return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6) end
Returns true if the ipaddr is an IPv4-mapped IPv6 address.
# File lib/ipaddr.rb, line 262 def ipv4_mapped? return ipv6? && (@addr >> 32) == 0xffff end
Returns true if the ipaddr is an IPv6 address.
# File lib/ipaddr.rb, line 257 def ipv6? return @family == Socket::AF_INET6 end
Returns a new ipaddr built by masking IP address with the given prefixlen/netmask. (e.g. 8, 64, “<IP_ADDRESS>”, etc.)
# File lib/ipaddr.rb, line 159 def mask(prefixlen) return self.clone.mask!(prefixlen) end
Returns a new ipaddr built by converting the IPv6 address into a native IPv4 address. If the IP address is not an IPv4-mapped or IPv4-compatible IPv6 address, returns self.
# File lib/ipaddr.rb, line 296 def native if !ipv4_mapped? && !ipv4_compat? return self end return self.clone.set(@addr & IN4MASK, Socket::AF_INET) end
Returns a string for DNS reverse lookup. It returns a string in RFC3172 form for an IPv6 address.
# File lib/ipaddr.rb, line 305 def reverse case @family when Socket::AF_INET return _reverse + ".in-addr.arpa" when Socket::AF_INET6 return ip6_arpa else raise AddressFamilyError, "unsupported address family" end end
Returns the successor to the ipaddr.
# File lib/ipaddr.rb, line 333 def succ return self.clone.set(@addr + 1, @family) end
Returns the integer representation of the ipaddr.
# File lib/ipaddr.rb, line 202 def to_i return @addr end
Creates a Range object for the network address.
# File lib/ipaddr.rb, line 358 def to_range begin_addr = (@addr & @mask_addr) case @family when Socket::AF_INET end_addr = (@addr | (IN4MASK ^ @mask_addr)) when Socket::AF_INET6 end_addr = (@addr | (IN6MASK ^ @mask_addr)) else raise AddressFamilyError, "unsupported address family" end return clone.set(begin_addr, @family)..clone.set(end_addr, @family) end
Returns a string containing the IP address representation.
# File lib/ipaddr.rb, line 207 def to_s str = to_string return str if ipv4? str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1') loop do break if str.sub!(/\A0:0:0:0:0:0:0:0\z/, '::') break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':') break if str.sub!(/\b0:0:0:0:0:0\b/, ':') break if str.sub!(/\b0:0:0:0:0\b/, ':') break if str.sub!(/\b0:0:0:0\b/, ':') break if str.sub!(/\b0:0:0\b/, ':') break if str.sub!(/\b0:0\b/, ':') break end str.sub!(/:{3,}/, '::') if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\z/i =~ str str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256) end str end
Returns a string containing the IP address representation in canonical form.
# File lib/ipaddr.rb, line 233 def to_string return _to_string(@addr) end
Returns a new ipaddr built by bitwise OR.
# File lib/ipaddr.rb, line 129 def |(other) return self.clone.set(@addr | coerce_other(other).to_i) end
Returns a new ipaddr built by bitwise negation.
# File lib/ipaddr.rb, line 144 def ~ return self.clone.set(addr_mask(~@addr)) end
Protected Instance Methods
Set current netmask to given mask.
# File lib/ipaddr.rb, line 414 def mask!(mask) if mask.kind_of?(String) if mask =~ /\A\d+\z/ prefixlen = mask.to_i else m = IPAddr.new(mask) if m.family != @family raise InvalidPrefixError, "address family is not same" end @mask_addr = m.to_i @addr &= @mask_addr return self end else prefixlen = mask end case @family when Socket::AF_INET if prefixlen < 0 || prefixlen > 32 raise InvalidPrefixError, "invalid length" end masklen = 32 - prefixlen @mask_addr = ((IN4MASK >> masklen) << masklen) when Socket::AF_INET6 if prefixlen < 0 || prefixlen > 128 raise InvalidPrefixError, "invalid length" end masklen = 128 - prefixlen @mask_addr = ((IN6MASK >> masklen) << masklen) else raise AddressFamilyError, "unsupported address family" end @addr = ((@addr >> masklen) << masklen) return self end
Set +@addr+, the internal stored ip address, to
given addr
. The parameter addr
is validated using
the first family
member, which is Socket::AF_INET
or Socket::AF_INET6
.
# File lib/ipaddr.rb, line 393 def set(addr, *family) case family[0] ? family[0] : @family when Socket::AF_INET if addr < 0 || addr > IN4MASK raise InvalidAddressError, "invalid address" end when Socket::AF_INET6 if addr < 0 || addr > IN6MASK raise InvalidAddressError, "invalid address" end else raise AddressFamilyError, "unsupported address family" end @addr = addr if family[0] @family = family[0] end return self end
Private Instance Methods
# File lib/ipaddr.rb, line 586 def _reverse case @family when Socket::AF_INET return (0..3).map { |i| (@addr >> (8 * i)) & 0xff }.join('.') when Socket::AF_INET6 return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.') else raise AddressFamilyError, "unsupported address family" end end
# File lib/ipaddr.rb, line 599 def _to_string(addr) case @family when Socket::AF_INET return (0..3).map { |i| (addr >> (24 - 8 * i)) & 0xff }.join('.') when Socket::AF_INET6 return (("%.32x" % addr).gsub!(/.{4}(?!$)/, '\&:')) else raise AddressFamilyError, "unsupported address family" end end
# File lib/ipaddr.rb, line 575 def addr_mask(addr) case @family when Socket::AF_INET return addr & IN4MASK when Socket::AF_INET6 return addr & IN6MASK else raise AddressFamilyError, "unsupported address family" end end
# File lib/ipaddr.rb, line 512 def coerce_other(other) case other when IPAddr other when String self.class.new(other) else self.class.new(other, @family) end end
# File lib/ipaddr.rb, line 538 def in6_addr(left) case left when RE_IPV6ADDRLIKE_FULL if $2 addr = in_addr($~[2,4]) left = $1 + ':' else addr = 0 end right = '' when RE_IPV6ADDRLIKE_COMPRESSED if $4 left.count(':') <= 6 or raise InvalidAddressError, "invalid address" addr = in_addr($~[4,4]) left = $1 right = $3 + '0:0' else left.count(':') <= ($1.empty? || $2.empty? ? 8 : 7) or raise InvalidAddressError, "invalid address" left = $1 right = $2 addr = 0 end else raise InvalidAddressError, "invalid address" end l = left.split(':') r = right.split(':') rest = 8 - l.size - r.size if rest < 0 return nil end (l + Array.new(rest, '0') + r).inject(0) { |i, s| i << 16 | s.hex } | addr end
# File lib/ipaddr.rb, line 523 def in_addr(addr) case addr when Array octets = addr else m = RE_IPV4ADDRLIKE.match(addr) or return nil octets = m.captures end octets.inject(0) { |i, s| (n = s.to_i) < 256 or raise InvalidAddressError, "invalid address" s.match(/\A0./) and raise InvalidAddressError, "zero-filled number in IPv4 address is ambiguous" i << 8 | n } end


|
App Engine Python SDK
v1.6.9 rev.445
The Python runtime is available as an experimental Preview feature.
|
Public Member Functions | |
| def | __del__ |
| def | __getstate__ |
| def | __init__ |
| def | fileno |
| def | bind |
| def | listen |
| def | accept |
| def | connect |
| def | connect_ex |
| def | getpeername |
| def | getsockname |
| def | recv |
| def | recv_into |
| def | recvfrom |
| def | recvfrom_into |
| def | send |
| def | sendall |
| def | sendto |
| def | setblocking |
| def | settimeout |
| def | gettimeout |
| def | setsockopt |
| def | getsockopt |
| def | shutdown |
| def | close |
Public Attributes | |
| family | |
| type | |
| proto | |
socket([family[, type[, proto]]]) -> socket object Open a socket of the given type. The family argument specifies the address family; it defaults to AF_INET. The type argument specifies whether this is a stream (SOCK_STREAM, this is the default) or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0, specifying the default protocol. Keyword arguments are accepted. A socket object represents one endpoint of a network connection.
| def google.appengine.api.remote_socket._remote_socket.socket.accept | ( | self | ) |
accept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. For IP sockets, the address info is a pair (hostaddr, port).
| def google.appengine.api.remote_socket._remote_socket.socket.bind | ( | self, | |
| address | |||
| ) |
bind(address) Bind the socket to a local address. For IP sockets, the address is a pair (host, port); the host must refer to the local host. For raw packet sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
| def google.appengine.api.remote_socket._remote_socket.socket.close | ( | self | ) |
close() Close the socket. It cannot be used after this call.
| def google.appengine.api.remote_socket._remote_socket.socket.connect | ( | self, | |
| address, | |||
_hostname_hint = None |
|||
| ) |
connect(address) Connect the socket to a remote address. For IP sockets, the address is a pair (host, port).
| def google.appengine.api.remote_socket._remote_socket.socket.connect_ex | ( | self, | |
| address | |||
| ) |
connect_ex(address) -> errno This is like connect(address), but returns an error code (the errno value) instead of raising an exception when an error occurs.
| def google.appengine.api.remote_socket._remote_socket.socket.fileno | ( | self | ) |
fileno() -> integer Return the integer file descriptor of the socket.
| def google.appengine.api.remote_socket._remote_socket.socket.getpeername | ( | self | ) |
getpeername() -> address info Return the address of the remote endpoint. For IP sockets, the address info is a pair (hostaddr, port).
| def google.appengine.api.remote_socket._remote_socket.socket.getsockname | ( | self | ) |
getsockname() -> address info Return the address of the local endpoint. For IP sockets, the address info is a pair (hostaddr, port).
| def google.appengine.api.remote_socket._remote_socket.socket.getsockopt | ( | self, | |
| level, | |||
| option, | |||
buffersize = 0 |
|||
| ) |
getsockopt(level, option[, buffersize]) -> value Get a socket option. See the Unix manual for level and option. If a nonzero buffersize argument is given, the return value is a string of that length; otherwise it is an integer.
| def google.appengine.api.remote_socket._remote_socket.socket.gettimeout | ( | self | ) |
gettimeout() -> timeout Returns the timeout in floating seconds associated with socket operations. A timeout of None indicates that timeouts on socket operations are disabled.
| def google.appengine.api.remote_socket._remote_socket.socket.listen | ( | self, | |
| backlog | |||
| ) |
listen(backlog) Enable a server to accept connections. The backlog argument must be at least 1; it specifies the number of unaccepted connection that the system will allow before refusing new connections.
| def google.appengine.api.remote_socket._remote_socket.socket.recv | ( | self, | |
| buffersize, | |||
flags = 0 |
|||
| ) |
recv(buffersize[, flags]) -> data Receive up to buffersize bytes from the socket. For the optional flags argument, see the Unix manual. When no data is available, block until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, return the empty string.
| def google.appengine.api.remote_socket._remote_socket.socket.recv_into | ( | self, | |
| buf, | |||
nbytes = 0 , |
|||
flags = 0 |
|||
| ) |
recv_into(buffer, [nbytes[, flags]]) -> nbytes_read A version of recv() that stores its data into a buffer rather than creating a new string. Receive up to buffersize bytes from the socket. If buffersize is not specified (or 0), receive up to the size available in the given buffer. See recv() for documentation about the flags.
| def google.appengine.api.remote_socket._remote_socket.socket.recvfrom | ( | self, | |
| buffersize, | |||
flags = 0 |
|||
| ) |
recvfrom(buffersize[, flags]) -> (data, address info) Like recv(buffersize, flags) but also return the sender's address info.
| def google.appengine.api.remote_socket._remote_socket.socket.recvfrom_into | ( | self, | |
| buffer, | |||
nbytes = 0 , |
|||
flags = 0 |
|||
| ) |
recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info) Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.
| def google.appengine.api.remote_socket._remote_socket.socket.send | ( | self, | |
| data, | |||
flags = 0 |
|||
| ) |
send(data[, flags]) -> count Send a data string to the socket. For the optional flags argument, see the Unix manual. Return the number of bytes sent; this may be less than len(data) if the network is busy.
| def google.appengine.api.remote_socket._remote_socket.socket.sendall | ( | self, | |
| data, | |||
flags = 0 |
|||
| ) |
sendall(data[, flags]) Send a data string to the socket. For the optional flags argument, see the Unix manual. This calls send() repeatedly until all data is sent. If an error occurs, it's impossible to tell how much data has been sent.
| def google.appengine.api.remote_socket._remote_socket.socket.sendto | ( | self, | |
| data, | |||
| args | |||
| ) |
sendto(data[, flags], address) -> count Like send(data, flags) but allows specifying the destination address. For IP sockets, the address is a pair (hostaddr, port).
| def google.appengine.api.remote_socket._remote_socket.socket.setblocking | ( | self, | |
| block | |||
| ) |
setblocking(flag) Set the socket to blocking (flag is true) or non-blocking (false). setblocking(True) is equivalent to settimeout(None); setblocking(False) is equivalent to settimeout(0.0).
| def google.appengine.api.remote_socket._remote_socket.socket.setsockopt | ( | self, | |
| level, | |||
| option, | |||
| value | |||
| ) |
setsockopt(level, option, value) Set a socket option. See the Unix manual for level and option. The value argument can either be an integer or a string.
| def google.appengine.api.remote_socket._remote_socket.socket.settimeout | ( | self, | |
| timeout | |||
| ) |
settimeout(timeout) Set a timeout on socket operations. 'timeout' can be a float, giving in seconds, or None. Setting a timeout of None disables the timeout feature and is equivalent to setblocking(1). Setting a timeout of zero is the same as setblocking(0).
| def google.appengine.api.remote_socket._remote_socket.socket.shutdown | ( | self, | |
| flag | |||
| ) |
shutdown(flag) Shut down the reading side of the socket (flag == SHUT_RD), the writing side of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).


Advanced heapprof¶
As you use heapprof more, you’ll want to understand the corner cases of memory allocation better. Here are some general advanced tips worth knowing:
The performance overhead of heapprof hasn’t yet been measured. From a rough eyeball estimate, it seems to be significant during the initial import of modules (because those generate so many distinct stack traces) but fairly low (similar to cProfile) during code execution. This will need to be measured and performance presumably tuned.
The .hpx file format is optimized around minimizing overhead at runtime. The idea is that the profiler continuously writes to the two open file descriptors, and relies on the kernel’s buffering in the file system implementation to minimize that impact; to use that buffering most effectively, it’s important to minimize the size of data written, so that flushes are rare. This is why the wire encoding (cf file_format.*) tends towards things like varints, which use a bit more CPU but reduce bytes on the wire. This also helps keep the sizes of the generated files under control.
The profiler very deliberately uses C++ native types, not Python data types, for its internal operations. This has two advantages: pure C++ types are faster and more compact, (because of the simpler memory management model), and they eliminate the risk of weird recursions if the heap profiler were to try to call any of the Python allocators. NB, however, that this means that the heap profiler does not include its own memory allocation in its output!
More generally, the heap profiler only profiles calls to the Python memory allocators; C/C++ modules which allocate memory separately from that are not counted. This can lead to discrepancies between the output of heapprof and total system usage.
Furthermore, all real malloc() implementations generally allocate more bytes than requested under the hood (e.g., to guarantee memory alignment of the result; see e.g. this function in tcmalloc). Unfortunately, there is no implementation-independent way to find out how many bytes were actually allocated, either from the underlying C/C++ allocators or from the higher-level Python allocators. This means that the heap measured by heapprof will be the “logical” heap size, which is strictly less than the heap size requested by the process from the kernel. However, it is that latter size which is monitored by external systems such as the out-of-memory (OOM) process killers in sandbox environments.
Controlling Sampling¶
The sampling rate controls the probability with which heap events are written. Too high a sampling rate, and the overhead of writing the data will stop your app, or the amount of data written will overload your disk; too low a sampling rate, and you won’t get a clear picture of events.
heapprof defines sampling rates as a Dict[int, float]
, which maps the upper range of byte sizes to
sampling probabilities. For example, the default sampling rate is {128: 1e-4, 8192: 0.1}
. This
means that allocations from 1-127 bytes get sampled at 1 in 10,000; allocations from 128-8191 bytes
get sampled at 1 in 10; and allocations of 8192 bytes or more are always written, without sampling.
These values have proven useful for some programs, but they probably aren’t right for everything.
As heapprof is in its early days, its tools for picking sampling rates are somewhat manual. The best way to do this is to run heapprof in “stats gathering” mode: you can do this either with
python -m heapprof --mode stats -- mycommand.py args ...
or programmatically by calling heapprof.gatherStats()
instead of heapprof.start(filename)
. In
this mode, rather than generating .hpx files, it will build up a distribution of allocation sizes,
and print it to stderr at profiling stop. The result will look something like this:
-------------------------------------------
HEAP USAGE SUMMARY
Size Count Bytes
1 - 1<PHONE_NUMBER>
2 - 2 30462 60924
3 - 4 3766 14076
5 - 8<PHONE_NUMBER>169
9 - 16 1553664 23614125
17 - 32 17465509 509454895
33 - 64 27282873<PHONE_NUMBER>
65 -<PHONE_NUMBER> 801787796
129 -<PHONE_NUMBER> 567321439
257 - 512<PHONE_NUMBER>60935
513 - 1024<PHONE_NUMBER>07137
1025 - 2048<PHONE_NUMBER>41685
2049 - 4096<PHONE_NUMBER>13256
4097 - 8192<PHONE_NUMBER>937305
8193 - 16384 27027 278236057
16385 - 32768 8910 183592671
32769 - 65536 4409 200267665
65537 -<PHONE_NUMBER> 228614855
131073 -<PHONE_NUMBER> 277347497
262145 -<PHONE_NUMBER> 306727390
524289 - 1048576<PHONE_NUMBER>1
1048577 - 2097152 58 83804159
2097153 - 4194304 37 106320012
4194305 - 8388608 8 44335352
8388609 - 16777216 6 69695438
16777217 - 33554432 3 55391152
This tells us that there was a huge number of allocations of 256 bytes or less, which means that we
can use a small sampling rate and still get good data, perhaps 1e-5. There seems to be a spike in
memory usage in the 4096-8192 byte range, and generally the 256-8192 byte range has a few hundred
thousand allocations, so we could sample it at a rate of 0.1 or 0.01. Beyond that, the counts drop
off radically, and so sampling would be a bad idea. This suggests a sampling rate of
{256: 1e-5, 8192: 0.1}
for this program. You can set this by running
python -m heapprof -o <filename> --sample '{256:1e-5, 8192:0.1} -- mycommand.py args...
or
heapprof.start('filename', {256: 1e-5, 8192: 0.1})
Some tips for choosing a good sampling rate:
The most expensive part of logging isn’t writing the events, it’s writing the stack traces. Generally, very small allocations happen at a huge variety of stack traces (nearly every time you instantiate a Python variable!), but larger ones are far less common. This means that it’s usually very important to keep the sampling rate low for very small byte sizes – say, no more than 1e-4 below 64 bytes, and preferably up to 128 bytes – but much less important to keep it low for larger byte sizes.
The only reason you want to keep the sampling rate low is for performance; if at any point you can get away with a bigger sampling rate, err on that side.


Section 2.11 Internet
Skills Addressed in this Lesson:
Access the Internet from the Main Menu.
Type in and go to a specific web page.
Read a web page.
Move from link to link and open links when desired.
Access and use input controls.
Utilize the favorites list.
Use the history list.
Use computer Braille as necessary.
Subsection 2.11.1 Tasks
Complete the tasks listed below with your student. This lesson assumes that you have access to the Internet.
Assist your student in removing the compact flash card from the back of the BrailleNote if there is one inserted.
Help your student to insert the network card into the appropriate slot in the BrailleNote.
From the Main Menu of the BrailleNote, access the internet by keying in the letter i. At this point the url (address) of a web page will be displayed. By default, the web address of PulseData is displayed.
-
The following tasks can be accomplished from the url address. To learn these options listed for yourself, push space with h for help.
One option is to type in a url or a favorite name and press enter. You will be taken to the web site that you typed in.
For a local file, type backspace, then the file name.
To access the favorite list and saved html files, press space.
Space with dots5 6 will access the browser history list.
Use computer Braille to type the name of a web address. This means you may not use Braille contractions and you must use dots4 6 for a dot(period).
After you have pressed i from Main Menu to go to the internet, press enter to go to the web address displayed.
You may need to press enter to access your internet service or space to it and press enter.
-
Practice reading the web page you opened. Use the following commands:
Press space with g to go forward reading.
Go to the top of the page when necessary with space and dots1 2 3. Space with dots4 5 6 will go to the bottom of the page.
To find a text string, press space with f.
To move back a character and forward by character, use space with dot3 or space with dot6. Space with dots3 and 6 will read the current character.
To hear the current word, press space with dots2 5. Space with dot2 or space with dot5 will move back or forward by word.
To read back and forward by sentence, use space with dot4 or space with dot1.
Space with dots2 3 will move back by paragraph. Space with dots5 6 will move forward by paragraph. Space with dots2 3 5 6 will read the current paragraph.
Space with m will determine the current reading mode.
Space with m repeated will change the current reading mode.
Enter with dots5 6 will move to the next text section. Enter with dots2 3 will move to the previous text section.
Space with w will announce the key name.
To query the current cursor position, use space with dots1 5 6.
-
Practice with the Thumb-Key Commands
The advance thumb-key will advance the display by a width. Use the back thumb-key to move the display back by a width of the Braille display.
Use space with dots1 2 4 5 6 to start the Braille display moving automatically. Use the previous or next thumb-keys to control the speed. To stop, press previous and next together.
Previous with back will move the display back a word. Previous with advance will move the display on a word.
The previous thumb-key with space will change speech to on or off.
The next thumb-key with space will change the Braille display mode.
Back with advance will route the cursor to the beginning of the Braille display.
To cycle through the four Braille display modes, press previous and next repeatedly.
The advance thumb-key with the next thumb-key repeatedly will cycle through the text file display options.
On the Pulse Data page, go to the top of the page by using space with dots1 2 3.
Now type a g for the Google search engine link. Then press enter and you will go to the Google url.
Conduct a search for a specific topic of interest on the Google page. To get to the text input control, press space with dots4 and 6. Use computer Braille to key in the name of a topic. Press space with dots4 and 6 to move to the next input control, which should be the search button.
Press enter to begin the search. You may also just press enter after you write in the search edit box.
Use space to move forward by link. Move back by link by pressing backspace. Explore the results of your search. Press enter on a link to open the url. Use the web browser and miscellaneous commands listed here. Practice as necessary.
-
Web Browser and Miscellaneous Commands
Use enter with o to open a new url.
Space with i will display the name of the current web page.
Press enter to click a button.
Enter with f will go forward in a session history list.
Enter with b will go back a page in the session history list.
To refresh the current web page, press enter with the letter r.
To access the favorites menu, press enter with a low f (dots2 3 5).
-
Enter with m will go to the internet options menu. From the internet options menu, you may:
open an html file
set the current page as the home page
go to your home page
manage internet files
go to the display settings
print the current web page
check the error status
Enter with lower h (dots2 3 6 will go to the history list).
Space with dots1 3 will go to the previous input control. Space with dots4 and 6 will go to the next input control. Space with dots1 3 4 6 will read the current input control.
Space with b will take you to the block commands menu.
To access the spelling checker, use space with dots1 6.
Space with s will save a file.
Remember, at any time you can press the initial letter of a link to go directly to it. Practice using only the basic commands at first.
Subsection 2.11.2 Quiz
Give a short answer to each question.
What will space + dots46 do?
Space with what will display the name of the current web page?
How can you start the Braille display moving automatically?
What will using space + previous thumb-key turn on and off?
When using the Internet, enter + dots235 will do what?
When on a web page, what can you use to move from link to link?
What will enter with m bring up?
When using computer Braille, which Braille dotsmake a period?
When using the Internet, what will space + dots456 do?
What will take you to the history list?


COURSE DESCRIPTION: The course will investigate the origins and popularization of Rock and Roll as a musical genre and social and cultural phenomenon. The focus the relations between people’s social situation and the music generated, as well as how this music was then turned into profit, and how this in turn affected the music and musical scene." [Click to read more.]
Instructor: Mark R. Baker, Ph.D.
Phone:<PHONE_NUMBER>
email<EMAIL_ADDRESS>(I am most easily accessible via email.)
[website]
Class periods will include a mixture of discussion, video presentations, and lectures. Student participation is strongly encouraged.
| Date | Topic | ppt | Readings |
|---|---|---|---|
| 24 Sept. 2018 | Introduction to the course, origins of Rock and Roll: Race and Hill Billy Music | ppt | Szatmary, Chapter 1 |
| 1 Oct. 2018 | The Emergence of Rock and Roll as Cultural Force | ppt | Szatmary, Chapter 2; Marcus, Chapter 1 |
| 15 Oct. 2018 | Elvis and the Rock Idols: Rock and Roll Turns White | ppt | Szatmary, Chapter 3; Marcus, "Crying, Waiting, Hoping" |
| 22 Oct. 2018 | California, Surf Music, and the Beach Boys | ppt | Szatmary, Chapters 4-5 |
| 29 Oct. 2018 | Folk Music, Bob Dylan, and the export of Rock and Roll | ppt | Szatmary, Chapters 4-5 |
| 5 Nov. 2018 | The Beatles and the British Invasion | ppt | Szatmary, Chapters 6-7; Marcus, "Money (that's what I want)" |
| Muddy Waters performing "You can't lose what you never had" in 1966. | link |
| "This Day in Music History" tells you what was happening in music on any particular day of the year | link |
| How the bassist for Nirvana and Soundgarden became a US Forces ranger | link |
| What has streaming done to the music industry? Here is one recent take on the issue | link |
| Great article on a couple who attended Woodstock and are still married! | link |
| Here is a fascinating article on feminist punk rock: | link |
| Debra Harrie of Blondie, still a punk at age 70! | link |
| Here is a photo article about rock and roll in the last decade of the Soviet Union: | link |
| Rolling Stone Magazine has made a selection of articles from its archive freely available to all. | link |
| Come take the Survey! Rank the best rock songs of all time! | link |


Card
Card Header
Card Body
1 Card Header
1 Card Body
2 Card Header
2 Card Body
3 Card Header
3 Card Body


How can I contribute to RNAlysis?
Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
Report Bugs
Report bugs at https://github.com/GuyTeichman/rnalysis/issues.
If you are reporting a bug, please include:
Your operating system name and version.
Any details about your local setup that might be helpful in troubleshooting.
Detailed steps to reproduce the bug.
Fix Bugs
Look through the GitHub issues for bugs. Anything tagged with “bug” and “help wanted” is open to whoever wants to implement it.
Write Documentation
RNAlysis could always use more documentation, whether as part of the official RNAlysis docs, in docstrings, or even on the web in blog posts, articles, and such.
Submit Feedback
The best way to send feedback is to file an issue at https://github.com/GuyTeichman/rnalysis/issues.
If you are proposing a feature:
Explain in detail how it would work.
Keep the scope as narrow as possible, to make it easier to implement.
Remember that this is a volunteer-driven project, and that contributions are welcome :)
Implement Features
You are welcome to implement new features that you think would be useful! If you are looking for ideas, check out the Ideas/To-Do list below:
Ideas/To-Do
This is a rather unsorted list of features that would be nice to have, of things that could be improved in the source code, and of possible algorithmic improvements:
Interactive scatter plots (for example - click on a point to show/hide it’s gene/sample name)
Implement the GSEA single-list enrichment algorithm
Accept per-gene scaling factors in addition to per-sample scaling factors
Distplot for count matrices
Support for single-cell transcriptomics analysis
Support for ATAC-seq analysis
Generate sashimi plots
Generate genome browser-like plots
Merge tables row/column-wise
Support for additional formats of customized annotations
Correlation plots
Rank-sum test comparing data from two different columns/tables
RNAlysis Design Philosophy
As a guiding priniple for future development of RNAlysis, see this short list of the general design principle RNAlysis should follow:
Universality - RNAlysis should be usable on most computers. This means new features should be supported by commonly-used operating systems (Windows, Linux, MacOS) and currently supported Python versions. In the best case scenario, users who open RNAlysis should never ask themselves “which of these functions/modules are supported by my operating system?”
Graphical and Programmatic support - The majority of RNAlysis features should be usable both in the Graphical User Interface, and in Python scripts.
Customization and clarity - Functions and algorithms implemented in RNAlysis should give user a high degree of control over the function/algorithm parameters. This serves two purposes: firstly, it allows more advanced users to modify analysis parameters to suit their needs. Second, and perhaps most importantly, specifying and documenting all possible analysis parameters provides a high degree of transparency. Knowing exactly what parameters can be changed, and what are the default values, makes accurate and transparent reporting of analysis much easier. For example, when running GO enrichment, users can know and report exactly how the GO annotations are fetched, filtered, and annotated, which statistical test is used for analysis, etc.
Get Started!
Ready to contribute? Here’s how to set up rnalysis for local development.
Fork the rnalysis repo on GitHub.
Clone your fork locally:
$ git clone git@github.com:your_name_here/rnalysis.git
Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:
$ mkvirtualenv rnalysis $ cd rnalysis/ $ python setup.py develop
Create a branch for local development:
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
When you’re done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:
$ flake8 rnalysis tests $ python setup.py test or py.test $ tox
To get flake8 and tox, just pip install them into your virtualenv.
Commit your changes and push your branch to GitHub:
$ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature
Submit a pull request through the GitHub website.
Pull Request Guidelines
Before you submit a pull request, check that it meets these guidelines:
The pull request should include tests.
If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst.
The pull request should work for Python versions 3.7 - 3.10, and for PyPy. Check https://coveralls.io/github/GuyTeichman/RNAlysis and make sure that the tests pass for all supported Python versions.
Tips
To run a subset of tests:
$ py.test tests.test_rnalysis
Deploying
A reminder for the maintainers on how to deploy. Make sure all your changes are committed (including an entry in HISTORY.rst). Then run:
$ bumpversion patch # possible: major / minor / patch
$ git push
$ git push --tags
Travis will then deploy to PyPI if tests pass.


There Are a Ton of Cool Easter Eggs in The CREEPSHOW Series and This Video Points Them All Out
by Joey PaurGreg Nicotero’s horror anthology series Creepshow was a lot of fun to watch and it was loaded with a ton of Easter Eggs, some of which you might have missed while watching the show. There are a lot of Stephen King Easter eggs along with Day of the Dead, Halloween, A Nightmare on Elm Street, Evil Dead, The Shining, Texas Chainsaw Massacre, and more.
Thanks to a video that was released by AMC’s streaming service Shudder, you can see every Easter egg that was packed into this show.
If you haven’t watched the first season of Creepshow yet, you should check it out! The series was so well received that Shudder has renewed it for a second season.


{% extends "layout.html" %} {% block content %}
Under development, November, 2014.
In future, other systems will be able to POST data to this endpoint to inform this PROMS server instance that a reference to one of the Entities listed here has been made in a provenance graph.
This is in accordance with the idea of "Forward provenance" as per PROV-AQ: Provenance Access and Query, W3C Working Draft 12 March 2013
@prefix prov: <http://www.w3.org/ns/prov#> . <their_entity_uri> a prov:Entity ; prov:wasDerivedFrom <our_entity_uri> ; .
@prefix prov: <http://www.w3.org/ns/prov#> . <their_activity_uri> a prov:Activity ; prov:used <our_entity_uri> ; .


BATMAN RETURNS A film review by Kreme Copyright 1992 by Lewis Butler
Summary: Batman is back, and some of the style seems to have been washed out. Overall a fun movie with a comic-book plot and a wonderfully endearing performance from Michelle Pfeiffer and a good, but silly, performance from Danny DeVito. A +1 (-4 to +4)
The Bat is back, and this time we get to see his nemesis, The Penguin and the provocative Catwoman. This movie will disappoint many people who are hoping to see more of the same movie magic that made BATMAN so enjoyable. While the plot has regressed remarkably to a cartoonish-comic-bookish level, the sexual innuendo/humor has escalated to a purely adult level. The movie sends mixed signals throughout and never fails to miss even the most obvious sexual joke. Too bad, if the movie had stayed mostly adult as BATMAN did it would have been much better; even if it had been purely comic-book it would have been marginally better. As it is it tries to straddle the fence between pleasing the 13 year-olds and pleasing the parents with them. I think it misses both.
Understand me, this is not a *poor* movie. Not at all, but it is not BATMAN, and it is not even a particularly worthy successor. While BATMAN had a undeniable forcefulness to it and a tightness to the plot and dialog, this film slowly meanders through an ambling plotline to a predictable end. Much of the dialog is spend on jokes, but without the same humor or strength of BATMAN. BATMAN RETURNS is trying to show-off.
Once again the focus of the movie is not Batman himself, but rather one of the villains. In this movie it is Michelle Pfeiffer as Catwoman who steals center stage. Her performance is wonderfully alive, down to the soft throaty growl in her voice and the unassuming "Meow." She is everything a cat-woman should be, even slightly naughty (though she tends to sharpen her claws on people instead of furniture). Selina Kyle is a perfect foil to Bruce Wayne, and as readers of the Batman comics have know for years, Catwoman is in many ways Batman's perfect "villain."
Danny DeVito is quite good as the Penguin, but I felt that the screenplay called for a character that was far too much a "freak" and far too comical. There is none of the sheer evil of Nicholson's Joker, just a comical silliness that DeVito never quite manages to shed, even when he is trying to be the bad guy. The ridiculous costume hinders him and reduces the character to a rather uninteresting goon.
The plot is choppier than BATMAN. Much of the movie is a bit confused. We don't really *know* who the "Red Triangle Gang" is: children that were stolen or performers from the circus? There is a general feeling of slight discontinuity throughout the film. In short the editing was not nearly as good as BATMAN.
But the movie is enjoyable anyway. The sets are great, though we never have time to really examine them, and there is no wonderful architectural focal point like the church in BATMAN. Instead there is a Christmas Tree. Oh well.
Elfman's score is wonderful and manages to lift the movie during some of its weaker moments. The supporting cast is mostly very good, though I though the actor playing Max's (Christopher Walken) son could have done better with the three or four lines he had.
If you are a bat-freak you will see this movie no matter what, and there are enough bat-freaks out there that this movie will certainly be successful, though it will play in comparison to the first. If they learn from their mistakes in this film and remember the first, the third should be something wonderful. (Anyone doubt there will be a third?)
For the less bat-fixated among you, the movie is worth seeing for anyone who really liked the first movie and would like to see a great performance from Michelle Pfeiffer.
If you disliked the first movie you will probably like this one even less.
Oh yes, and one more thing, there is quite a bit more gratuitous violence and mayhem in BATMAN RETURNS than in BATMAN.
--<EMAIL_ADDRESS>kreme@#22 (FV3 Net) [303/722-2009] Vox
.
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


EU, U.S., UK, others condemn violence - The Nation Newspaper
By Bola Olajuwon, Assistant Editor
THE “Diplomatic Watch” teams deployed by Austria, the European Union Delegation, Germany, Ireland, the Netherlands, the United Kingdom (UK) and the United States (U.S.) to monitor last Saturday’s elections in Bayelsa and Kogi states have expressed concern over reports of widespread violence and intimidation, some of which were witnessed in Kogi State.
A joint statement issued yesterday by the embassies of the teams condemned reports of fatalities and cases of people missing, including Independent National Electoral Commission (INEC) staff, during the elections.
The statement said: “Our thoughts are with all victims and their families. We encourage all stakeholders, in particular, political leaders, to call for calm and we encourage security agencies to investigate thoroughly and bring perpetrators to justice.
“We are also concerned by evident vote-buying and credible reports of ballot box snatching in both Bayelsa and Kogi.
“We commend the commitment and resilience of voters in both states, who came out to exercise their democratic rights.
“We express our sympathy for those affected by the violence, including ordinary voters; INEC officials; members of the NYSC; civil society; and the media. All should be able to carry out their fundamental role in the democratic process free from intimidation and harassment.
“As long-standing friends, we have been present at every major election in Nigeria since 1999. We remain committed to working impartially with Nigerian authorities, INEC in particular, as well as civil society to consolidate and deepen democracy.”


Let's now consider the statement, "All children deserve to live." This is a common quantified statement that is offered in abortion debates. Let's discuss the sets, and think independently about potential subsets that can exist.


Social media sites allow users to post and share content and react to each other’s content. Major players include Facebook and Twitter. Facebook is a force, claiming about
Marketing on social media can take many forms. The primary form is creating profiles for your dealership and posting content that helps potential customers understand your message and see what you have to offer.
Once you establish trust, you can drive your followers to your site through strategic social posting.
Utilizing social media is one of the few ways dealers can communicate with potential customers.
These metrics reveal that the people who saw the content appreciated you posting it and acknowledge and enjoy the value there, which is a great start and a solid indicator of the type of content that will resonate.
This metric helps determine if the material was emotionally resonant enough for people to feel impacted and compelled to comment on it (whether positively or negatively, so this needs to be analyzed on a case-by-case basis).
These are the ultimate sign of being on the right track; when your content has increasingly high share numbers, that often means users think there’s a high level of value in that content.
If your content isn’t getting enough shares, try sharing more content that meets the following criteria:
It communicates new, surprising information, which, as a result, inherently has newsworthiness.
It provides value by being informative and relevant to the industry, perhaps acting as a resource for potential buyers and previous buyers.
It connects with locals by being open and honest about how the brand is involved with the community.
While starting up new social accounts and gaining fans/followers can be slow-going, the important thing to track is whether or not you’re seeing improvement in engagement.
Are the numbers of the above metrics increasing over time? Does one month see an improvement over the other? These are the questions you need to assess as you tweak your social strategy.


All elements should have box-sizing:border-box and dimensions should be 100x100 (for generated content 30x30)
box-sizing:content-box elements and their descendants should have default box model and dimensions should be 130x130 (for generated content 50x50)
html should have overflow-y:scroll, black text color and sans-serif font values
body should have white background color
Typography
abbr[title], acronym[title], dfn should have cursor:help
abbr title
acronym title
dfn
hr should be rationalized
b and strong should be rationalized
b element strong element
Embedded content
img should be fluid and have vertical-align:bottom
Unreachable img should have italic alternative text
Images inside Google Maps shouldn’t be fluid
object, embed should have vertical-align:bottom
Grouping content
pre should have normalized overflow
Lorem ipsum dolor sit amet
Forms
input should have normalized line-height
Basic form elements should inherit parent element font and color values
Placeholder in inputs should be shortened with ellipsis if it doesn’t fit
Placeholder in inputs should have consistent text color
input, textarea should have normalize invalid styling
legend should have display:table;
fieldset should be styled with sensible defaults
textarea should only allow vertical resizing
textarea should not have any vertical spacing
select should have white background color
select, label[for], label input, input[type="image"], button, [type="button"], [type="reset"], [type="submit"], [role="button"] should have pointer as cursor
role submit
[disabled] should have default cursor
Tables
Tables should have consistent styling
Foo
Bar
Accessibility
Focused elements with [tabindex="0"] should be visually emphasized
custom tabindex
Focused elements with [tabindex="-1"] shouldn’t be visually emphasized
custom tabindex
Elements with [aria-disabled="true"] should have default cursor


 Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
List:
- mouse
- keyboard
- monitor
-
12345
It's interesting how the software landscape twists and turns sometimes. Go itself has some good Pascal-ish flavor, mostly via Oberon (although I actually liked the comparison with Algol 68[1], flawed as it was)
A good comparison of Go-like interfaces vs Oberon's minimalistic record extension would be interesting.
robdelacruz 2020-02-24
That's a good observation. I wish I thought of that.
user2 2020-02-24
@robdelacruz Yeah me too.
In fact, I think I did think of that.


Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \). The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable.
A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with
Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.
Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is $$ y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i, $$ where \( \epsilon_i \) is the error in our approximation.
For every set of values \( y_i,x_i \) we have thus the corresponding set of equations $$ \begin{align*} y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ \dots & \dots \\ y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\ \end{align*} $$
Defining the vectors $$ \hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ $$ \hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ $$ \hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ and the matrix $$ \hat{X}= \begin{bmatrix} 1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ 1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ 1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ \dots& \dots &\dots& \dots & \dots &\dots\\ 1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ \end{bmatrix} $$ we can rewrite our equations as $$ \hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. $$
We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. For every set of values \( y_i,x_i \) we can then generalize the equations to $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ \dots & \dots \\ y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ \dots & \dots \\ y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$
We redefine in turn the matrix \( \hat{X} \) as $$ \hat{X}= \begin{bmatrix} x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ \dots& \dots &\dots& \dots & \dots &\dots\\ x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ \end{bmatrix} $$ and without loss of generality we rewrite again our equations as $$ \hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. $$ The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?
We have defined the matrix \( \hat{X} \) $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ \dots & \dots \\ y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ \dots & \dots \\ y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$
We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as $$ \hat{\tilde{y}}= \hat{X}\hat{\beta}, $$ and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely $$ Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right), $$ or using the matrix \( \hat{X} \) as $$ Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right). $$
The function $$ Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right), $$ can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable.
In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring $$ \frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, $$ which results in $$ \frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, $$ or in a matrix-vector form as $$ \frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right). $$
We can rewrite $$ \frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right), $$ as $$ \hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta}, $$ and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution $$ \hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}. $$
The residuals \( \hat{\epsilon} \) are in turn given by $$ \hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta}, $$ and with $$ \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, $$ we have $$ \hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, $$ meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.
Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable.
Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function as $$ \chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right), $$ where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.
In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\hat{\beta}) \) by requiring $$ \frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, $$ which results in $$ \frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, $$ or in a matrix-vector form as $$ \frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right). $$ where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \).
We can rewrite $$ \frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right), $$ as $$ \hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta}, $$ and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution $$ \hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}. $$
If we then introduce the matrix $$ \hat{H} = \hat{A}^T\hat{A}, $$ we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \hat{H} \) are \( h_{ij} \)) $$ \beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} $$ We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as $$ \sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, $$ resulting in $$ \sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! $$
The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write $$ y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. $$ By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by $$ \frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, $$ and $$ \frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. $$
We define then $$ \gamma = \sum_{i=0}^{1}\frac{1}{\sigma_i^2}, $$ $$ \gamma_x = \sum_{i=0}^{1}\frac{x_{i}}{\sigma_i^2}, $$ $$ \gamma_y = \sum_{i=0}^{1}\left(\frac{y_i}{\sigma_i^2}\right), $$ $$ \gamma_{xx} = \sum_{i=0}^{1}\frac{x_ix_{i}}{\sigma_i^2}, $$ $$ \gamma_{xy} = \sum_{i=0}^{1}\frac{y_ix_{i}}{\sigma_i^2}, $$ and show that $$ \beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, $$ $$ \beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. $$
The LSM suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below.
How can we use the singular value decomposition to find the parameters \( \beta_j \)? More details will come. We first note that a general \( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal matrix \( \hat{\Sigma} \) of dimensionality \( n\times n \) and two orthognal matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality \( m \times n \) and the last dimensionality \( n\times n \). We have then $$ \hat{A} = \hat{U}\hat{\Sigma}\hat{V} $$


Menu
Contact
About
Build your team with us
Welcome to your Teamathon site.
Now go build some awesome teams.
Log in / Sign in
© Copyright 2018
Privacy
Contact


Public participation guide
Not your municipality?
Click here to change locations
Cape Agulhas
Bergrivier
Cape Agulhas
Cederberg
Matzikama
Swartland
Not your municipality?
Click here to change it
Citizens of
Make your voices heard by engaging with your municipality
Find upcoming engagements
Contact your ward Councillor
Engagements in the next
3 Months
1 Month
3 Months
6 Months
12 Months
FILTER engagements by TYPE:
Loading...
Upcoming engagements styles
Engagement tab links
.tab-link .current
Loading...
.tab-link
Loading...
Engagement tab content
empty .tab-pane (this is the grid layout element that houses all the elements below)
Example of what the loading state looks like (.loading not hidden)
.tab-pane__empty
No engagements to show for this period.
Try expanding your time-frame.
.engagement-block
Loading...
.engagement-block--highlight
Loading...


CORS¶
Many endpoints in IdentityServer will be accessed via Ajax calls from JavaScript-based clients. Given that IdentityServer will most likely be hosted on a different origin than these clients, this implies that Cross-Origin Resource Sharing (CORS) will need to be configured.
Client-based CORS Configuration¶
One approach to configuring CORS is to use the AllowedCorsOrigins
collection on the client configuration.
Simply add the origin of the client to the collection and the default configuration in IdentityServer will consult these values to allow cross-origin calls from the origins.
Note
Be sure to use an origin (not a URL) when configuring CORS. For example: https://foo:123/
is a URL, whereas https://foo:123
is an origin.
This default CORS implementation will be in use if you are using either the “in-memory” or EF-based client configuration that we provide.
If you define your own IClientStore
, then you will need to implement your own custom CORS policy service (see below).
Custom Cors Policy Service¶
IdentityServer allows the hosting application to implement the ICorsPolicyService
to completely control the CORS policy.
The single method to implement is: Task<bool> IsOriginAllowedAsync(string origin)
.
Return true
if the origin is allowed, false
otherwise.
Once implemented, simply register the implementation in DI and IdentityServer will then use your custom implementation.
DefaultCorsPolicyService
If you simply wish to hard-code a set of allowed origins, then there is a pre-built ICorsPolicyService
implementation you can use called DefaultCorsPolicyService
.
This would be configured as a singleton in DI, and hard-coded with its AllowedOrigins
collection, or setting the flag AllowAll
to true
to allow all origins.
For example, in ConfigureServices
:
var cors = new DefaultCorsPolicyService(_loggerFactory.CreateLogger<DefaultCorsPolicyService>())
{
AllowedOrigins = { "https://foo", "https://bar" }
};
services.AddSingleton<ICorsPolicyService>(cors);
Note
Use AllowAll
with caution.
Mixing IdentityServer’s CORS policy with ASP.NET Core’s CORS policies¶
IdentityServer uses the CORS middleware from ASP.NET Core to provide its CORS implementation. It is possible that your application that hosts IdentityServer might also require CORS for its own custom endpoints. In general, both should work together in the same application.
Your code should use the documented CORS features from ASP.NET Core without regard to IdentityServer.
This means you should define policies and register the middleware as normal.
If your application defines policies in ConfigureServices
, then those should continue to work in the same places you are using them (either where you configure the CORS middleware or where you use the MVC EnableCors
attributes in your controller code).
If instead you define an inline policy in the use of the CORS middleware (via the policy builder callback), then that too should continue to work normally.
The one scenario where there might be a conflict between your use of the ASP.NET Core CORS services and IdentityServer is if you decide to create a custom ICorsPolicyProvider
.
Given the design of the ASP.NET Core’s CORS services and middleware, IdentityServer implements its own custom ICorsPolicyProvider
and registers it in the DI system.
Fortunately, the IdentityServer implementation is designed to use the decorator pattern to wrap any existing ICorsPolicyProvider
that is already registered in DI.
What this means is that you can also implement the ICorsPolicyProvider
, but it simply needs to be registered prior to IdentityServer in DI (e.g. in ConfigureServices
).


#include <address.hpp>
| static Try<Address> process::network::Address::create |
( |
const sockaddr_storage & |
storage | ) |
|
|
inlinestatic |
| Family process::network::Address::family |
( |
| ) |
const |
|
inline |
| process::network::Address::operator sockaddr_storage |
( |
| ) |
const |
|
inline |
| size_t process::network::Address::size |
( |
| ) |
const |
|
inline |
template<typename AddressType >
| std::ostream& operator<< |
( |
std::ostream & |
stream, |
|
|
const Address & |
address |
|
) |
| |
|
friend |
| sockaddr_in process::network::Address::in |
| sockaddr_storage process::network::Address::storage |
| sockaddr_un process::network::Address::un |
The documentation for this class was generated from the following file:


Phishing is a way of attempting to acquire information such as usernames, passwords, and credit card details by masquerading as a trustworthy entity in an electronic communication. Communications purporting to be from popular social web sites, auction sites, online payment processors or IT administrators are commonly used to lure the unsuspecting public. Phishing is typically carried out by e-mail spoofing or instant messaging.
This step by step guide will show you how you can make your own Facebook Phishing (Fake) page easily...have fun!
1. Haktuts.php
2. Index.html
Step 1:
Creating Haktuts.php file. First of all we need a PHP script which will collect all the form of data.
Step 2 :
Creating index.html page Goto Facebook. com (without logging in) , Right click anywhere in the browser and choose view page source. Open the source code in a text editor (notepad).
Step 3:
<Now a new window will pop-up where you can see all the HTML code. We need to look for word action. Press CRTL+F and search for action. you will find link like this
action="https://www. facebook. com/ login.php? login_attempt=1"
Replace the link after action between the "..... " with Haktuts.php like action="Haktuts.php" and save this page as index.html (not index.html.txt).
Step 4:
Create account on free hosting website like
http://www. t35. com
http://www. freehostia. Com
http://www.000webhost.com
Step 5:
Now upload "Haktuts.php" & "index.html" to the "facebook" folder you created inside "your name. t35. com". So when you're done with the uploading part, the link to your gmail phisher is
"www. your name. t35. com/facebook/index.htm".
Step 6:
Send this link to the victim with any message like change your facebook password etc. If any body login on your fake page then his/her username and password stores on you free hosting website account in log.txt file.
So Enjoy Phishing.....
© 2014 HaKTuts. All rights reserved.


IntroductionFrequently asked questionsSyntax, keywords and built-in functionsStandard distributionimport implementationBrowser interface
Introduction - DOM API
Creating a document Accessing elements Attributes and methods Events Mouse events Keyboard events Focus events Drag events Query string Using Javascript objects and libraries Brython-specific built-in modules
browser
browser.ajax browser.html browser.local_storage browser.markdown browser.object_storage browser.session_storage browser.svg browser.timer browser.websocket javascript Working with Brython
Options of function
brython()
Installing the development environment Testing and debugging Deploying an application Brython for Firefox OSCookbook |
Building your own webapp : application logicCreate a Python program called calculator.py ; in index.html, just after thebody tag, add this line
This will make the Brython engine load and run the script The first lines of calculator.py will import the built-in Brython names used to interact with the application from browser import documentAll the keys in the keyboard are inside html anchors (tags ... ). The object document can find all the anchors by :
anchors = document.get(selector='a')Since you are debugging the application, it is useful to control that you really get the anchors, so you can add the line print(anchors)which will print the anchors list in the browser console Ok, so calculator.py is from browser import document anchors = document.get(selector="a") print(anchors)Reload the page in the browser and open the console (Tools > Web developer > Web console). In the console, you should see a list of elements <DOMNode object type 'ELEMENT' name 'A'>Each of the anchor object has an attribute text ; you can see what this attribute is by changing the last line by print(list(anchor.text for anchor in anchors))This prints ['7', '8', '9', '÷', '4', '5', '6', '*', '1', '2', '3', '-', '.', '0', '=', '+'] in the console
To define what happens when the user clicks on an anchor, Brython uses the syntax
anchor.bind('click', callback)where callback is a function taking a DOMEvent instance as argument. In this application, we will use the same callback function for all the keys
from browser import document anchors = document.get(selector="a") def callback(ev): print(ev.target.text) for anchor in anchors: anchor.bind('click', callback)With these bindings, when the user hits a key, the text on this key in printed in the console (the attribute target of the DOMEvent object is the anchor itself)
This is not exactly what we want : the text should be entered in the entry field. This entry field has the id "entry", and Brython gets a reference to the field by document["entry"] . The callback function can be changed to
def callback(ev): document["entry"].value += ev.target.textThis is ok for most keys, but we must handle those that are supposed to compute a result. The complete code of calculator.py below should be self-explanatory from browser import document import math anchors = document.get(selector="a") entry = document["entry"] def callback(ev): txt = ev.target.text if txt=='C': entry.value = '' elif txt=='<' and entry.value: entry.value = entry.value[:-1] elif txt=='=': try: entry.value = eval(entry.value) except: entry.value = 'error' elif txt=='√¯': try: entry.value = math.sqrt(float(entry.value)) except: entry.value = 'error' elif txt=="1/x": try: entry.value = 1/float(entry.value) except: entry.value = 'error' else: entry.value += ev.target.text for anchor in anchors: anchor.bind('click', callback) |


Tweet to @tweetTrek
tweets will show up here, as they happen! if they don't, your browser might not support
websockets
.


You get more flexibilty running an HTML notification, adding any HTML element you want. Even a link to close it.
The maximum size seems to be 300x175 (with borders and everything).