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 |
|---|---|---|---|---|---|
The domain name space is a tree structure. Each node and leaf on the tree corresponds to a resource set (which may be empty). The domain system makes no distinctions between the uses of the interior nodes and leaves, and this memo uses the term “node” to refer to both.).
When a user needs to type a domain name, the length of each label is omitted and the labels are separated by dots (“.”). Since a complete domain name ends with the root label, this leads to a printed form which ends in a dot, that is omitted. For example, a valid domain name is
wallet.alice.rsk.
Each domain name has a node identifier in the RNS Registry, that is obtained via
namehash functions, that is as follows:
def namehash(name): if name == '': return '\0' * 32 else: label, _, remainder = name.partition('.') return sha3(namehash(remainder) + sha3(label))
Given a
node, a
subnode can be identified by using its label:
sha3(namehash(node) + sha3(label))
Further reading:
Go to top | https://developers.rsk.co/rif/rns/specs/ | CC-MAIN-2020-34 | refinedweb | 170 | 68.1 |
Strings in C++ programming
Definition of Strings
The standard library provides a string type to complement the string literals. The string type provides a variety of useful string operations, such as concatenation.
For example:
string compose(const string& name, const string& domain) { return name + # + domain; } auto addr = compose("amg","infoweb14.com");
Here, addr is initialized to the character sequence [email protected]. ‘‘Addition’’ of strings means concatenation. You can concatenate a string, a string literal, a C-style string, or a character to a string.
The standard string has a move constructor so returning even long strings by value is efficient.
The string class also has several member functions. For example, the size function returns the length of the string. It is demonstrated in the for loop in program below.
This program demonstrates some C++ string class member functions.
#include <iostream> #include <string> using namespace std; int main() { string str1, str2, str3; str1 = "ABC"; str2 = "DEF"; str3 = str1 + str2; // Use the size() string member function // and the overloaded string operator [ ]. for (int k = 0; k < str3.size(); k++) cout << str3[k]; // Use the overloaded string operator <. if (str1 < str2) cout << str1 << " is less than " << str2 << endl; else cout << str1 << " i cout << endl; s not less than " << str2 << endl; return 0; }
Program Output : ABCDEF ABC is less than DEF
The table following lists many of the string class member functions and their overloaded variations.
Ads Right | https://www.infocodify.com/cpp/strings | CC-MAIN-2020-34 | refinedweb | 234 | 64.61 |
Hello friends, this is my first article in CodeProject.com. This article is mainly intended to read content from
a PDF file and convert that into a string using C#.
This was actually assigned as a task for me. Actually I Googled about this and finally did
it with a simple code. I'm sure this code will be very helpful for beginners.
The following steps will guide you to read content from a PDF file:
You have successfully completed the initial step in the process..... hurrah.....! ! ! !
Now open Microsoft Visual studio. For me it is Microsoft Visual C# 2010 Express.
Select Project menu --> Select Browse tab --> Select itextsharp.dll from
the local directory.
richTextBox1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ExtractTextFromPDFPage("c:\sample.pdf", 1);
}
public void ExtractTextFromPDFPage(string pdfFile, int pageNumber)
{
PdfReader reader = new PdfReader(pdfFile);
string text = PdfTextExtractor.GetTextFromPage(reader, pageNumber);
try { reader.Close(); }
catch { }
richTextBox1.Text = text;
}
}
}
Look how simple it is....!!! " src="" />
RichTextBox
That's it, you have successfully converted a PDF file into text.
Here c:\sample.pdf is where I kept my PDF file. So you should update the path
to your file. The second parameter denotes which page you need to get converted.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
General News Suggestion Question Bug Answer Joke Rant Admin
Math Primers for Programmers | http://www.codeproject.com/Tips/387327/Convert-PDF-file-content-into-string-using-Csharp?msg=4265376 | CC-MAIN-2013-20 | refinedweb | 271 | 54.59 |
20 June 2011
By clicking Submit, you accept the Adobe Terms of Use.
Knowledge of Flex and/or ActionScript
All
Note: Besides this article, you can watch Serge Jespers's accompanying video to learn more about Flash Builder 4.5.
Just twelve months on from the release of Flash Builder 4, we're excited to deliver a major update to our developer tooling that introduces a wealth of new features and enhancements to Flash Builder.
Our pre-release testers have described this as a game-changing release and we hope you agree that we're providing the most productive development environment for Flex and ActionScript developers.
In Flash Builder 4.5 we've focused our efforts on the following areas:
This article will provide you with an overview of the new features, product enhancements, and workflows introduced in Flash Builder 4.5, as well as provide links to additional resources that will help you get started with this release.
Flash Builder 4.5 adds comprehensive support for developing, testing and deploying mobile AIR applications built using Adobe Flex 4.5 SDK or ActionScript. Using your existing skills and familiar workflows, you can now productively build web, desktop, and mobile applications with Flash Builder.
We’ve added support for defining either a Flex or an ActionScript mobile project in Flash Builder, from which you can package an application that targets one or more mobile platforms, including Google Android, Apple iOS and BlackBerry Tablet OS.
Adobe Flex 4.5 SDK introduces support for mobile application development, through the provision of mobile optimized mobile components and new application-level constructs that encapsulate common design patterns for mobile applications (see Figure 1). For projects using Adobe Flex 4.5 SDK, the coding environment in Flash Builder automatically suggests mobile optimized components through content assist, while design view provides full support for mobile application layout and visual preview for different device screen sizes and orientations.
For all mobile projects, Flash Builder enables convenient launch and debugging options, allowing applications to be previewed and debugged either on the desktop or using a connected mobile device.
When your application is finished and ready for deployment, Flash Builder provides a streamlined workflow for exporting a release build of the application.
For more information on developing mobile applications using Adobe Flex 4.5 SDK and Flash Builder 4.5 please read Narciso Jaramillo’s article on the Adobe Developer Connection site.
As we planned for this release, we listened to requests from developers to provide an even more productive coding environment - that's what we've delivered in Flash Builder 4.5. There are over 25 new features focused on making your coding experience faster, in addition to those we added in Flash Builder 4.
Flash Builder 4.5 adds support for code templates (often referred to as snippets), allowing you to use content assist to insert pre-defined blocks of MXML, ActionScript or CSS into your code. Flash Builder comes with over 100 built-in templates that are ready-to-use, such as for defining a package, class, for loop, while loop, switch block, etc. You can define your own set of custom templates, as well as import/export templates so that everyone on the development team has a consistent set of templates for use on projects (see Figure 2).
Quick Assists provide contextual access to convenient code-related operations and can be accessed in Flash Builder 4.5 using CTRL+1. In this release we’ve added support for renaming identifiers in file or workspace, organizing imports, converting local variables to field, assigning expressions to variables, generating getter/setters, generating event handlers, generating label functions and splitting variable declarations. Quick Assists can also be used to generate stub code when you reference a yet-to-be-defined variable, method, class or interface in your code. In these situations, Flash Builder provides a real-time warning, indicated by an orange squiggly line, allowing you to use Quick Assist to resolve the problem and continue with the development task in hand.
In addition to the above features, we’ve added support for metadata content assist, meaning that Flash Builder now provides you with code hints for both Flex SDK and custom metadata when you type ‘[‘ in code view; we’ve improved content assist so as to support proposal cycling for ActionScript, meaning that you can quickly filter code hints to only show templates, variables, functions, classes/interfaces, packages or namespaces; and we’ve added the ability to generate stub methods for parent class methods that you want to override or interface methods that you want to implement.
We also paid particular attention to a range of minor enhancements that collectively make a big impact on the coding experience - in Flash Builder 4.5 you'll benefit from the following improvements:
For more information on using the coding productivity features in Flash Builder 4.5 please read Sameer Bhatt and Sreenivas Ramaswamy’s article on the Adobe Developer connection site.
With the release of Flash Builder 4 and Flash Catalyst CS5 we enabled designers and developers to begin to collaborate on the production of high-fidelity Flex projects, with the designer providing the developer with design assets and component skins. We knew however that further investment was required to support bi-directional workflows between designers and developers.
The Flash Catalyst team has also been working hard on a new release, Flash Catalyst CS5.5, which adds support for opening Flex projects that were created or edited in Flash Builder 4.5.
In addition to opening Flash Builder projects, Flash Catalyst has improved code generation, supports re-sizable user interfaces, and ensures that developer code referenced from user interface controls are protected from designer edits.
To support the new capabilities in Flash Catalyst CS5.5, we’ve introduced a number of new features in Flash Builder 4.5.
One of the key things a developer will need to consider while working with a designer is maintaining compatibility with sub-set of Flex features supported by Flash Catalyst; in addition, there are also some project configuration settings which are incompatible with Flash Catalyst. In Flash Builder you can turn on the ‘Flash Catalyst compatibility checker’ to provide warnings if any of the components, attributes or project settings might cause an issue upon import into Flash Catalyst—you can then resolve those issues or re-factor parts of the project into a Library before exporting the project for a designer.
Flash Catalyst enables designers to use the convert artwork to component skins workflow (introduced in the previous release) with custom skinnable components defined by the developer. In Flash Builder we’ve provided a convenient wizard to help you generate the required ActionScript classes in which you can specify the skin states, skin parts, and the component business logic.
For developers who are comfortable with both making code and design changes, we've also added a launch-and-edit workflow in Flash Builder. With both products installed, you can select a project in Flash Builder, select "Edit in Flash Catalyst", make the required design changes in Flash Catalyst and then return to Flash Builder to continue working on the updated version of the project. This speeds up the workflow and completely avoids the need to export and import FXP files.
There are a number of different approaches to using Flash Builder and Flash Catalyst together—for more information on designer-lead and developer-lead workflows, creating custom skinnable components and the restrictions that are in place for Flash Catalyst projects please see Jacob Surber's article on the Adobe Developer Connection site.
As part of this release, we’re now using the latest version of Eclipse (version 3.6.1 “Helios”) as the base for Flash Builder and hence all the improvements and bug fixes made in Eclipse are now visible to Flash Builder users. In addition, on Mac OS X we’ve updated Flash Builder to use the “Cocoa” version of Eclipse and are removing support for the older “Carbon” version.
Flash Builder also includes the latest support for Adobe technologies—including Adobe Flex SDK 4.5, Adobe AIR 2.6, and Flash Player 10.2. For non-mobile projects, Adobe Flex SDK 4.5 introduces Spark versions of the Form, Image and DataGrid components, all of which are supported in Flash Builder 4.5. For more information on Adobe Flex 4.5 SDK please read Deepa Subramaniam’s article on the Adobe Developer Connection site.
One area in which we have made improvements that may not be immediately obvious is in relation to the architecture of Flash Builder and the installer. There are no longer separate downloads for the standalone and plug-in versions (where you add Flash Builder to an existing Eclipse instance); instead, after installation of the standalone version, you use a small utility (found in the utilities directory) to configure Flash Builder to work with one or more existing versions of Eclipse.
In addition to updated platform support, we also spent a considerable amount of time examining large customer projects in Flash Builder to see where performance and memory usage can be improved. We identified three specific areas where significant improvements could be made - design view, refactoring and profiling. For the latter two areas, you will find that the time taken to complete operations has reduced by up to 65%, making it far more productive to work with projects that have a large number of source files or multiple dependent library projects. Design view has undergone a major overhaul in Flash Builder 4.5, reducing the time taken to switch from code to design view and making it robust enough to render complex projects.
There are a number of other features and minor enhancements that we’ve added to this release, based on customer feedback and feature requests we received through the Adobe Ideas site. Here are some of the improvements:
In addition to the great features and improvements already mentioned in this article, we’re also introducing a new version of Flash Builder aimed specifically at PHP developers. Flash Builder 4.5 for PHP is an integration of Flash Builder 4.5 and Zend Studio 8 that streamlines the development process for building web and mobile applications using Flex and PHP. The features include an integrated installer, new project wizards, improved connection to PHP services, and joint debugging workflows. For more information about this exciting new product, please read the article Introducing Flash Builder 4.5 for PHP.
For more information on the new features in Flash Builder 4.5, Flash Catalyst CS5.5, or Flex 4.5 SDK, check out the Adobe Developer Connection. You can also watch Serge Jespers's accompanying video to learn more about Flash Builder 4.5.
We hope that you're as excited as we are about this release—the entire product team looks forward to seeing what you build using Flash Builder. | http://www.adobe.com/devnet/flash-builder/articles/whatsnew-flashbuilder-45.html?devcon=f1a | CC-MAIN-2013-20 | refinedweb | 1,821 | 50.06 |
Synopsis editsource filenamesource -encoding encodingName fileName
Documentation edit
See Also edit
- gets
- read
- open
- encoding
- source with args
- stepsource.tcl
- run
- pre-processing for source
- Overloaded source for C-style comments
- \u001a is an end-of-file character in scripts
- about the use of ^Z
- sourcecache
, by David Welton
- acts as source does, but with caching. This is useful, as he notes, "for applications such as web servers running dynamic pages ..."
- how to change a running system
- RS: source is the weakest way of . Relying on auto_index or package mechanisms is more robust, and easier once set up - do nothing (maybe extend auto_path), or package require.
Description edit[source] arranges for the Tcl interpreter to evaluate the contents of the specified file or resource exactly as if [eval] were called at that point with an argument identical to the the literal content of the given file, up to the first occurrence of ^Z
If an error occurs in evaluating the contents of the script then the[source] will have an error status its value will be that error.'\32' (dec 26) (^Z) is used as the end-of-stream character for all platforms. [source] reads only up to the first instance of character. This restriction does not exist for the [read] or [gets], allowing files to contain both containing code and data segments. If you require a "^Z" in code for string comparison, you can use "\032" or "\u001a", which will be safely substituted by the Tcl interpreter into "^Z".filename is normally read using the system encoding, but this can be overridden with the -encoding option.
Ensure that a file is only sourced onceJoe Mistachkin 2003-08-25: The following proc will source a file only once:
proc sourceOnce { file } { upvar "1" sources sources if {![info exists sources([file normalize $file])]} then { # don't catch errors, since that may indicate we failed to load it...? uplevel "1" [list source $file] # mark it as loaded since it was source'd with no error... set sources([file normalize $file]) "1" } }DGP: I don't think that quite works. Different callers might well refer to different sources arrays. Better to encapsulate all in the same namespace.
namespace eval my { namespace export sourceOnce variable sources array set sources {} proc sourceOnce { file } { # Remaining exercise for the next reader. Adapt argument # processing to support the -rsrc and -encoding options # that [::source] provides (or will in Tcl 8.5) variable sources if {![info exists sources([file normalize $file])]} then { # don't catch errors, since that may indicate we failed to load it...? # Extra challenge: Use the techniques outlined in TIP 90 # to catch errors, then re-raise them so the [uplevel] does # not appear on the stack trace. # We don't know what command is [source] in the caller's context, # so fully qualify to get the [::source] we want. uplevel 1 [list ::source $file] # mark it as loaded since it was source'd with no error... set sources([file normalize $file]) 1 } } } namespace import my::sourceOnceelfring 2003-08-26: The discussion about the function "sourceOnce" is a continuation of feature request #301: Include source files only once
Making Use of Environment PATHRS: /bin/sh-like source: When playing Bourne shell, I found out that their source command "." searches the environment PATH, a feature that has occasionally been missed in Tcl's source. Well, here's an emulation (that caters for Unix/Win differences as well):
proc path'separator {} { switch -- $::tcl_platform(platform) { unix {return ":"} windows {return ";"} default {error "unknown platform"} } } if {[llength [info global tk*]]==0} { # The name . is taboo in a wish, would exit immediately proc . filename { foreach path [split $::env(PATH) [path'separator]] { set try [file join $path $filename] if [file readable $try] {return [source $try]} } error ".: no such file or directory: $filename" } } ;# RS
Evaluate Channel Contents
proc sourceOpen {channel} { while 1 { append line [gets $channel line] if {[info complete $line]} { eval $line } if {[eof $channel]} break } }PYK: This will behave differently from [source] in various ways: ^Z won't be respected, lines will be evaluated within the scope of sourceOpen instead of its caler, and treatment of [return] will be different.
Evalate Channel Contents in Chunkshans 2008-02-25: [source] reads the whole file into memory first before eval'ing. I'm saving updates to a large tcl source file whenever any vars change, so the "tape" file can become quite large. Of course the memory is freed after sourcing, but still there is a huge spike.Here's my solution. After every update to my data.tcl file, I'm inserting a line with: "#~". Of course, I have to escape that special char everywhere. Now it's easy to read and eval the huge file in chunks, timing is very close to that of source.
proc load_data {fname} { set f [open $fname r] fconfigure $f -translation binary \ -buffersize 1000000 -encoding "iso8859-1" while {![eof $f]} { set r [read $f 1000000] set l [string length $r] set c [string last "~" $r] while {$c eq -1} { if {[eof $f]} { error "Missing ~" } set r2 [read $f 1000000] append r $r2 set l [string length $r] set c [string last "~" $r] } set e [string range $r 0 $c] uplevel #0 eval $e seek $f [expr $c-$l-1] current if {$l<1000000} { break } } close $f }Perhaps someone will come along and help out with error handling and plug logic holes here...
Determining whether the current script was sourced editArjen Markus: Sometimes it is useful to distinguish between the Tcl/Tk shell sourcing the file (as in tclsh aa.tcl) and the script being evaluated to do this (via the command "source aa.tcl"). This can be used to:
- Provide a library of useful procedures and
- Provide a self-contained "main" proc in the same file
tclsh numcomp.tcl a.inp b.inpthe main proc gets executed and the comparison is started. If sourced inside another script, however, this is not done and the sourcing script has full control. (In this case: it is a larger script controlling a number of programs whose results must be compared against reference files).The trick is the code below:
if { [info script] eq $::argv0 } { puts {In main} } else { puts {Sourcing [info script]} }
[return] in a sourced file editArjen Markus: Another trick I recently learned: [return] works in source as in any other script - it allows you to return from the source command, so that the rest of the file is not handled. Quite useful for recovering from errors or making the processing depend on external influences.
Examples edit
loading dataYou can also source (almost) pure data files like this:
array set data [source datafile]where datafile contains:
return { 1 {some data} 2 {other data} . ... foo {note that the element name does not have to be numeric} }results in:
% parray data data(.) = ... data(1) = some data data(2) = other data data(foo) = note that the element name does not have to be numeric
Multiple filesJust [glob] the files you want, and [source] them all.
foreach x [glob -dir $myDirectory *.tcl] { source $x }
Exclude myself when sourcing everything in my directoryIf you want to have it load all scripts in its own directory, instead of that "source $x" do an "if $x not itself.."
Encoding editNotice that sourcing is always done in the system encoding. For sources in Unicode or other goodies you'd have to open a file, fconfigure -encoding, read, eval, close - see Unicode file reader or source with encoding. source $file does something like:
set fp [open $file] set data [read $fp] close $fp eval $data | http://wiki.tcl.tk/1113 | CC-MAIN-2014-15 | refinedweb | 1,257 | 58.32 |
Providers¶
The provider is how web3 talks to the blockchain. Providers take JSON-RPC requests and return the response. This is normally done by submitting the request to an HTTP or IPC socket based server.
If you are already happily connected to your Ethereum node, then you can skip the rest of the Providers section.
Choosing How to Connect to Your Node¶
Most nodes have a variety of ways to connect to them. If you have not decided what kind of node to use, head on over to How do I choose which node to use?
The most common ways to connect to your node are:
- IPC (uses local filesystem: fastest and most secure)
- Websockets (works remotely, faster than HTTP)
- HTTP (more nodes support it)
If you’re not sure how to decide, choose this way:
- If you have the option of running Web3.py on the same machine as the node, choose IPC.
- If you must connect to a node on a different computer, use Websockets.
- If your node does not support Websockets, use HTTP.
Most nodes have a way of “turning off” connection options. We recommend turning off all connection options that you are not using. This provides a safer setup: it reduces the number of ways that malicious hackers can try to steal your ether.
Once you have decided how to connect, you specify the details using a Provider. Providers are Web3.py classes that are configured for the kind of connection you want.
See:
Once you have configured your provider, for example:
from web3 import Web3 my_provider = Web3.IPCProvider('/my/node/ipc/path')
Then you are ready to initialize your Web3 instance, like so:
w3 = Web3(my_provider)
Finally, you are ready to get started with Web3.py.
Automatic vs Manual Providers¶
The
Web3 object will look for the Ethereum node in a few
standard locations if no providers are specified. Auto-detection happens
when you initialize like so:
from web3.auto import w3 # which is equivalent to: from web3 import Web3 w3 = Web3()
Sometimes, web3 cannot automatically detect where your node is.
- If you are not sure which kind of connection method to use, see Choosing How to Connect to Your Node.
- If you know the connection method, but not the other information needed to connect (like the path to the IPC file), you will need to look up that information in your node’s configuration.
- If you’re not sure which node you are using, see How do I choose which node to use?
For a deeper dive into how automated detection works, see:
How Automated Detection Works¶
Web3 attempts to connect to nodes in the following order, using the first succesful connection it can make:
- The connection specified by an environment variable, see Provider via Environment Variable
IPCProvider, which looks for several IPC file locations. IPCProvider will not automatically detect a testnet connection, it is suggested that the user instead uses a w3 instance from web3.auto.infura (e.g. from web3.auto.infura.ropsten import w3) if they want to auto-detect a testnet.
HTTPProvider, which attempts to connect to “”
- None - if no providers are successful, you can still use Web3 APIs that do not require a connection, like:
Examples Using Automated Detection¶
Some nodes provide APIs beyond the standards. Sometimes the same information is provided in different ways across nodes. If you want to write code that works across multiple nodes, you may want to look up the node type you are connected to.
For example, the following retrieves the client enode endpoint for both geth and parity:
from web3.auto import w3 connected = w3.isConnected() if connected and w3.version.node.startswith('Parity'): enode = w3.parity.enode elif connected and w3.version.node.startswith('Geth'): enode = w3.geth.admin.nodeInfo['enode'] else: enode = None
Provider via Environment Variable¶
Alternatively, you can set the environment variable
WEB3_PROVIDER_URI
before starting your script, and web3 will look for that provider first.
Valid formats for this environment variable are:
ws://127.0.0.1:8546
Auto-initialization Provider Shortcuts¶
There are a couple auto-initialization shortcuts for common providers.
Infura Mainnet¶
To easily connect to the Infura Mainnet remote node, first register for a free project ID if you don’t have one at .
Then set the environment variable
WEB3_INFURA_PROJECT_ID with your Project ID:
$ export WEB3_INFURA_PROJECT_ID=YourProjectID
If you have checked the box in the Infura UI indicating that requests need
an optional secret key, set the environment variable
WEB3_INFURA_API_SECRET:
$ export WEB3_INFURA_API_SECRET=YourProjectSecret
>>> from web3.auto.infura import w3 # confirm that the connection succeeded >>> w3.isConnected() True
Built In Providers¶
Web3 ships with the following providers which are appropriate for connecting to local and remote JSON-RPC servers.
HTTPProvider¶
- class
web3.providers.rpc.
HTTPProvider(endpoint_uri[, request_kwargs])¶
This provider handles interactions with an HTTP or HTTPS based JSON-RPC server.
endpoint_urishould be the full URI to the RPC endpoint such as
''. For RPC servers behind HTTP connections running on port 80 and HTTPS connections running on port 443 the port can be omitted from the URI.
request_kwargsthis should be a dictionary of keyword arguments which will be passed onto the http/https request.
>>> from web3 import Web3 >>> w3 = Web3(Web3.HTTPProvider(""))
Note that you should create only one HTTPProvider per python process, as the HTTPProvider recycles underlying TCP/IP network connections, for better performance.
Under the hood, the
HTTPProvideruses the python requests library for making requests. If you would like to modify how requests are made, you can use the
request_kwargsto do so. A common use case for this is increasing the timeout for each request.
>>> from web3 import Web3 >>> w3 = Web3(Web3.HTTPProvider("", request_kwargs={'timeout': 60}))
IPCProvider¶
- class
web3.providers.ipc.
IPCProvider(ipc_path=None, testnet=False, timeout=10)¶
This provider handles interaction with an IPC Socket based JSON-RPC server.
ipc_pathis the filesystem path to the IPC socket.:56
>>> from web3 import Web3 >>> w3 = Web3(Web3.IPCProvider("~/Library/Ethereum/geth.ipc"))
If no
ipc_pathis specified, it will use the first IPC file it can find from this list:
- On Linux and FreeBSD:
~/.ethereum/geth.ipc
~/.local/share/io.parity.ethereum/jsonrpc.ipc
- On Mac OS:
~/Library/Ethereum/geth.ipc
~/Library/Application Support/io.parity.ethereum/jsonrpc.ipc
- On Windows:
\\\.\pipe\geth.ipc
\\\.\pipe\jsonrpc.ipc
WebsocketProvider¶
- class
web3.providers.websocket.
WebsocketProvider(endpoint_uri[, websocket_kwargs])¶
This provider handles interactions with an WS or WSS based JSON-RPC server.
endpoint_urishould be the full URI to the RPC endpoint such as
'ws://localhost:8546'.
websocket_kwargsthis should be a dictionary of keyword arguments which will be passed onto the ws/wss websocket connection.
>>> from web3 import Web3 >>> w3 = Web3(Web3.WebsocketProvider("ws://127.0.0.1:8546"))
Under the hood, the
WebsocketProvideruses the python websockets library for making requests. If you would like to modify how requests are made, you can use the
websocket_kwargsto do so. A common use case for this is increasing the timeout for each request.
>>> from web3 import Web3 >>> w3 = Web3(Web3.WebsocketProvider("", websocket_kwargs={'timeout': 60}))
EthereumTesterProvider¶
Warning
Experimental: This provider is experimental. There are still significant gaps in functionality. However it is being actively developed and supported.
- class
web3.providers.eth_tester.
EthereumTesterProvider(eth_tester=None)¶
This provider integrates with the
eth-testerlibrary. The
eth_testerconstructor argument should be an instance of the
EthereumTesteror a subclass of
BaseChainBackendclass provided by the
eth-testerlibrary. If you would like a custom eth-tester instance to test with, see the
eth-testerlibrary documentation for details.
>>> from web3 import Web3, EthereumTesterProvider >>> w3 = Web3(EthereumTesterProvider())
Note
To install the needed dependencies to use EthereumTesterProvider, you can install the
pip extras package that has the correct interoperable versions of the
eth-tester
and
py-evm dependencies needed to do testing: e.g.
pip install web3[tester] | https://web3py.readthedocs.io/en/stable/providers.html | CC-MAIN-2019-43 | refinedweb | 1,282 | 56.66 |
Monitor.Wait Method (Object, Int32)
April 12, 2014.
- millisecondsTimeout
- Type: System.Int32
The number of milliseconds to wait before the thread enters the ready queue. on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object.. demonstrates how to use the Wait method with a time-out. The method times out when the Producer thread is no longer supplying new values.
using System; using System.Threading; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Input; using System.Windows.Controls; class Example { const int MAX_ITERATIONS = 100; // Example data: A BackgroundWorker that reports progress to the user // interface thread, the queue that is protected by the lock, and a // random number generator. private BackgroundWorker m_worker = new BackgroundWorker(); private Queue<int> m_smplQueue = new Queue<int>(); private Random m_random = new Random(); // This thread does work and produces a result (in this case just a // number). private void Producer() { int counter = 0; lock (m_smplQueue) { while (counter < MAX_ITERATIONS) { // Wait, if the queue is busy. Monitor.Wait(m_smplQueue); // Simulate a small amount of work, then queue one element // and release the waiting thread. Thread.Sleep(10 + m_random.Next(10)); m_smplQueue.Enqueue(counter); Monitor.Pulse(m_smplQueue); counter += 1; } } } // This thread consumes the result produced by the first thread. It // could do additional processing, but in this case it just reports // the number. private void Consumer() {. m_worker.ReportProgress(0, String.Format("{0} ", counter)); // Release the waiting thread. Monitor.Pulse(m_smplQueue); } } } // ------------------- // This section contains supporting code that runs the example on a // background thread, so it doesn't block the UI thread, and enables // the example to display output using Windows Phone UI elements. There // is no example code for Monitor in this section. // This UI element receives the output from the example. It's the same // for all instances of Example. private static TextBlock outputBlock; // A list of all Example objects that are currently running. private static List<Example> examples = new List<Example>(); // The Demo method saves the TextBlock used for output, and sets up a // mouse event that you click to run instances of the demonstration. // public static void Demo(TextBlock outputBlock) { Example.outputBlock = outputBlock; outputBlock.Text += "Click here to begin running the example.\r\n"; // Set up an event handler to run the example when the TextBlock // is clicked. outputBlock.MouseLeftButtonUp += MouseUp; } // This mouse event gives visual feedback and starts a new instance of // Example. The instance must be started on the UI thread, so that the // BackgroundWorker raises its events on the UI thread. // private static void MouseUp(object sender, MouseButtonEventArgs e) { outputBlock.Text += "<Click> "; examples.Add(new Example()); } // Each new Example sets up the events for its background task and // launches the task. It also creates a unique ID number. // private int m_id; private static int lastId = 0; public Example() { m_id = Interlocked.Increment(ref lastId); m_worker.DoWork += this.RunExample; m_worker.WorkerReportsProgress = true; m_worker.ProgressChanged += this.Progress; m_worker.RunWorkerCompleted += this.Completed; m_worker.RunWorkerAsync(); } // Launch the producer and consumer threads. private void RunExample(object sender, DoWorkEventArgs e) { // Create the threads and start them. Thread tProducer = new Thread(this.Producer); Thread tConsumer = new Thread(this.Consumer); tProducer.Start(); Thread.Sleep(1); tConsumer.Start(); // Wait until the two threads end. tProducer.Join(); tConsumer.Join(); // When the task completes, return the Example object. e.Result = this; } // The display output that is queued using the ReportProgress method // is delivered to the UI thread by this event handler. // private void Progress(object sender, ProgressChangedEventArgs e) { // This code is executed on the main UI thread, so it's safe to // access the UI elements. outputBlock.Text += e.UserState.ToString(); } // This event handler signals task completion to the UI thread. It // removes the Example object from the list and displays its count. // private void Completed(object sender, RunWorkerCompletedEventArgs e) { examples.Remove(this); outputBlock.Text += String.Format("<Example({0}) Queue Count = {1}> ", m_id, m_smplQueue.Count); } } /* This code produces output similar to the following: Click here to begin running the example. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <Click> 31 32 33 0 34 1 35 2 36 3 37 38 4 5 39 6 40 7 41 8 42 43 9 10 44 45 11 46 12 13 47 48 14 49 15 50 16 51 17 52 18 53 19 54 20 55 21 56 22 57 23 24 58 25 59 26 60 27 28 61 29 62 30 31 63 64 32 33 65 34 66 35 67 36 68 37 69 38 39 70 71 40 41 72 42 73 74 43 75 44 76 77 45 46 78 47 79 48 80 49 81 50 82 51 83 52 84 53 85 54 86 55 87 56 88 57 89 58 90 59 91 60 92 61 93 62 94 63 95 64 65 96 97 66 98 67 99 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 <Example(1) Queue Count = 0> <Example(2) Queue Count = 0> */ | http://msdn.microsoft.com/en-US/library/windowsphone/develop/syehfawa(v=vs.105).aspx | CC-MAIN-2014-15 | refinedweb | 880 | 64.61 |
Auto Layout was introduced in OS X 10.7, and one year later it made its way into iOS 6. Soon apps on iOS 7 will be expected to honor the systemwide font size setting, thus requiring even more flexibility in the user interface layout next to different screen sizes and orientations. Apple is doubling down on Auto Layout, so now is a good time to get your feet wet if you haven’t done so yet.
Many developers struggle with Auto Layout when first trying it, because of the often-frustrating experience of building constraint-based layouts with Xcode 4’s Interface Builder. But don’t let yourself be discouraged by that; Auto Layout is much better than Interface Builder’s current support for it. Xcode 5 will bring some major relief in this area.
This article is not an introduction to Auto Layout. If you haven’t worked with it yet, we encourage you to watch the Auto Layout sessions from WWDC 2012 (202 – Introduction to Auto Layout for iOS and OS X, 228 – Best Practices for Mastering Auto Layout, 232 – Auto Layout by Example). These are excellent introductions to the topic which cover a lot of ground.
Instead, we are going to focus on several advanced tips and techniques, which enhance productivity with Auto Layout and make your (development) life easier. Most of these are touched upon in the WWDC sessions mentioned above, but they are the kind of things that are easy to oversee or forget while trying to get your daily work done.
The Layout Process
First we will recap the steps it takes to bring views on screen with Auto Layout enabled. When you’re struggling to produce the kind of layout you want with Auto Layout, specifically with advanced use cases and animation, it helps to take a step back and to recall how the layout process works.
Compared to working with springs and struts, Auto Layout introduces two additional steps to the process before views can be displayed: updating constraints and laying out views. Each step is dependent on the one before; display depends on layout, and layout depends on updating constraints.
The first step – updating constraints – can be considered a “measurement pass.” It happens bottom-up (from subview to super view) and prepares the information needed for the layout pass to actually set the views’ frame. You can trigger this pass by calling
setNeedsUpdateConstraints. Any changes you make to the system of constraints itself will automatically trigger this. However, it is useful to notify Auto Layout about changes in custom views that could affect the layout. Speaking of custom views, you can override
updateConstraints to add the local constraints needed for your view in this phase.
The second step – layout – happens top-down (from super view to subview). This layout pass actually applies the solution of the constraint system to the views by setting their frames (on OS X) or their center and bounds (on iOS). You can trigger this pass by calling
setNeedsLayout, which does not actually go ahead and apply the layout immediately, but takes note of your request for later. This way you don’t have to worry about calling it too often, since all the layout requests will be coalesced into one layout pass.
To force the system to update the layout of a view tree immediately, you can call
layoutIfNeeded/
layoutSubtreeIfNeeded (on iOS and OS X respectively). This can be helpful if your next steps rely on the views’ frame being up to date. In your custom views you can override
layoutSubviews/
layout to gain full control over the layout pass. We will show use cases for this later on.
Finally, the display pass renders the views to screen and is independent of whether you’re using Auto Layout or not. It operates top-down and can be triggered by calling
setNeedsDisplay, which results in a deferred redraw coalescing all those calls. Overriding the familiar
drawRect: is how you gain full control over this stage of the display process in your custom views.
Since each step depends on the one before it, the display pass will trigger a layout pass if any layout changes are pending. Similarly, the layout pass will trigger updating the constraints if the constraint system has pending changes.
It’s important to remember that these three steps are not a one-way street. Constraint-based layout is an iterative process. The layout pass can make changes to the constraints based on the previous layout solution, which again triggers updating the constraints following another layout pass. This can be leveraged to create advanced layouts of custom views, but you can also get stuck in an infinite loop if every call of your custom implementation of
layoutSubviews results in another layout pass.
Enabling Custom Views for Auto Layout
When writing a custom view, you need to be aware of the following things with regard to Auto Layout: specifying an appropriate intrinsic content size, distinguishing between the view’s frame and alignment rect, enabling baseline-aligned layout, and how to hook into the layout process. We will go through these aspects one by one.
Intrinsic Content Size
The intrinsic content size is the size a view prefers to have for a specific content it displays. For example,
UILabel has a preferred height based on the font, and a preferred width based on the font and the text it displays. A
UIProgressView only has a preferred height based on its artwork, but no preferred width. A plain
UIView has neither a preferred width nor a preferred height.
You have to decide, based on the content to be displayed, if your custom view has an intrinsic content size, and if so, for which dimensions.
To implement an intrinsic content size in a custom view, you have to do two things: override
intrinsicContentSize to return the appropriate size for the content, and call
invalidateIntrinsicContentSize whenever something changes which affects the intrinsic content size. If the view only has an intrinsic size for one dimension, return
UIViewNoIntrinsicMetric/
NSViewNoIntrinsicMetric for the other one.
Note that the intrinsic content size must be independent of the view’s frame. For example, it’s not possible to return an intrinsic content size with a specific aspect ratio based on the frame’s height or width.
Compression Resistance and Content Hugging
Each view has content compression resistance priorities and content hugging priorities assigned for both dimensions. These properties only take effect for views which define an intrinsic content size, otherwise there is no content size defined that could resist compression or be hugged.
Behind the scenes, the intrinsic content size and these priority values get translated into constraints. For a label with an intrinsic content size of
{ 100, 30 }, horizontal/vertical compression resistance priority of
750, and horizontal/vertical content hugging priority of
250, four constraints will be generated:
H:[label(<=100@250)] H:[label(>=100@750)] V:[label(<=30@250)] V:[label(>=30@750)]
If you’re not familiar with the visual format language for the constraints used above, you can read up about it in Apple’s documentation. Keeping in mind that these additional constraints are generated implicitly helps to understand Auto Layout’s behavior and to make better sense of its error messages.
Frame vs. Alignment Rect
Auto Layout does not operate on views’ frame, but on their alignment rect. It’s easy to forget the subtle difference, because in many cases they are the same. But alignment rects are actually a powerful new concept that decouple a view’s layout alignment edges from its visual appearance.
For example, a button in the form of a custom icon that is smaller than the touch target we want to have would normally be difficult to lay out. We would have to know about the dimensions of the artwork displayed within a larger frame and adjust the button’s frame accordingly, so that the icon lines up with other interface elements. The same happens if we want to draw custom ornamentation around the content, like badges, shadows, and reflections.
Using alignment rects we can easily define the rectangle which should be used for layout. In most cases you can just override the
alignmentRectInsets method, which lets you return edge insets relative to the frame. If you need more control you can override the methods
alignmentRectForFrame: and
frameForAlignmentRect:. This can be useful if you want to calculate the alignment rect based on the current frame value instead of just subtracting fixed insets. But you have to make sure that these two methods are inverses of each other.
In this context it is also good to recall that the aforementioned intrinsic content size of a view refers to its alignment rect, not to its frame. This makes sense, because Auto Layout generates the compression resistance and content hugging constraints straight from the intrinsic content size.
Baseline Alignment
To enable constraints using the
NSLayoutAttributeBaseline attribute to work on a custom view, we have to do a little bit of extra work. Of course this only makes sense if the custom view in question has something like a baseline.
On iOS, baseline alignment can be enabled by implementing
viewForBaselineLayout. The bottom edge of the view you return here will be used as baseline. The default implementation simply returns self, while a custom implementation can return any subview. On OS X you don’t return a subview but an offset from the view’s bottom edge by overriding
baselineOffsetFromBottom, which has the same default behavior as its iOS counterpart by returning 0 in its default implementation.
Taking Control of Layout
In a custom view you have full control over the layout of its subviews. You can add local constraints, you can change local constraints if a change in content requires it, you can fine-tune the result of the layout pass for subviews, or you can opt out of Auto Layout altogether.
Make sure though that you use this power wisely. Most cases can be handled by simply adding local constraints for your subviews.
Local Constraints
If we want to compose a custom view out of several subviews, we have to lay out these subviews somehow. In an Auto Layout environment it is most natural to add local constraints for these views. However, note that this makes your custom view dependent on Auto Layout, and it cannot be used anymore in windows without Auto Layout enabled. It’s best to make this dependency explicit by implementing
requiresConstraintBasedLayout to return
YES.
The place to add local constraints is
updateConstraints. Make sure to invoke
[super updateConstraints] in your implementation after you’ve added whatever constraints you need to lay out the subviews. In this method, you’re not allowed to invalidate any constraints, because you are already in the first step of the layout process described above. Trying to do so will generate a friendly error message informing you that you’ve made a “programming error.”
If something changes later on that invalidates one of your constraints, you should remove the constraint immediately and call
setNeedsUpdateConstraints. In fact, that’s the only case where you should have to trigger a constraint update pass.
Control Layout of Subviews
If you cannot use layout constraints to achieve the desired layout of your subviews, you can go one step further and override
layoutSubviews on iOS or
layout on OS X. This way, you’re hooking into the second step of the layout process, when the constraint system has already been solved and the results are being applied to the view.
The most drastic approach is to override
layoutSubviews/
layout without calling the super class’s implementation. This means that you’re opting out of Auto Layout for the view tree within this view. From this point on, you can position subviews manually however you like.
If you still want to use constraints to lay out subviews, you have to call
[super layoutSubviews]/
[super layout] and make fine-tuned adjustments to the layout afterwards. You can use this to create layouts which are not possible to define using constraints, for example layouts involving relationships between the size and the spacing between views.
Another interesting use case for this is to create a layout-dependent view tree. After Auto Layout has done its first pass and set the frames on your custom view’s subviews, you can inspect the positioning and sizing of these subviews and make changes to the view hierarchy and/or to the constraints. WWDC session 228 – Best Practices for Mastering Auto Layout has a good example of this, where subviews are removed after the first layout pass if they are getting clipped.
You could also decide to change the constraints after the first layout pass. For example, switch from lining up subviews in one row to two rows, if the views are becoming too narrow.
- layoutSubviews { [super layoutSubviews]; if (self.subviews[0].frame.size.width <= MINIMUM_WIDTH) { [self removeSubviewConstraints]; self.layoutRows += 1; [super layoutSubviews]; } } - updateConstraints { // add constraints depended on self.layoutRows... [super updateConstraints]; }
Intrinsic Content Size of Multi-Line Text
The intrinsic content size of
UILabel and
NSTextField is ambiguous for multi-line text. The height of the text depends on the width of the lines, which is yet to be determined when solving the constraints. In order to solve this problem, both classes have a new property called
preferredMaxLayoutWidth, which specifies the maximum line width for calculating the intrinsic content size.
Since we usually don’t know this value in advance, we need to take a two-step approach to get this right. First we let Auto Layout do its work, and then we use the resulting frame in the layout pass to update the preferred maximum width and trigger layout again.
- (void)layoutSubviews { [super layoutSubviews]; myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width; [super layoutSubviews]; }
The first call to
[super layoutSubviews] is necessary for the label to get its frame set, while the second call is necessary to update the layout after the change. If we omit the second call we get a
NSInternalInconsistencyException error, because we’ve made changes in the layout pass which require updating the constraints, but we didn’t trigger layout again.
We can also do this in a label subclass itself:
@implementation MyLabel - (void)layoutSubviews { self.preferredMaxLayoutWidth = self.frame.size.width; [super layoutSubviews]; } @end
In this case, we don’t need to call
[super layoutSubviews] first, because when
layoutSubviews gets called, we already have a frame on the label itself.
To make this adjustment from the view controller level, we hook into
viewDidLayoutSubviews. At this point the frames of the first Auto Layout pass are already set and we can use them to set the preferred maximum width.
- (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width; [self.view layoutIfNeeded]; }
Lastly, make sure that you don’t have an explicit height constraint on the label that has a higher priority than the label’s content compression resistance priority. Otherwise it will trump the calculated height of the content.
Animation
When it comes to animating views laid out with Auto Layout, there are two fundamentally different strategies: Animating the constraints themselves, and changing the constraints to recalculate the frames and use Core Animation to interpolate between the old and the new position.
The difference between the two approaches is that animating constraints themselves results in a layout that conforms to the constraint system at all times. Meanwhile, using Core Animation to interpolate between old and new frames violates constraints temporarily.
Directly animating constraints is really only a feasible strategy on OS X, and it is limited in what you can animate, since only a constraint’s constant can be changed after creating it. On iOS you would have to drive the animation manually, whereas on OS X you can use an animator proxy on the constraint’s constant. Furthermore, this approach is significantly slower than the Core Animation approach, which also makes it a bad fit for mobile platforms for the time being.
When using the Core Animation approach, animation conceptually works the same way as without Auto Layout. The difference is that you don’t set the views’ target frames manually, but instead you modify the constraints and trigger a layout pass to set the frames for you. On iOS, instead of:
[UIView animateWithDuration:1 animations:^{ myView.frame = newFrame; }];
you now write:
// update constraints [UIView animateWithDuration:1 animations:^{ [myView layoutIfNeeded]; }];
Note that with this approach, the changes you can make to the constraints are not limited to the constraints’ constants. You can remove constraints, add constraints, and even use temporary animation constraints. Since the new constraints only get solved once to determine the new frames, even more complex layout changes are possible.
The most important thing to remember when animating views using Core Animation in conjunction with Auto Layout is to not touch the views’ frame yourself. Once a view is laid out by Auto Layout, you’ve transferred the responsibility to set its frame to the layout system. Interfering with this will result in weird behavior.
This means also that view transforms don’t always play nice with Auto Layout if they change the view’s frame. Consider the following example:
[UIView animateWithDuration:1 animations:^{ myView.transform = CGAffineTransformMakeScale(.5, .5); }];
Normally we would expect this to scale the view to half its size while maintaining its center point. But the behavior with Auto Layout depends on the kind of constraints we have set up to position the view. If we have it centered within its super view, the result is as expected, because applying the transform triggers a layout pass which centers the new frame within the super view. However, if we have aligned the left edge of the view to another view, then this alignment will stick and the center point will move.
Anyway, applying transforms like this to views laid out with constraints is not a good idea, even if the result matches our expectations at first. The view’s frame gets out of sync with the constraints, which will lead to strange behavior down the road.
If you want to use transforms to animate a view or otherwise animate its frame directly, the cleanest technique to do this is to embed the view into a container view. Then you can override
layoutSubviews on the container, either opting out of Auto Layout completely or only adjusting its result. For example, if we setup a subview in our container which is laid out within the container at its top and left edges using Auto Layout, we can correct its center after the layout happens to enable the scale transform from above:
- (void)layoutSubviews { [super layoutSubviews]; static CGPoint center = {0,0}; if (CGPointEqualToPoint(center, CGPointZero)) { // grab the view's center point after initial layout center = self.animatedView.center; } else { // apply the previous center to the animated view self.animatedView.center = center; } }
If we expose the
animatedView property as an IBOutlet, we can even use this container within Interface Builder and position its subview with constraints, while still being able to apply the scale transform with the center staying fixed.
Debugging
When it comes to debugging Auto Layout, OS X still has a significant advantage over iOS. On OS X you can make use of Instrument’s Cocoa Layout template, as well as
NSWindow’s
visualizeConstraints: method. Furthermore,
NSView has an
identifier property, which you can set from Interface Builder or in code, in order to get much more readable Auto Layout error messages.
Unsatisfiable Constraints
If we run into unsatisfiable constraints on iOS, we only see the views’ memory addresses in the printout. Especially in more complex layouts, it’s sometimes difficult to identify the views which are part of the problem. However, there are several ways we can help ourselves in this situation.
First, whenever you see
NSLayoutResizingMaskConstraints in the unsatisfiable constraints error message, you almost certainly forgot to set
translatesAutoResizingMaskIntoConstraints to
NO for one of your views. While Interface Builder does this automatically, you have to do this manually for all views created in code.
If it’s not obvious which views are causing the trouble, you have to identify the view by its memory address. The most straightforward option is to use the debugger console. You can print out the description of the view itself or its super view, or even the recursive description of the view tree. This mostly gives you lots of cues to identify which view you’re dealing with.
>>
A more visual approach is to modify the view in question from the console so that you can spot it on screen. For example, you can do this by changing its background color:
(lldb) expr ((UIView *)0x7731880).backgroundColor = [UIColor purpleColor]
Make sure to resume the execution of your app afterward or the changes will not show up on screen. Also note the cast of the memory address to
(UIView *) and the extra set of round brackets so that we can use dot notation. Alternatively, you can of course also use message sending notation:
(lldb) expr [(UIView *)0x7731880 setBackgroundColor:[UIColor purpleColor]]
Another approach is to profile the application with Instrument’s allocations template. Once you’ve got the memory address from the error message (which you have to get out of the Console app when running Instruments), you can switch Instrument’s detail view to the Objects List and search for the address with Cmd-F. This will show you the method which allocated the view object, which is often a pretty good hint of what you’re dealing with (at least for views created in code).
You can also make deciphering unsatisfiable constraints errors on iOS easier by improving the error message itself. We can overwrite
NSLayoutConstraint’s description method in a category to include the views’ tags:
tag], [self.secondItem tag]]; } #endif @end
If the integer property
tag is not enough information, we can also get a bit more adventurous and add our own nametag property to the view class, which we then print out in the error message. We can even assign values to this custom property in Interface Builder using the “User Defined Runtime Attributes” section in the identity inspector.
@interface UIView (AutoLayoutDebugging) - (void)setAbc_NameTag:(NSString *)nameTag; - (NSString *)abc_nameTag; @end @implementation UIView (AutoLayoutDebugging) - (void)setAbc_NameTag:(NSString *)nameTag { objc_setAssociatedObject(self, "abc_nameTag", nameTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (NSString *)abc_nameTag { return objc_getAssociatedObject(self, "abc_nameTag"); } @end abc_nameTag], [self.secondItem abc_nameTag]]; } #endif @end
This way the error message becomes much more readable and you don’t have to find out which view belongs to which memory address. However, it requires some extra work on your part to consistently assign meaningful names to the views.
Another neat trick (via Daniel) that gives you better error messages without requiring extra work is to integrate call stack symbols into the error message for each layout constraint. This makes it easy to see where the constraints involved in the problem were created. To do this, you have to swizzle the
addConstraint: and
addConstraints: methods of
UIView or
NSView, as well as the layout constraint’s
description method. In the methods for adding constraints, you should then add an associated object to each constraint, which describes the first frame of the current call stack backtrace (or whatever information you would like to have from it):
static void AddTracebackToConstraints(NSArray *constraints) { NSArray *a = [NSThread callStackSymbols]; NSString *symbol = nil; if (2 < [a count]) { NSString *line = a[2]; // Format is // 1 2 3 4 5 // 012345678901234567890123456789012345678901234567890123456789 // 8 MyCoolApp 0x0000000100029809 -[MyViewController loadView] + 99 // // Don't add if this wasn't called from "MyCoolApp": if (59 <= [line length]) { line = [line substringFromIndex:4]; if ([line hasPrefix:@"My"]) { symbol = [line substringFromIndex:59 - 4]; } } } for (NSLayoutConstraint *c in constraints) { if (symbol != nil) { objc_setAssociatedObject(c, &ObjcioLayoutConstraintDebuggingShort, symbol, OBJC_ASSOCIATION_COPY_NONATOMIC); } objc_setAssociatedObject(c, &ObjcioLayoutConstraintDebuggingCallStackSymbols, a, OBJC_ASSOCIATION_COPY_NONATOMIC); } } @end
Once you have this information available on each constraint object, you can simply modify
UILayoutConstraint’s description method to include it in the output.
- (NSString *)objcioOverride_description { // call through to the original, really NSString *description = [self objcioOverride_description]; NSString *objcioTag = objc_getAssociatedObject(self, &ObjcioLayoutConstraintDebuggingShort); if (objcioTag == nil) { return description; } return [description stringByAppendingFormat:@" %@", objcioTag]; }
Check this GitHub repository for a full code example of this technique.
Ambiguous Layout
Another common problem is ambiguous layout. If we forget to add a constraint, we are often left wondering why the layout doesn’t look like what we expected.
UIView and
NSView provide three ways to detect ambiguous layouts:
hasAmbiguousLayout,
exerciseAmbiguityInLayout, and the private method
_autolayoutTrace.
As the name indicates,
hasAmbiguousLayout simply returns YES if the view has an ambiguous layout. Instead of traversing through the view hierarchy ourselves and logging this value, we can make use of the private
_autolayoutTrace method. This returns a string describing the whole view tree – similar to the printout of
recursiveDescription – which tells you when a view has an ambiguous layout.
Since this method is private, make sure to not ship any code which contains this call. One possible way to safeguard yourself against this is to create a method in a view category like this:
@implementation UIView (AutoLayoutDebugging) - (void)printAutoLayoutTrace { #ifdef DEBUG NSLog(@"%@", [self performSelector:@selector(_autolayoutTrace)]); #endif } @end
_autolayoutTrace creates a printout like this:
2013-07-23 17:36:08.920 FlexibleLayout[4237:907] *<UIWindow:0x7269010> | *<UILayoutContainerView:0x7381250> | | *<UITransitionView:0x737c4d0> | | | *<UIViewControllerWrapperView:0x7271e20> | | | | *<UIView:0x7267c70> | | | | | *<UIView:0x7270420> - AMBIGUOUS LAYOUT | | <UITabBar:0x726d440> | | | <_UITabBarBackgroundView:0x7272530> | | | <UITabBarButton:0x726e880> | | | | <UITabBarSwappableImageView:0x7270da0> | | | | <UITabBarButtonLabel:0x726dcb0>
As with the unsatisfiable constraints error message, we still have to figure out which view belongs to the memory address of the printout.
Another more visual way to spot ambiguous layouts is to use
exerciseAmbiguityInLayout. This will randomly change the view’s frame between valid values. However, calling this method once will also just change the frame once. So chances are that you will not see this change at all when you start your app. It’s a good idea to create a helper method which traverses through the whole view hierarchy and makes all views that have an ambiguous layout “jiggle.”
@implementation UIView (AutoLayoutDebugging) - (void)exerciseAmbiguityInLayoutRepeatedly:(BOOL)recursive { #ifdef DEBUG if (self.hasAmbiguousLayout) { [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(exerciseAmbiguityInLayout) userInfo:nil repeats:YES]; } if (recursive) { for (UIView *subview in self.subviews) { [subview exerciseAmbiguityInLayoutRepeatedly:YES]; } } #endif } @end
NSUserDefault Options
There are a couple of helpful
NSUserDefault options that help with debugging and testing Auto Layout. You can either set these in code, or you can specify them as launch arguments in the scheme editor.
As the names indicate,
UIViewShowAlignmentRects and
NSViewShowAlignmentRects make the alignment rects of all views visible.
NSDoubleLocalizedStrings simply takes every localized string and doubles it in length. This is a great way to test your layout for more verbose languages. Lastly, setting
AppleTextDirection and
NSForceRightToLeftWritingDirection to
YES simulates a right-to-left language.
Constraint Code
The first thing to remember when setting up views and their constraints in code is to always set
translatesAutoResizingMaskIntoConstraints to NO. Forgetting this will almost inevitably result in unsatisfiable constraint errors. It’s something which is easy to miss even after working with Auto Layout for a while, so watch out for this pitfall.
When you use the visual format language to set up constraints, the
constraintsWithVisualFormat:options:metrics:views: method has a very useful
options argument. If you’re not using it already, check out the documentation. It allows you to align the views in a dimension other than the one affected by the format string. For example, if the format specifies the horizontal layout, you can use
NSLayoutFormatAlignAllTop to align all views included in the format string along their top edges.
There is also a neat little trick to achieve centering of a view within its superview using the visual format language, which takes advantage of inequality constraints and the options argument. The following code aligns a view horizontally in its super view:
UIView *superview = theSuperView; NSDictionary *views = NSDictionaryOfVariableBindings(superview, subview); NSArray *c = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[superview]-(<=1)-[subview]"] options:NSLayoutFormatAlignAllCenterX metrics:nil views:views]; [superview addConstraints:c];
This uses the option
NSLayoutFormatAlignAllCenterX to create the actual centering constraint between the super view and the subview. The format string itself is merely a dummy that results in a constraint specifying that there should be less than one point of space between the super view’s bottom and the subview’s top edge, which is always the case as long as the subview is visible. You can reverse the dimensions in the example to achieve centering in the vertical direction.
Another convenient helper when using the visual format language is the
NSDictionaryFromVariableBindings macro, which we already used in the example above. You pass it a variable number of variables and get back a dictionary with the variable names as keys.
For layout tasks that you have to do over and over, it’s very convenient to create your own helper methods. For example, if you often have to space out a couple of sibling views vertically with a fixed distance between them while aligning all of them horizontally at the leading edge, having a method like this makes your code less verbose:
@implementation UIView (AutoLayoutHelpers) + leftAlignAndVerticallySpaceOutViews:(NSArray *)views distance:(CGFloat)distance { for (NSUInteger i = 1; i < views.count; i++) { UIView *firstView = views[i - 1]; UIView *secondView = views[i]; firstView.translatesAutoResizingMaskIntoConstraints = NO; secondView.translatesAutoResizingMaskIntoConstraints = NO; NSLayoutConstraint *c1 = constraintWithItem:firstView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:secondView attribute:NSLayoutAttributeTop multiplier:1 constant:distance]; NSLayoutConstraint *c2 = constraintWithItem:firstView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:secondView attribute:NSLayoutAttributeLeading multiplier:1 constant:0]; [firstView.superview addConstraints:@[c1, c2]]; } } @end
In the meantime there are also many different Auto Layout helper libraries out there taking different approaches to simplifying constraint code.
Performance
Auto Layout is an additional step in the layout process. It takes a set of constraints and translates them into frames. Therefore it naturally comes with a performance hit. In the vast majority of cases, the time it takes to resolve the constraint system is negligible. However, if you’re dealing with very performance critical view code, it’s good to know about it.
For example, if you have a collection view which has to bring several new cells on screen when a new row appears, and each cell consists of several subviews laid out by Auto Layout, you may notice the effect. Luckily, we don’t need to rely on our gut feeling when scrolling up and down. Instead we can fire up Instruments and actually measure how much time Auto Layout spends. Watch out for methods of the
NSISEngine class.
Another scenario where you might run into performance issues with Auto Layout is when you are showing lots of views at once. The constraint solving algorithm, which translates the constraints into view frames, is of super-linear complexity. This means that from a certain number of views on, performance will become pretty terrible. The exact number depends on your specific use case and view configuration. But to give you a rough idea, on current iOS devices it’s in the order of a magnitude of 100. For more details, you can also read these two blog posts.
Keep in mind that these are edge cases. Don’t optimize prematurely and avoid Auto Layout for its potential performance impact. It will be fine for most use cases. But if you suspect it might cost you the decisive milliseconds to get the user interface completely smooth, profile your code and only then should you decide if it makes sense to go back to setting frames manually. Furthermore, hardware will become more and more capable, and Apple will continue tweaking the performance of Auto Layout. So the edge cases where it presents a real-world performance problem will decrease over time.
Conclusion
Auto Layout is a powerful technique to create flexible user interfaces, and it’s not going away anytime soon. Getting started with Auto Layout can be a bit rough, but there is light at the end of the tunnel. Once you get the hang of it and have all the little tricks to diagnose and fix problems up your sleeve, it actually becomes very logical to work with. | https://www.objc.io/issues/3-views/advanced-auto-layout-toolbox/ | CC-MAIN-2017-26 | refinedweb | 5,329 | 50.26 |
Make Your XML RDF-FriendlyMake Your XML RDF-Friendly..
The good news is that a given resource can be both the object of one or more RDF statements and the subject of others. For example, the following shows that Bridget Fonda's father is Peter Fonda and that Peter Fonda's father is Henry Fonda. Peter is the object of the statement made by the outer triple and the subject of the inner one.
<Entertainer rdf: <gc:father> <Entertainer rdf: <gc:father> <Entertainer rdf: </gc:father> </Entertainer> </gc:father> </Entertainer>
There's no limit to the level of nesting, as long as even-numbered elements in the line of descendants are resources and odd-numbered resources are predicates. This alternating relationship is known in RDF circles as striping.
The bad news is that many common uses of container elements throw this striping pattern off. The following example, which omits the document element and namespace declarations, is otherwise perfectly good RDF until the attachments element.
<email rdf: <from>bram@snee.com</from> <to>bela@snee.com</to> <date>20021024T081423</date> <msgSubject>Dinner tonight</msgSubject> <attachments> <attachment>data\sample1.txt</attachment><!-- RDF parser chokes here --> <attachment>data\sample2.txt</attachment> </attachments> <cc>frank@snee.com</cc> </email>
Up to that point, an RDF parser knows that the resource with the ID "msg001" has a from value of "bram@snee.com", a to value of "bela@snee.com", and so on, but what is the attachments value? If its contents were an XML element, it would have to be just one element, with an identifier that named it as a specific resource. Having more than one element -- which is the whole point of the wrapper, because a given e-mail message may have more than one attachment -- is something that RDF can't handle when represented this way. It thinks that the attachments property of the email resource has two properties of its own (the two attachment elements). Properties can't have properties, but resources can.
There are two obvious options for giving this email element the resource-predicate-resource-predicate descendant structure that RDF expects: either remove a layer of containment or add one. Removing the attachments container would make each attachment element a sibling of from, to, and the email element's other children, and email wouldn't have any grandchildren:
<email rdf: <from>bram@snee.com</from> <to>bela@snee.com</to> <date>20021024T081423</date> <msgSubject>Dinner tonight</msgSubject> <attachment>data\sample1.txt</attachment> <attachment>data\sample2.txt</attachment> <cc>frank@snee.com</cc> </email>
The problem with this is that you may have a good reason to use that container. For example, when processing your XML e-mail messages using an event-based model such as the SAX API, maybe there's something specific you want to do when you reach the end of the attachment list. How do you know you've reached the end of that list when processing this version of the email element? When you reach the cc element? What if cc is optional? Nothing says "end of attachment list" like an </attachments>.
If you must have a container around your attachment elements, and want to make it proper RDF, one solution is to use one of RDF's specialized container elements. In this case, you can wrap an rdf:Bag element around the attachment elements in the original e-mail example, inside of the attachments element. (In keeping with guideline 2, the attachments element has been given an rdf:ID attribute to make it easier for a parser to refer to it.) The rdf:Bag element describes a container whose contents aren't ordered in any meaningful way. The example's rdf:Bag element has an rdf:ID value of "i2", telling an RDF parser that in addition to having a from property with a value of "bram@snee.com", as well as the other properties we saw, the resource with the ID "msg003" also has an attachments property with resource #i2 has its value. This i2 resource has a type of rdf:Bag, which RDF parsers understand to be a container of unordered content. The i2 resource has one attachment with a value of "data\sample1.txt" and another with a value of "data\sample1.txt". And, unlike the first e-mail example above, this one causes no error message in the RDF parser.
<email rdf: <from>bram@snee.com</from> <to>bela@snee.com</to> <date>20021024T081423</date> <msgSubject>Dinner tonight</msgSubject> <attachments rdf: <rdf:Bag rdf: <attachment>data\sample1.txt</attachment> <attachment>data\sample2.txt</attachment> </rdf:Bag> </attachments> <cc>frank@snee.com</cc> </email>
In addition to the rdf:Bag container for unordered content, RDF also offers the rdf:Seq element for ordered (or "sequenced") content and the less popular rdf:Alt container to show available alternatives to a specified value.
There is actually a third, even simpler option for converting this email element's structure into something that won't confuse the RDF parser: we can explicitly tell this parser that the attachments property of the email element is itself a resource with the rdf:ParseType attribute:
<email rdf: <from>bram@snee.com</from> <to>bela@snee.com</to> <date>20021024T081423</date> <msgSubject>Dinner tonight</msgSubject> <attachments rdf: <attachment>data\sample1.txt</attachment> <attachment>data\sample2.txt</attachment> </attachments> <cc>frank@snee.com</cc> </email>
Think about the original problem: the attachments property of the email element couldn't have its own properties, which is why the RDF parser choked at the first attachment element -- it thought that the document was trying to name a property of a property, which is illegal. Now that the attachments element is explicitly named as a resource, it can have properties, so the RDF parser will have no problem with the two attachment children of this element.
Mixed content presents a more advanced version of the problem caused by containers that throw off the striping pattern. Once you see that the resources described in RDF statements must either be siblings of each other or skip an odd number of generations when descendants of each other, and that predicates must be descendants found at the levels between those, it's clear how the typically irregular patterns of mixed content can throw off RDF striping. Mixed content can also put strings of PCDATA in odd places -- or at least in places that seem odd if you're looking for regular recurring patterns.
This doesn't mean that you can't have RDF in a document with mixed content. The "Moby Dick" example at the beginning of this article has mixed content, and the rdf:RDF element showing publishing metadata such as the work's creator and availability date is kept separately in an RDF header section.
RDF statements in a mixed content document can even use elements within the mixed content as resources. The following example has an rdf:RDF header element that contains a made-up imgLink element linking the character in-line element to an image on a remote server.
<article xmlns="" xmlns: <rdf:RDF> <imgLink rdf: <image rdf: </imgLink> </rdf:RDF> <body> <title>Moby Dick</title> <para>Call me <character rdf:Ishmael</character>.</para> <para>Just don't call me late for supper.</para> </body> </article>
An RDF parser will find the statement linking the character element to the Moby.gif picture and will have no problem with the mixed content along the way.
When learning any new language, you want to be sure that what you think you're saying is really what you're saying. Most RDF parsers make this easy by outputting a subject-predicate-object triple for each RDF statement they find. For example, the W3C's RDF Validation Service turns this document
<rdf:RDF xmlns: <Entertainer rdf: <gc:father> <Entertainer rdf: </gc:father> </Entertainer> </rdf:RDF>
into this (carriage returns added):
<> <> <> . <> <> <> . <> <> <> .
Or, in English, using only the URI fragment identifiers:
Peter Fonda has a type value of Entertainer.
Bridget Fonda has a father value of Peter Fonda.
Bridget Fonda has a type value of Entertainer.
In general, using a utility to convert RDF to triples helps you to understand exactly what is being said if you read the subject-predicate-object triple "X, Y, Z" as "X has a Y value of Z." All the natural language descriptions of RDF statements in this article were checked this way.
As RDF tools become more widely available and easy to use, you'll have more resources available to do improved metadata management for your own data. Even if you're not ready to build serious RDF applications just yet, making more of your own data RDF-friendly will do more than widen the number of applications that can use it. For many people, the kinds of things that RDF is good at become clearer to them when used with data that is important to their business or important to them personally, such as an address or appointment file. Using RDF tools to play with your own data will help you understand the strong points of RDF and, perhaps, even the strong points of your own data better.
XML.com Copyright © 1998-2006 O'Reilly Media, Inc. | http://www.xml.com/lpt/a/2002/10/30/rdf-friendly.html | crawl-002 | refinedweb | 1,537 | 52.19 |
You are not logged in.
Pages: 1
OK I'm trying to have a simple loop which keeps on printing each number from 1,2,... on a different line and it keeps on doing so until the user enters 'e'.
e.g
for(i=0;i<=9999999999;i++)
{
printf("%d\n",i);
}
It does not take any input from user and keeps on printing but as soon as user presses e the program exits.Any clue how to go about this.
There are multiple ways to go about it... One is to use ncurses, and set nodelay(),
which is essentially non-blocking mode for input, so you can then call getch() each
time through the loop and it'll either fail or return a key if one has been pressed...
You can do similar without the ncurses overhead by using tcsetattr() to turn off ICANON,
then set FD 0 to non-blocking mode, and just do a read()... Or, you can just use
select()/poll() to check stdin for readability every time through the loop, and just do a
read() if there's something there to read... Or, you could use fcntl(F_SETOWN) with
O_ASYNC and a SIGIO handler to asynchronously be notified about input ready to be
read from stdin... Or, you could create 2 threads: one spitting out the numbers non-stop,
and one blocked on input from stdin, waiting to see the "e"; and, when it sees it, it would
kill the other thread to stop it... Etc... Like I said, there are multiple approaches...
Well thanks for your your answer .I'm new with c.So it would be great if you could tell me about how to use the stdout/poll option ..
Well, here's a simple example using select(), since I'm far more comfortable with it
than poll(), and I'm not going to do ALL your work for you... ;-)
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <termios.h> #include <sys/select.h> int main () { int i; char c; fd_set fds; struct timeval timeout; struct termios old, new; if (tcgetattr (STDIN_FILENO, &old)) { perror ("Unable to read old terminal attributes"); return (-1); } memcpy (&new, &old, sizeof (struct termios)); new.c_lflag &= ~(ICANON | ECHO); if (tcsetattr (STDIN_FILENO, 0, &new)) { perror ("Unable to set new terminal attributes"); return (-1); } for (i = 0;; i++) { printf ("%d\n", i); FD_ZERO (&fds); FD_SET (STDIN_FILENO, &fds); memset (&timeout, '\0', sizeof (timeout)); if ((select (STDIN_FILENO + 1, &fds, NULL, NULL, &timeout) > 0) && (read (STDIN_FILENO, &c, 1) == 1)) { if (c == 'e') break; else printf ("Read (%c)\n", c); } } tcsetattr (STDIN_FILENO, 0, &old); return (0); }
Pages: 1 | https://developerweb.net/viewtopic.php?pid=29022 | CC-MAIN-2021-43 | refinedweb | 438 | 79.09 |
FreeBSD Bugzilla – Bug 94585
mail/mailagent 'basic/config' test hangs on FreeBSD-6 amd64
Last modified: 2006-05-08 07:49:44 UTC
Building mail/mailagent hangs during running tests (basic/config).
'filter' process starts to eat all the CPU and doesn't respond to SIGTERM.
SIGKILL works as usual. On i386 platform there is no such behaviour.
If I replace 'filter' binary by i386's one, the test passes.
Further investigation reveals that the following code causes SEGV on amd64, but not on i386.
--------------------------
#include <stdio.h>
int main()
{
printf("%s\n",strerror(2));
exit(0);
}
--------------------------
Adding "#include <string.h>" solves the problem.
logfile.c in agent/filter doesn't include string.h, and it seems to cause an infininte loop during its signal handling.
I'm not an expert of C programming, so I'm not sure whether it is a bug of
FreeBSD amd64 itself or including string.h is mandatory.
Fix: Add the following file to patch directory of the port.
How-To-Repeat: make /usr/ports/mail/mailagent as an ordinary user on FreeBSD-6 amd64.
Responsible Changed
From-To: freebsd-ports-bugs->max
Over to maintainer
Responsible Changed
From-To: max->freebsd-ports-bugs
Maintainer was reset.
State Changed
From-To: open->closed
The submitted patch has been added to the repository. Thanks!! and sorry for the delay!
Responsible Changed
From-To: freebsd-ports-bugs->max
Max reclaims the maintainership and applied the suggested fix. | https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=94585 | CC-MAIN-2015-14 | refinedweb | 241 | 51.95 |
opening and closing many files is slow on pypy3
Another thing that's quite slow in pypy3 is opening and closing many files:
import sys import time def main(): t1 = time.time() for i in range(int(sys.argv[1])): with open(__file__, "r") as f: pass t2 = time.time() print(t2 - t1) if __name__ == '__main__': main()
about 4x slower than cpython for me (not a problem on pypy2), most of the time is spent in the gc.
I think the
_io module is missing a call to
may_unregister_rpython_finalizer maybe?
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information | https://foss.heptapod.net/pypy/pypy/-/issues/3457 | CC-MAIN-2021-25 | refinedweb | 108 | 71.85 |
We are given a set of items, each item is associated with a weight and a value. We need to determine the number of each item to include in a knapsack so that the total weight of the final knapsack is less than or equal to a given limit W and the total value is maximum. Also, please note that the items are indivisible units which means that there are only two possible choice – either include or exclude the item.
Sample Input: Values = { 20, 5, 10, 40, 15, 25 }, Weights = { 1, 2, 3, 8, 7, 4 }, W = 10
Expected Output: 60
Explanation: Weight = 1 + 8 < 10 (W) and Value = 20 + 40 = 60
Algorithm:
- The problem can be solved using dynamic programming as it has optimal substructure and overlapping sub problem.
- For each item we have two possibilities, either we include the current item in the knapsack, add the value and weight of the current item to the total value and weight and then recur for remaining items with decreased capacity.
Or we can exclude the current item from knapsack and recur for remaining items.
- Finally, we return the maximum value by including or excluding the current item.
- The following implementation is a bottom up approach of the same problem.
- We create a 2D array DP of size (n+1, w+1) where n is the total number of items and w is the weight limit of the knapsack.
- If the current element’s weight is greater than the remaining capacity, we exclude the item and retrieve the result of the previous sub problem.
- Else we find the maximum of the following conditions – either we exclude the current item or we include the current items value to the answer of the sub problem.
/* Author => Raunak Jain */ #include <bits/stdc++.h> using namespace std; int helper(vector<int> weights, vector<int> values, int w){ int wsize = weights.size(); vector<vector<int>> dp(wsize+1, vector<int>(w+1, 0)); for(int i=1; i<=wsize; i++){ for(int j=1; j<=w; j++){ if(weights[i-1]>j){ dp[i][j] = dp[i-1][j]; }else{ dp[i][j] = max(dp[i-1][j], values[i-1]+dp[i-1][j-weights[i-1]]); } } } return dp[wsize][w]; } int main(){ vector<int> values = { 60, 100, 120 }; vector<int> weights = { 10, 20, 30 }; int W = 50; cout<<helper(weights, values, W); return 0; }
Also, check out another popular interview question Pots of Gold. | https://nerdycoder.in/2020/08/07/0-1-knapsack-problem-dp-07/ | CC-MAIN-2021-04 | refinedweb | 410 | 53.95 |
Opened 8 years ago
Closed 2 years ago
#14415 closed Bug (fixed)
Multiple aliases for one database: testing problems
Description
In a setting where the multiple-databases feature is used to create multiple aliases for one database, the testing framework can get a little confused.
For ease of reference, assume we have the following dictionary defining database parameters:
db_params = dict ( NAME = 'main', ENGINE = 'django.db.backends.whatever', USER = 'user', PASSWORD = 'password', HOST = '', PORT = '' )
The relatively benign cases
In these cases, the test framework just treats the two aliases as separate databases; which means it first creates the test database for one alias, then tries to create the test database for the second one, running into an error because (of course) it already exists. The user is asked to choose between destroying the existing database (in order to recreate it) and canceling the test. In cases where database routers constrict models to a specific alias, this may completely prevent testing (or at least some of the tests).
This happens if at least one of two conditions hold:
The dictionaries used to define the alias are distinct
That is, the databases are defined by
DATABASES = { 'default' : db_params, 'other' : db_params.copy() }
or some equivalent
Test name is explicitly specified
That is,
db_params looks like:
db_params = dict ( NAME = 'main', TEST_NAME = 'test_main', ... # same as above )
The databases may then be specified by the more natural
DATABASES = { 'default' : db_params, 'other' : db_params }
The more dangerous case
In this case, the testing framework creates spurious databases and
finalizes be destroying the main, non-test database.
This happens when none of the above applies -- that is,
db_params does not include
the
TEST_NAME entry, relying on the default
test_ prefix addition, and databases
are specified by two references to the same dictionary (as in the last definition above).
Regretfully, one may expect this to be the common use case in a multiple-aliases-for-one-database
approach.
In detail: With the definitions above, the testing framework first creates a
test_main database, then a
test_test_main database, and runs its tests with both of them present; then, during tear-down, it drops the
test_test_main and *
main* databases, leaving
test_main in place.
A word for fixers
For whoever wants to work on this ticket (perhaps myself...), Russel Keith-Magee has said that
...
Attachments (4)
Change History (31)
comment:1 Changed 8 years ago by
comment:2 Changed 7 years ago by
Changed 7 years ago by
comment:3 Changed 7 years ago by
comment:4 Changed 7 years ago by
I think you've tried to solve this in the wrong place. Rather than fixing this at the level of the database backend, it seems to me that the solution lies in fixing the test runner's setup_databases call. There is already some handling for avoiding duplicate database setup (via the handling for the TEST_MIRROR setting); it seems to me that the problem described here is really just an TEST_MIRROR that is implied because the database name is the same.
So - if we refactor the handling of TEST_MIRROR so that we pre-evaluate the list of database that need to be created and the list that needs to be redirected, we should be able to avoid this problem entirely.
Of course, this is just based on first inspection; there might be some detail that I'm missing. I'll take a closer look later tonight (my time).
Also - bumping to 1.3 milestone because of the potential for unintentional data loss.
Changed 7 years ago by
Alternative solution based around the test runner
comment:5 Changed 7 years ago by
comment:6 Changed 7 years ago by
I think Russell's approach is closer to home, but there are still problems.
For starters, the patch has a "surface" problem of identifying databases by their (Engine,Name) combination. The current docs about TEST_MIRROR () show an example where this would be invalid (same name, different hosts). To fix this, it seems, we would need a notion of equivalence of settings --
== between dicts seems close enough for my taste (if a user defines two MySql databases, one with
PORT='' and another with
PORT='3306', I think they deserve the brouhaha they'll get), but I may be wrong (different OPTIONS'es, for example, for different transactional behavior, would seem legitimate).
But there is a deeper problem: solving the issue by directing the actual connections -- not just fixing the creation/destruction issue -- would cause the test process to have different transaction semantics. Consider:
def do_stuff(alias1, alias2): with transaction.commit_manually(using=alias1) # Make an invalid change in an object m = MyModel.objects.get(pk=17) m.fld = 'invalid' m.save(using=alias1) # Commit other changes, but not the invalid change transaction.commit(using=alias2) # Roll back the invalid change transaction.rollback(using=alias1) # Check the outcome m1 = MyModel.objects.get(pk=17) assert m1.fld1 != 'invalid'
This will work in production, but fail in testing under t14415.diff.
Changed 7 years ago by
Updated patch for test database issue
comment:7 Changed 7 years ago by
@shai - Good call on the HOST issue - I've made that change; new patch incoming shortly.
However, regarding the connection issue - I'm unclear whether what you consider correct behavior, and under what circumstances.
The 'connection copying' behavior is only performed for the TEST_MIRROR case, and that behavior exists historically. To my mind, this is a bug; using connection obtained from the alias that is a TEST_MIRROR shouldn't affect transactions created using the connection that is being mirrored. The new patch addresses this bug.
However, you seem to be implying that the same connection copying behavior exists for connections with a copied settings dictionary, which isn't the case. The patch I've provided causes your sample code to raise an exception at "transaction.commit(using=alias2)", because the code isn't under transaction management (for alias2) at that point.
Have I misunderstood something here?
comment:8 Changed 7 years ago by
@russelm -- Sorry, I had misread your original patch; you are right, the connections seem to be handled correctly.
I'll look at it again tonight (Israel time), to comment on the change in TEST_MIRROR handling.
One note, though, about adding HOST: While it is, as far as I know, good enough for Django's officially supported DBMSs, it is not enough for SqlServer or Sybase, where a host includes a set of databases, each containing a set of "schemata". Not sure if preparing support for this is easy, and if not easy, if it is worthwhile, but I thought it's worth mentioning.
comment:9 Changed 7 years ago by
After a second look: Yes, the new TEST_MIRROR behavior seems to be correct and even required to preserve production semantics (interleaved operations on master and slave with no commit may yield different result in production and test with current code).
One other note, though: PORT needs to be treated just like HOST, orthogonal to the SqlServer issue mentioned in my earlier comment.
If there is an easy way to provide tests for these issues, I'd like to do that.
Thanks,
Shai.
comment:10 Changed 7 years ago by
Fixed the patch, ran some tests with it. It seems to work (though using the same parameters for the two databases makes many tests fail, nothing seems to blow up, and nothing is generated or destroyed more than once).
Changed 7 years ago by
just adding PORT to t14415.2.diff
comment:11 Changed 7 years ago by
To clarify -- when you say "makes many tests fail", is that a good thing or a bad thing? Is this an indication that the test suite is now running and revealing problems in your code, or that the test setup is broken in some way?
comment:12 Changed 7 years ago by
I think it's a good thing -- essentially, the Django test suite assumes that different aliases point at different databases. I didn't check every failure in detail, but as an example, there was a test in
multiple_database that failed because an object saved through one alias was accessible through the other.
comment:13 Changed 7 years ago by
Django's test suite has a very specific set of requirements for the test database, and yes, independence between default and other is one of those requirements. If you're running Django's test suite with a mirrored or aliased database, there will be failures.
Thanks for the help testing this, Shai.
comment:14 Changed 7 years ago by
comment:15 Changed 7 years ago by
(In [14697]) [1.2.X] Fixed #14415 -- Corrected the process of creating and destroying test databases to prevent accidental deletion of the source database. Also improves the mirroring process to prevent some cross-connection effects. Thanks to Shai Berger for the help diagnosing and testing.
Backport of r14696 from trunk.
comment:16 Changed 7 years ago by
Milestone 1.3 deleted
comment:17 Changed 2 years ago by
It's quite amazing to realize, more than 5 years later, that the bug was actually not properly fixed.
The problem is in
django.db.backends.base.creation:
def test_db_signature(self): """ Returns a tuple with elements of self.connection.settings_dict (a DATABASES setting value) that uniquely identify a database accordingly to the RDBMS particularities. """ settings_dict = self.connection.settings_dict return ( settings_dict['HOST'], settings_dict['PORT'], settings_dict['ENGINE'], settings_dict['NAME'] )
The decision whether a database is a mirror of another, when
TEST['MIRROR'] is not set explicitly, is taken based on the production settings rather than test settings. You are not likely to notice until you try to test separation of a model into a dedicated database -- where you try to set only the test databases to be separate.
comment:18 Changed 2 years ago by
Could you give an example where the tests currently fail? I'm not very clear on the model separation.
comment:19 Changed 2 years ago by
Let's say you have two db's - "default" and "other".
In db "other" you have table x, which you don't have In db "default" (I used db router to accomplish that).
During a test, you are trying to add a row to table x, only on db "other".
Let's assume this is your DATABASES setting:
DATABASES = { 'default': { 'NAME': 'some_name', 'ENGINE': 'django.db.backends.postgresql_psycopg2'', 'USER': ..., 'PASSWORD': ... } } other = DATABASES['default'].copy() other['TEST']['NAME'] = 'other_name' DATABASES['other'] = other
Django will ignore
other['TEST']['NAME'] = 'other_name'
as long as you don't set
other['NAME']
to a value different from
DATABASES['default']['name']
comment:20 Changed 2 years ago by
I have changed test_db_signature to use
settings_dict['TEST']['NAME']
if set, and
settings_dict['NAME']
as a fallback.
comment:21 Changed 2 years ago by
comment:22 Changed 2 years ago by
comment:23 Changed 2 years ago by
comment:24 Changed 2 years ago by
Did you try to add a test for that change?
comment:25 Changed 2 years ago by
Left an idea for a test on the pull request.
This is what I've found:
I think the maximum that Django can provide is what I've tried to implement in the patch:
DATABASES['alias']['NAME']and
DATABASES['alias']['TEST_NAME']happens between DB aliases/connections, even when they are described by the same Python dict so in no event the production
DATABASES['alias']['NAME']DB gets removed.
What's described above is generally applicable to Postgres, MySQL and SQlite3.
But after fixing that, there are other problems (at test DB teardown time): In Postgres and MySQL the test databases are removed by using the production one as a pivot (a connection is made to the production DB and from there the test one is DROPped). If you get the setup you describe, it might happen (It happens to me) that 'default' will get is test DB ('test_main') dropped and when 'other' tries to connect to its production one to do the same (remove it 'test_test_main' DB) it won't find it.
Solving this means Django would need to detect and keep track of the fact that one alias' test DB name is the same as other alias' production DB, and DATABASES being a dict, there is no guaranteed order of creation/removal of DBs.
The conclusion I get is this is what you describe as the The more dangerous case and one may expect this to be the common use case in a multiple-aliases-for-one-database approach is enough of an edge case that can't be completely solved by Django. If you really need to create more that one DATABASES aliases to the same database and you decide to represent them by pointing them to the same dict, then maybe you will need to implement your own test runner that will need to have some inside knowledge of this and e.g. will need to setup/tear down the test DBs in the right order, etc.
The Oracle backed has its own tools so (again) the user, not Django, tries to implement a workaround to the scenarios you describe (see wiki:OracleTestSetup Understanding the database test setup section.) | https://code.djangoproject.com/ticket/14415 | CC-MAIN-2018-17 | refinedweb | 2,188 | 57 |
.
When it comes to working with GUIs, it’s always easier to see how you might put one together yourself. Let’s write little form that takes a string and has two buttons: an OK button and an Cancel button.
This example is based on one from the PySimpleGUI User’s Manual:
import PySimpleGUI as sg # Create some elements layout = [[sg.Text("What's your name?"), sg.InputText()], [sg.Button('OK'), sg.Button('Cancel')]] # Create the Window window = sg.Window('Hello PySimpleGUI', layout) # Create the event loop while True: event, values = window.read() if event in (None, 'Cancel'): # User closed the Window or hit the Cancel button break print(f'Event: {event}') print(str(values)) window.close()
Here you import PySimpleGUI and then you create a series of widgets, which are known as “Elements” in PySimpleGUI: Text, InputText and two Buttons. To layout the Elements in rows, you can add them to lists. So for the first row of Elements, you create a list that contains the Text Element followed by the InputText Element. The Elements are added from left-to-right horizontally. To add a second row, you add a second list of Elements, which contains the two buttons.
After you have all your Elements in a nested set of lists, you can create the Window. This is the parent Element that contains all the other Elements. It has a title and accepts your nested list of Elements.
Finally you create an while loop and call the Window’s read() method to extract the events and values that the user has set. If the user presses the Cancel button or closes the Window, you catch that and break out of the loop. Otherwise you print out the event and any value the user has entered.
This is what the GUI should look like when you run your code:
Let’s say you enter the string “mike” in the text entry widget and then hit the OK button. You should see the following output in your terminal:
Event: OK
{0: 'mike'}
Wouldn't it be nice if you could redirect stdout to a debug window in your GUI though? PySimpleGUI actually has an easy way to do that. All you need to do is update your print statement in the code above to the following:
sg.Print(f'Event: {event}') sg.Print(str(values))
Now when you run the code and enter a string and press OK, you should see the following debug window:
PySimpleGUI Elements
There isn't enough time to go over every Element that PySimpleGUI supports. However you can see which Elements are supported by going to this part of the documentation. There is a note in the documentation that mentions that Table widget currently has issues. It is implied that the Tree widget is also problematic, but doesn't really talk about why.
Note that PySimpleGUI has wrapped all the widgets available in Tkinter, so you do have a good number of widgets to work with. However the widgets in ttk are currently not supported.
Update: After speaking with the package's maintainer, I was told that the Table and Tree Elements are actually working quite well.
Creating Multiple Windows
One thing that I see a lot of new programmers struggle with is opening multiple windows in their GUI toolkit of choice. Fortunately, PySimpleGUI has directions of how to do this clearly labeled. They actually have two different "design patterns" for doing this sort of thing.
For brevity, I'll only show how to do two active windows:
import PySimpleGUI as sg # Create some Elements ok_btn = sg.Button('Open Second Window') cancel_btn = sg.Button('Cancel') layout = [[ok_btn, cancel_btn]] # Create the first Window window = sg.Window('Window 1', layout) win2_active = False # Create the event loop while True: event1, values1 = window.read(timeout=100) if event1 in (None, 'Cancel'): # User closed the Window or hit the Cancel button break if not win2_active and event1 == 'Open Second Window': win2_active = True layout2 = [[sg.Text('Window 2')], [sg.Button('Exit')]] window2 = sg.Window('Window 2', layout2) if win2_active: events2, values2 = window2.Read(timeout=100) if events2 is None or events2 == 'Exit': win2_active = False window2.close() window.close()
The first few lines are pretty similar to the first example in this article. This time around you will create the main application with only two buttons. One of the buttons is used for opening a second window while the other button is used for closing the program.
Next you set a flag, win2_active, to False and then start your "event loop". Inside of the event loop, you check if to see if the user has pressed the "Open Second Window" button. If they have, then you open the second window and watch for its events too.
Personally I find this kind of clunky to work with. I think a lot of this could be improved by using some classes for the Windows and abstracting the main loop. I wouldn't want to have to deal with creating a lot of windows using this kind of pattern as it looks like it would get very complex very quickly to me. But I haven't used this package enough to know if there are already good workarounds for this.
Wrapping Up
PySimpleGUI is a neat library and I like that it tries to be a bit more "Pythonic" than wxPython and PyQt tend to be. Of course, if you are looking for another GUI toolkit that uses a more Pythonic approach versus a C++ approach that PyQt and wxPython use, you might want to check out Toga or Kivy.
Anyway, I think PySimpleGUI looks like it has a lot of interesting features. The widget set matches Tkinter and even goes a bit beyond it. PySimpleGUI also has a lot of cool demo applications on their Github. They also have information on turning your application into an executable on Windows and Mac using PyInstaller, which is something you don't normally see in the documentation for a GUI toolkit.
If you are looking for a simple GUI toolkit, PySimpleGUI might be right up your alley. | https://www.blog.pythonlibrary.org/2019/10/23/a-brief-intro-to-pysimplegui/ | CC-MAIN-2021-31 | refinedweb | 1,019 | 63.39 |
Maintains a tree of blocks (stored in
m_block_index) which is consulted to determine where the most-work tip is.
More...
#include <validation.h>
Maintains a tree of blocks (stored in
m_block_index) which is consulted to determine where the most-work tip is.
This data is used mostly in
CChainState - information about, e.g., candidate tips is not maintained here.
Definition at line 348 of file validation.h.
If a block header hasn't already been seen, call CheckBlockHeader on it, ensure that it doesn't descend from an invalid block, and then add it to m_block_index.
Definition at line 3607 of file validation.cpp.
Definition at line 3154 of file validation.cpp.
Create a new block index entry for a given block hash.
Definition at line 4072 of file validation.cpp.
Load the blocktree off disk and into memory.
Populate certain metadata per index entry (nStatus, nChainWork, nTimeMax, etc.) as well as peripheral collections like setDirtyBlockIndex.
Definition at line 4092 of file validation.cpp.
Clear all data members.
Definition at line 4147 of file validation.cpp.
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
Pruned nodes may have entries where B is missing data.
Definition at line 376 of file validation.h.
In order to efficiently track invalidity of headers, we keep the set of blocks which we tried to connect and found to be invalid here (ie which were set to BLOCK_FAILED_VALID since the last restart).
We can then walk this set and check if a new header is a descendant of something in this set, preventing us from having to walk m_block_index when we try to connect a bad block and fail.
While this is more complicated than marking everything which descends from an invalid block as invalid at the time we discover it to be invalid, doing so would require walking all of m_block_index to find all descendants. Since this case should be very rare, keeping track of all BLOCK_FAILED_VALID blocks in a set should be just fine and work just as well.
Because we already walk m_block_index in height-order at startup, we go ahead and mark descendants of invalid blocks as FAILED_CHILD at that time, instead of putting things in this set.
Definition at line 370 of file validation.h. | https://doxygen.bitcoincore.org/class_block_manager.html | CC-MAIN-2020-24 | refinedweb | 384 | 65.01 |
measuring academese01 Mar 2015
We all know that academic writing stinks, but exactly how bad is it? And in what disciplines does academic writing stink the most? To answer these questions I scraped 174,527 academic articles, came up with a few indicators of “academese” and compared these indicators across disciplines.
our data source
I scraped those articles from SciELO. In case you’ve never heard of SciELO, it’s like JSTOR, but focused on Latin American journals. I would rather have scraped JSTOR, but it’s gated. I could scrape it using my OSU credentials, but the Aaron Swartz brouhaha is not an encouraging precedent. Also, JSTOR articles are usually in PDF, which sucks for text mining (especially when the PDF is the scan of a document, which is often the case in JSTOR). SciELO, by contrast, is ungated (it doesn’t even have a “terms of use” page, so I can’t possibly be breaking any rules) and its articles are in HTML, which is much easier to parse than PDF.
Most articles on SciELO are in Portuguese or Spanish but that’s not a problem here. The flaws of academic writing - cluttered sentences, meaningless words, plenty of jargon - are not language-specific. And thanks to the Normands the mumbo jumbo barely changes from one language to another: in English you problematize the discursive paradigm and in Portuguese você problematiza o paradigma discursivo.
summary statistics
The 174,527 articles I scraped are all the articles in Portuguese from all the 281 active journals on SciELO. Here’s how they are distributed:
We’ll look into specific disciplines in a minute.
(SciELO doesn’t categorize its journals, so the categorizations above are my own, partly based on Latindex’s. In case you are curious, here are the journal ISSN codes and respective areas.)
academese and how to measure.)
As we see, academese is not a particular type of bad writing. The same set of flaws that we’ve been calling academese could very well be called journalese or bureaucratese. The specific jargon may change (academics critique, bureaucrats impact) but the underlying sins are the same: clutter and vagueness.
Now that we know what bad writing is we can measure it. Here are my indicators:
- Word length.
- Sentence length.
- Adverbs/total number of words. To identify adverbs I use the 1,000 most frequent adverbs in the Portuguese Corpus.
- Gerunds/total number of words. I count as a gerund any word that ends in ‘ndo’, which is how gerunds end in Portuguese - as in fazendo (doing), escrevendo (writing), etc.
- Inane words/total number of words. I don’t have an exhaustive list of inane words. Instead I selected any words that match one of the following regular expressions:
'^problematiz.*': problematizar (to problematize), problematização (problematization), etc.
'^paradigma.*': paradigma (paradigme), paradigmático (paradigmatic), etc.
'^discursiv.*': discursivo (discursive), discursividade (discursivity), etc.
'^dial\u00E9tic.*': dialética, dialético (both mean dialectic), etc.
'^critic.*'and
'^cr\u00EDtic.*': criticar (to criticize), crítico (critical, critic), criticado (criticized), etc. You may have qualms about this but think: are people supposed to do anything a-critically in academia? If not then critical is inane unless we’re talking about a specific disagreement (as in “Hayek criticized Keynes’ monetary theory”). Elsewhere - “critical theory”, “a critical look at”, etc - critical is pointless.
I picked these words because they are not specific to any disciplines. Sociologists and physicists alike can talk about paradigmes, problematize phenomena, or take a critical look at theories and experiments. Sociologists and physicists may differ in how often they use such inane words (that’s what I want to measure) but they both have the same opportunities to use them.
I considered enriching my list of inane words with words from Sokal’s hoax and from the Bad Writing Contest. But that might stack the deck against the humanities. Physicists probably don’t have many chances to write entelechy, otherness, or essentiality.
I’d rather use a machine learning approach but I couldn’t find a corpora of academic articles pre-labeled as academese/not academese (let alone one such corpora that happens to be in Portuguese). Hence what’s left is this sort of “dictionary” approach, which is much weaker - I’m certainly missing A LOT of relevant features (and possibly using some irrelevant ones). But it’ll have to do for now.
so, who stinks the most?
Here’s the ratio inane words / total number of words:
Adverbs / total number of words:
Gerunds / total number of words:
Average sentence length:
Average word length:
Clearly it’s in the humanities and social sciences that academese really thrives. Not exactly a shocking finding, but it’s nice to finally have some numbers. I didn’t expect the difference in inane words usage to be so large. Conversely, I expected word length to vary a lot more (maybe scientific names are inflating word size in the hard sciences?).
zooming in
Let’s zoom in on some of the humanities and social sciences. Here’s our articles:
Now let’s see how these different disciplines compare. Here’s the ratio inane words / total number of words:
Adverbs / total number of words:
Gerunds / total number of words:
Average sentence length:
Average word length:
Well, these are some disappointing data. I expected big differences - especially between pairs like economics and anthropology, or business and history. Turns out I was wrong. Sadly, there isn’t a clear “worst offender” for us to shame. Philosophy wins (well, loses) when it comes to poor word choices, but not by much, and philosophers don’t use longer sentences or words than the other social scientists.
what’s next
This analysis is not language-specific - what makes bad writing bad is the same set of flaws in English and in Portuguese. But perhaps this analysis is culture-specific? For instance, what passes for economics in Brazil is much different than what we find on the American Economic Review - there is a lot more “problematization of paradigms” in the tropics, so to speak. So I wonder how things would change if I used American articles instead. I’m not going to scrape any gated databases, lest I get in legal trouble. But maybe Google Scholar searches might contain enough ungated results? Or maybe there is some (large enough) ungated database that I don’t know of?
the gory details
Here’s the code I used to scrape SciELO, in case it may be useful to you. (Please, be considerate. SciELO is super nice to us scrapers: it’s ungated, there are no captchas, everything is in plain HTML, and - crucially - they don’t prohibit scraping. So don’t overparallelize or otherwise disrupt their servers.)
import os import re import requests from bs4 import BeautifulSoup # get URL of each journal (active journals only) startURL = '' session = requests.Session() startHTML = session.get(startURL).text soup = BeautifulSoup(startHTML) regex = re.compile(soup.find_all('p')[4].text) # regex to filter out non-active journals sections = soup.find_all(text = regex) journalURLs = [] for i in range(len(sections)): newSection = sections[i].next_element.find_all('a') newJournalURLs = [URL.get('href') for URL in newSection] journalURLs += newJournalURLs basepath = '/Users/thiagomarzagao/Desktop/articles/' # change as needed # go to each journal for i, journalURL in enumerate(journalURLs): print 'journal num:', i + 1, 'de', len(journalURLs) k = 1 IDstart = journalURL.index('pid=') IDend = journalURL.index('&lng') journalID = journalURL[IDstart+4:IDend] print 'journal id:', journalID journalPath = basepath + journalID + '/' if os.path.exists(journalPath): continue else: os.makedirs(journalPath) journalStartHTML = session.get(journalURL.replace('serial', 'issues')).text journalSoup = BeautifulSoup(journalStartHTML) # go to each issue issuesURLs = [URL.get('href') for URL in journalSoup.find_all('a')[10:-3]][:-2] for n, issueURL in enumerate(issuesURLs): print 'issue num:', n + 1, 'de', len(issuesURLs) if issueURL: if 'pid=' in issueURL: issueStartHTML = session.get(issueURL).text issueSoup = BeautifulSoup(issueStartHTML) articlesURLs = [URL.get('href') for URL in issueSoup.find_all('a', text = u'texto em Portugu\u00EAs')] if len(articlesURLs) > 0: # go to each article and scrape it for articleURL in articlesURLs: articleHTML = session.get(articleURL).text articleSoup = BeautifulSoup(articleHTML) articleTextList = [p.text for p in articleSoup.find_all('p')] articleText = '' for piece in articleTextList: articleText += piece # save article to disk with open(journalPath + str(k) + '.txt', mode = 'wb') as fbuffer: fbuffer.write(articleText.encode('utf8')) k += 1
The code above will yield a little garbage: a few articles not in Portuguese and some texts that are not articles (copyright notices mostly). Not enough garbage to be worth fixing though.
To parse the sentences I used the following regular expression, which I stole from here.
regex = re.compile("[^.!?\\s]" + "[^.!?]*" + "(?:" + " [.!?]" + " (?!['\"]?\\s|$)" + " [^.!?]*" + ")*" + "[.!?]?" + "['\"]?" + "(?=\\s|$)", re.MULTILINE)
To make the pie charts I used d3pie, which is amazing tool: you make the charts interactively and d3pie generates the code for you. (That sort of defeats the purpose of these posts, which is to help me practice D3, but it was just so quick and easy that I couldn’t resist.) To make the bar charts I just used plain D3. Here’s the code for the first bar chart (the code is almost the same for the others):
<!DOCTYPE html> <meta charset="utf-8"> <style> .axis path, .axis line { fill: none; stroke: black; } .axis text { font-family: sans-serif; font-size: 16px; } #tooltip { position: absolute; width: auto; height: auto; padding: 10><span id="value">100</span> </p> </div> <script src="d3/d3.min.js"></script> <script> var margins = { top: 12, left: 150, right: 24, bottom: 24 }, legendPanel = { width: 0 }, width = 500 - margins.left - margins.right - legendPanel.width + 150, height = 136 - margins.top - margins.bottom, dataset = [{ data: [{ month: 'humanities & social', count: 0.00080 }, { month: 'biological & earth', count: 0.00012 }, { month: 'exact', count: 0.00017 }], name: '' } ], series = dataset.map(function (d) { return d.name; }), dataset = dataset.map(function (d) { return d.data.map(function (o, i) { // Structure it so that your numeric // axis (the stacked amount) is y return { y: o.count, x: o.month }; }); }), stack = d3.layout.stack(); stack(dataset); var dataset = dataset.map(function (group) { return group.map(function (d) { // Invert the x and y values, and y0 becomes x0 return { x: d.y, y: d.x, x0: d.y0 }; }); }), svg = d3.select('body') .append('svg') .attr('width', width + margins.left + margins.right + legendPanel.width) .attr('height', height + margins.top + margins.bottom) .append('g') .attr('transform', 'translate(' + margins.left + ',' + margins.top + ')'), xMax = d3.max(dataset, function (group) { return d3.max(group, function (d) { return d.x + d.x0; }); }), xScale = d3.scale.linear() .domain([0, xMax]) .range([0, width]), months = dataset[0].map(function (d) { return d.y; }), yScale = d3.scale.ordinal() .domain(months) .rangeRoundBands([0, 100], .1), xAxis = d3.svg.axis() .ticks(5) .scale(xScale) .orient('bottom'), yAxis = d3.svg.axis() .scale(yScale) .orient('left'), colours = d3.scale.category10(), groups = svg.selectAll('g') .data(dataset) .enter() .append('g') .style('fill', function (d, i) { return colours(i); }), rects = groups.selectAll('rect') .data(function (d) { return d; }) .enter() .append('rect') .attr('x', function (d) { return xScale(d.x0); }) .attr('y', function (d, i) { return yScale(d.y); }) .attr('height', function (d) { return yScale.rangeBand(); }) .attr('width', function (d) { return xScale(d.x); }) .on('mouseover', function (d) { var xPos = parseFloat(d3.select(this).attr('x')) / 2 + width / 2; var yPos = parseFloat(d3.select(this).attr('y')) + yScale.rangeBand() / 2; d3.select('#tooltip') .style('left', xPos + 'px') .style('top', yPos + 'px') .select('#value') .text(d.x); d3.select('#tooltip').classed('hidden', false); }) .on('mouseout', function () { d3.select('#tooltip').classed('hidden', true); }) svg.append('g') .attr('class', 'axis') .attr('transform', 'translate(0,' + height + ')') .call(xAxis); svg.append('g') .attr('class', 'axis') .call(yAxis); series.forEach(function (s, i) { svg.append('text') .attr('fill', 'white') .attr('x', width + margins.left + 8) .attr('y', i * 24 + 24) .text(s); svg.append('rect') .attr('fill', colours(i)) .attr('width', 60) .attr('height', 20) .attr('x', width + margins.left + 90) .attr('y', i * 24 + 6); }); </script> </body>
This is it! | http://thiagomarzagao.com/2015/03/01/measuring-academese/ | CC-MAIN-2017-30 | refinedweb | 1,975 | 60.21 |
Hello:
I am trying to drive some 7 segment displays with the Edison (using Arduino expansion board) and the MAX7219 shift register. I am 99% sure I got the SPI bus up an running using the echo commands per the hardware guide, but I am not sure how to align the clock speed between the Edison and MAX7219. I am using the following LEDS:
I am using the LEDControl.h library in my Arduino sketch as it worked quickest with the Uno. My problem is that I am new to SPI and not sure how to adjust the clock speed to get the Edison aligned with the MAX7219. Does anyone have a suggestion on doing this in the Arduino environment? Do I need to make some type of mod to the LEDControl.h library? Any advice would be much appreciated. Arduino sample code I am using is below:
// Initialization for Small 7 Segment Displays
# include "LedControl.h"
LedControl lc=LedControl(12,11,10,1);
void setup() {
lc.shutdown(0,false);
/* Set the brightness to a medium values */
lc.setIntensity(0,10);
/* and clear the display */
lc.clearDisplay(0);
}
void loop() {
// Strike Test
strikeZero();
delay(1000);
strikeOne();
delay(1000);
strikeTwo();
delay(1000);
void strikeZero(){
lc.setDigit(0,1,0,false);
delay(10);
}
void strikeOne(){
lc.setDigit(0,1,1,false);
delay(10);
}
void strikeTwo(){
lc.setDigit(0,1,2,false);
delay(10);
}
Link Copied
Hi Frank_1985,
I'm curious about what echo commands you are referring to. I've checked the LedControl.h library available here: GitHub - wayoda/LedControl: An Arduino library for MAX7219 and MAX7221 Led display drivers and it seems that you don't have to set anything with the SPI; the library does it for you. However, I could be wrong since I haven't tested it yet.
Anyhow, how are you setting the SPI? Are you using the Arduino environment for it?
Regards,
Diego
Hi Diego,
Thanks for the response. My understanding from the Intel Edison Kit for Arduino Hardware guide is that (from section 11.7 ) in order to Configure IO10 through IO13 for SPI connectivity, you have to configure numerous GPIOs using echo commands on the Linux side...for example:
# echo 111 > /sys/class/gpio/export
Since the guide says to do this, I assumed that these pins were not configured for SPI connectivity by default. This has nothing to do with my Arduino code or using the LEDcontrol library, I was just under the impression from the hardware guide that the board is not configured for SPI connectivity out of the box and it requires making these commands on the Linux side before these pins are ready for SPI.
So in response your question about how am I setting SPI, the answer is that I am not. I have only configured the Edison for SPI connectivity per the directions in the Hardware Guide. After doing this, uploading the sketch with the default LEDcontrol.h library still does not work on the Edison. My guess is that I need to change "byte spidata[16]" (shown below) in the LedControl.h file. Once again I am new to SPI, but my guess is that "byte spidata[16]" shown in the code below corresponds to the 16MHz clock speed of the Arduino? Would this mean that I can just change the "16" to "100" to match up with the 100MHz clock in the Edison? I tried that and it did not work but I will try again.
Also, I wonder if the clockspeed is being divided somewhere in the LEDcontrol library? The Uno has a 16MHz clock and the datasheeet for the MAX7219 indicates the maximum for incoming data is 10MHz.
Any thoughts or comments would be much appreciated. Thanks!class LedControl { private : /* The array for shifting the data to the devices */ byte spidata[16]; /* Send out a single command to the device */ void spiTransfer(int addr, byte opcode, byte data); /* We keep track of the led-status for all 8 devices in this array */ byte status[64]; /* Data is shifted out of this pin*/<td class="blob-...
Hi Frank_1985,
You are correct. That's the way you should configure the SPI interface, however, when using an Arduino sketch, the SPI interface is automatically configured so there is no need to run the echo commands.
Regarding the LedControl.h library, if it works fine on the Arduino UNO but it doesn't work on Edison, the issue might be that the library is not compatible with the Edison architecture.
The line "byte spidata[16]" is not related to the SPI clock. It defines a byte array of 16 values/positions. If you change "16" to "100" you are defining an array of 100 values/positions.
As I said above, this library might not be compatible with Edison. I recommend you to try to write a new library for the LED driver. You could use the SPI library available in the Arduino IDE which is Edison compatible. If you are using the Arduino IDE 1.6.0, you can check the SPI.h/SPI.cpp files in the following directory: C:\...\arduino-1.6.0+Intel\hardware\intel\i686\libraries\SPI\src
Regards,
Diego
Diego,
Thanks again for the response. I guess what is confusing me is the fact that there is an Intel sponsored Instructable that gave me the impression that the LedControl.h library does work with the Edison. The main reason I started working on this project using the MAX7219 driver and the Intel Edison was because I felt rather assured that the LedControl.h library would work based on the Instructable (which Intel also seems to have sponsored).
After reviewing the Instructable again, I did find it odd that the Arduino sketch for was set to the Arduino Yun in the IDE when I downloaded the .Ino file. Watching the video again, it looks like they never even show the LED matrix being used with the Edison. Instead they have it connected to an Uno when they are playing Pong. This all seems very misleading. The link to the Instructable is below. Controlling An LED Matrix - All
Do you have any Arduino Sketches using the SPI library that you could forward along that you believe will work instantly with the MAX7219 driver?
Thanks Again
Hi Frank_1985,
You're right, I've checked the Instructable and it looks like everything should work on Edison but I tested the MatrixStaticAnimation code available and I couldn't get any signal on pins 10, 11 and 12. Then I tested the LCDemo7Segment example code available in the LedControl library and again, I got no response on pins 10, 11, 12. It seems that this library doesn't work on Edison.
Unfortunately, I'm not aware of any sketch for the MAX7219 driver. You would have to write one for your application. I recommend you to check the examples available in the Arduino IDE for the SPI library. You might find them useful to see what methods can be used in the SPI communication.
Regards,
Diego | https://community.intel.com/t5/Intel-Makers/Using-MAX7219-LED-Driver-With-Intel-Edison/td-p/530721 | CC-MAIN-2021-21 | refinedweb | 1,177 | 72.36 |
C# Keywords
Keywords are predefined sets of reserved words that have special meaning in a program. The meaning of keywords can not be changed, neither can they be directly used as identifiers in a program.
For example,
long mobileNum;
Here,
long is a keyword and mobileNum is a variable (identifier).
long has a special meaning in C# i.e. it is used to declare variables of type
long and this function cannot be changed.
Also, keywords like
long,
int,
char, etc can not be used as identifiers. So, we cannot have something like:
long long;
C# has a total of 79 keywords. All these keywords are in lowercase. Here is a complete list of all C# keywords.
Although keywords are reserved words, they can be used as identifiers if
@ is added as prefix. For example,
int @void;
The above statement will create a variable @void of type
int.
Contextual Keywords
Besides regular keywords, C# has 25 contextual keywords. Contextual keywords have specific meaning in a limited program context and can be used as identifiers outside that context. They are not reserved words in C#.
If you are interested to know the function of every keywords, I suggest you visit C# keywords (official C# docs).
C# Identifiers
Identifiers are the name given to entities such as variables, methods, classes, etc. They are tokens in a program which uniquely identify an element. For example,
int value;
Here,
value is the name of variable. Hence it is an identifier. Reserved keywords can not be used as identifiers unless
@ is added as prefix. For example,
int break;
This statement will generate an error in compile time.
To learn more about variables, visit C# Variables.
Rules for Naming an Identifier
- An identifier can not be a C# keyword.
- An identifier must begin with a letter, an underscore or
@symbol. The remaining part of identifier can contain letters, digits and underscore symbol.
- Whitespaces are not allowed. Neither it can have symbols other than letter, digits and underscore.
- Identifiers are case-sensitive. So, getName, GetName and getname represents 3 different identifiers.
Here are some of the valid and invalid identifiers:
Example: Find list of keywords and identifiers in a program
Just to clear the concept, let's find the list of keywords and identifiers in the program we wrote in C# Hello World.
using System; namespace HelloWorld { class Hello { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
The "Hello World!" inside
WriteLine method is a string literal. | https://cdn.programiz.com/csharp-programming/keywords-identifiers | CC-MAIN-2020-24 | refinedweb | 411 | 67.45 |
See Also: Pair Members
The System.Web.UI.Pair class is used as a basic structure to store two related objects. It is a utility class that is used in various ways throughout ASP.NET, such as during page state management tasks or in configuration section handlers. You can use the System.Web.UI.Pair class in your own code anywhere that you need a structure to contain two related objects and where data hiding is not essential. The System.Web.UI.Pair class does not encapsulate its object references, Pair.First and Pair.Second, in properties; it exposes them directly to all calling code as public class fields.
The System.Web.UI.Pair class can be used in several ways in page state persistence implementations. The most common use is as a container for both the Control.ViewState and PageStatePersister.ControlState collections. In this case, the Pair.First property is used for Control.ViewState, and the Pair.Second for PageStatePersister.ControlState. | http://docs.go-mono.com/monodoc.ashx?link=T%3ASystem.Web.UI.Pair | CC-MAIN-2017-51 | refinedweb | 162 | 54.08 |
Deletes a (non-owning) RCPNode but not it's underlying object in case of a throw. More...
#include <Teuchos_RCPNode.hpp>
Deletes a (non-owning) RCPNode but not it's underlying object in case of a throw.
This class is used in contexts where RCPNodeTracer::addNewRCPNode(...) might thrown an exception for a duplicate node being added. The assumption is that there must already be an owning (or non-owning) RCP object that will delete the underlying object and therefore this class should *not* call delete_obj()!
Definition at line 979 of file Teuchos_RCPNode.hpp.
Definition at line 982 of file Teuchos_RCPNode.hpp.
Called with node_!=0 when an exception is thrown.
When an exception is not thrown, the client should have called release() before this function is called.
Definition at line 990 of file Teuchos_RCPNode.hpp.
Definition at line 999 of file Teuchos_RCPNode.hpp.
Releaes the RCPNode pointer before the destructor is called.
Definition at line 1004 of file Teuchos_RCPNode.hpp. | http://trilinos.sandia.gov/packages/docs/r10.8/packages/teuchos/doc/html/classTeuchos_1_1RCPNodeThrowDeleter.html | CC-MAIN-2014-15 | refinedweb | 159 | 60.92 |
Hot Deploy Seam Apps on Tomcat?David Geary Jul 18, 2006 1:20 PM
I've got my Seam app running in Tomcat 5.5 with JBoss embedded EJB. I've got a configuration file wired to the application's build directory, so I can hot-deploy the app.
I'm able to run the application, but when I make a change and refresh the browser, Tomcat hangs and I have to restart it.
Does anyone know why this is happening or how I can resolve the issue? I applaud Seam's noble goal of providing Rails-like ease-of-development for JEE, but if I have to restart Tomcat everytime I make a change to the application, then that ease-of-development is greatly diminished.
david geary
1. Re: Hot Deploy Seam Apps on Tomcat?Gavin King Jul 18, 2006 1:26 PM (in response to David Geary)
It is possible (but fiddly) to set up eclipse to build to an exploded directory structure, and point JBoss to that expolded directory.
2. Re: Hot Deploy Seam Apps on Tomcat?David Geary Jul 18, 2006 1:32 PM (in response to David Geary)
I'm not familiar with the English adjective "fiddly"--perhaps it comes from the same place that "outjection" comes from. 8-)
Anyway, thanks for the quick response: what you describe is exactly what I'm doing with Tomcat. I've got IDEA set up to create an exploded directory that I access via Tomcat. But it doesn't work.
I'd really like to stick with Tomcat instead of switching to JBoss. Is there any obvious reason why hot deploy should work with JBoss but not with Tomcat? Does it have something to do with embedded EJB?
Thanks,
david geary
3. Re: Hot Deploy Seam Apps on Tomcat?Gavin King Jul 18, 2006 1:37 PM (in response to David Geary)
Tomcat hotdeploy is basically completely broken and AFAIK can't be made to work reliably.
4. Re: Hot Deploy Seam Apps on Tomcat?JBoss Fan Jul 18, 2006 8:49 PM (in response to David Geary)
"gavin.king@jboss.com" wrote:
Tomcat hotdeploy is basically completely broken and AFAIK can't be made to work reliably.
Sorry for xposting,
but can you elaborate more on what it is that badly broken?
Thx
5. Re: Hot Deploy Seam Apps on Tomcat?Rob Jellinghaus Jul 28, 2006 1:44 AM (in response to David Geary)
Basically Tomcat just can't reliably shut down a running webapp, because they are sloppy with their classloaders. You wind up with all kinds of static class references that aren't cleaned up properly, and the reloading of your webapp may or may not work. You can get weird ClassCastExceptions post-reloading because the old classloader's classes are still hanging around.
At least that's been my experience....
Cheers,
Rob
6. Re: Hot Deploy Seam Apps on Tomcat?Christian Bauer Jul 28, 2006 7:54 AM (in response to David Geary)
For future reference in case anybody finds this thread:
public class SomeServlet extends HttpServlet {
private static ClassLoader myClassloader;
public init(ServletConfig cfg) {
myClassloader = getClass().getClassLoader();
}
}
This servlet breaks context reloading in Tomcat, the context leaks a WebappClassloader per reload (and therefore other static variable values, so it can be a lot of memory that is never freed). Since many frameworks (Hibernate, Struts, etc.) use such a pattern, reloading in Tomcat can be considered currently broken. | https://developer.jboss.org/message/454983 | CC-MAIN-2016-30 | refinedweb | 574 | 65.01 |
Now that we know how to perform queries with
.getByX methods, it is time for us to move on to the other query method variants. RTL has two other categories of query methods called
.queryByX and
.findByX.
Look at the code below. It shows the code for a simple component that renders a header with the text
'Hello World!' and then changes the text to
'Goodbye!' 500ms after the user clicks a button. We will be using this
App component to demonstrate the different query types.
import { useState } from 'react'; const App = () => { const [text, setText] = useState('Hello World!'); // Changes header text after interval of 500ms const handleClick = () => { setTimeout(() => { setText('Goodbye!'); }, 500); }; return ( <div> <h1>{text}</h1> <button onClick={handleClick}>click me</button> </div> ) }; export default App;
Let’s start with the
.queryByX variants. The
.queryByX methods return
null if they don’t find a DOM node, unlike the
.getByX methods which throw an error and immediately cause the test to fail. This is useful when asserting that an element is NOT present in the DOM.
In this example, we want to confirm that the
header does not (yet) contain the text
'Goodbye':
import App from './components/App'; import { render, screen } from '@testing-library/react'; test('Header should not show Goodbye yet', () => { // Render App render(<App />); // Attempt to extract the header element const header = screen.queryByText('Goodbye!'); // Assert null as we have not clicked the button expect(header).toBeNull(); });
By using the
.queryByText(), variant when there is no element with the text
'Goodbye!', the value
null is returned and we can successfully validate this with
expect(header).toBeNull(). If the
.getByText() method were used instead, the test would fail immediately due to the error rather than continuing on to the
expect() assertion.
Next, let’s discuss the
.findByX variants. The
.findByX methods are used to query for asynchronous elements which will eventually appear in the DOM. For example, if the user is waiting for the result of an API call to resolve before data is displayed. The
.findByX methods work by returning a Promise which resolves when the queried element renders in the DOM. As such, the
async/
await keywords can be used to enable asynchronous logic.
In this example, we want to confirm that the
header will display the text
'Goodbye' after the button is clicked. This example uses the
userEvent library, which will be covered in depth in the next exercise, to simulate clicking on the button.
import App from './components/App'; import { render, screen } from '@testing-library/react'; test('should show text content as Goodbye', async () => { // Render App render(<App />); // Extract button node const button = screen.getByRole('button'); // click button userEvent.click(button); // Wait for the text 'Goodbye!' to appear const header = await screen.findByText('Goodbye!'); // Assert header to exist in the DOM expect(header).toBeInTheDocument(); });
In the example above we use
.findByText() since the
'Goodbye!' message does not render immediately. This is because our
handleClick() function changes the text after an interval of 500ms. So, we have to wait a bit before the new text is rendered in the DOM.
Observe the
async and
await keywords in the example above. Remember that
findBy methods return a Promise and thus the callback function that carries out the unit test must be identified as
async while the
screen.findByText() method must be preceded by
await.
Note: Before you start the instructions, go to the AddThoughtForm.js file and observe the
handleSubmit()function. For just this exercise, we’ve modified this function slightly with a
setTimeout(), so that the thoughts get added asynchronously. Go ahead and post a thought in the App. Notice how there is a slight lag when the thought gets posted after you click the
Addbutton.
Instructions
Suppose we wish to post a new thought with the text content
'Oreos are delicious'. Before we do that though, we want to make sure that this thought isn’t already in our list of thoughts.
In the first test of Thought.test.js, use the
.queryByText() method and search for a thought with the text content
'Oreos are delicious'. Assign the result of your query to a variable called
emptyThought.
In the first test of Thought.test.js, use an appropriate assertion to check if the result of your query is
null.
To confirm that you did this properly, run
npm test in the terminal. The first test should pass!
The second test of the Thought.test.js file mimics a user posting a thought with the text content
'Oreos are delicious' using the
userEvent library (we’ll cover how you can do this in the next exercise!).
Below, we use the
.getByText() method to assert that the thought is present in the DOM. However, since the thought is getting posted asynchronously,
.getByText() is unable to retrieve it and the test is failing (confirm for yourself by running
npm test).
Replace the
.getByText() method with a call to the appropriate query variant such that the test waits for the element with the text
'Oreos are delicious' to appear.
Run
npm test in your terminal | https://www.codecademy.com/courses/learn-react-testing/lessons/react-testing-library/exercises/different-query-methods | CC-MAIN-2021-39 | refinedweb | 845 | 67.45 |
On Mon, 19 Feb 2001, Itai Tavor wrote: > You posted your questions 3 days ago, so maybe you found a solution > by now... but this might still be useful to you. I just unwrapped the visitor pattern into an psuedo-case statement <grin>. > - I'm passing _ explicitly instead of relying on binding. I vaguely > recall reading something about a problem binding the namespace. It > might be fixed in the latest Python Scripts, I haven't tried the CVS > version yet. This appeared to be the key. I changed my 'accept(me)' call to read 'accept(me,_=_)', and everything started working. Thanks very much! > - visitLineItem is called in the context of an OrderLineItem, so no > <dtml-with item> is needed. I had actually tried that and gotten an even less intelligable error message. So now I've reverted to that form and it works great. > - If you wanted the visitor to implement looping over the items > (which is how the GoF do it) you could easily make something like: > > Order.displayItemsVisitor.displayItems (DTML Method): > <dtml-in line_items> > <tr> > <dtml-var "_['sequence-item'].accept(container, _)"> > </tr> > </dtml-in> Yeah, that's more or less what I do. My display dtml-method gets passed the list of objects, and it does the loop (implementing the batching logic for dtml-in) calling accept on the items in the list. I need to rename my folder to make it's purpose clearer, though <grin>. > BTW, I never thought of using a visitor for this until you brought it > up, so thanks! What I really like about it is that the same 'accept' > method can be used by multiple visitors, each one implementing a > different view of the object. So I can have displayItemsVisitor, > displayItemsCompactVisitor, and displayItemsEditableVisitor, all Yeah, exactly. displayItemsEditableVisitor is why I chose to implement the visitor pattern. I've wound up doing it another way (checking the auth of the logged in user and putting in a button), but I suspect I'll have another Visitor before I'm through with the project. Thanks again for your help. --RDM _______________________________________________ Zope-Dev maillist - [EMAIL PROTECTED] ** No cross posts or HTML encoding! ** (Related lists - )
Re: [Zope-dev] AttributeError validate using the Visitor pattern
R. David Murray Fri, 23 Feb 2001 08:21:15 -0800
- [Zope-dev] AttributeError validate using the Visitor patt... R. David Murray
- Re: [Zope-dev] AttributeError validate using the Vis... Itai Tavor
- R. David Murray | https://www.mail-archive.com/zope-dev@zope.org/msg04945.html | CC-MAIN-2017-51 | refinedweb | 409 | 66.23 |
Prefetching lets you start React apps without loading spinners. Gatsby introduced this concept with
staticQuery, react-query and NextJS make the pattern easier 😍
CodeWithSwiz is a twice-a-week live show. Like a podcast with video and fun hacking. Focused on experiments. Join live Wednesdays and Sundays
It took two episodes to figure this out and verify it works. Here they are 👇
We're building towards a headless CMS. The component that needs prefetching is a social card.
Prefetchable component
export const SocialCardImage = ({ title }) => {const cardQuery = useSocialCardQuery(title)if (cardQuery.isLoading) {return <Spinner />}return <Image src={cardQuery.data.url} />}
The
SocialCardImage component uses a query to create a social card for a title. When the query
isLoading, we show a spinner, when it's done, we show the image.
We built the
useSocialQuery custom hook in a past CodeWithSwiz episode. A thin wrapper on react-query's
useQuery makes it more reusable.
export function useSocialCardQuery(title) {return useQuery(["social-card", title], fetchSocialCard, {staleTime: 5000,})}
Name the query
"social-card", add
title as a parameter, use the
fetchSocialCard data loader, and set
staleTime to 5 seconds. Helps with query reuse and avoids refetching.
The data loader talks to my screenshot AWS Lambda to create social cards.
async function fetchSocialCard(key, title) {if (title) {const res = await fetch(`{title}`)return res.json()} else {return null}}
Basic
fetch() request to a lambda. The lambda spins up a Chrome browser, loads a special page on my blog, renders the card, takes a screenshot, saves it to S3, returns a URL.
What is prefetching
The
SocialCardImage component works great. Slow, but great.
Pop it on a page, add input from a form, users get a social card. Everyone expects a spinner. Can't load something before the user says what.
What if you load this as a new page?
Fill out the form, click submit, get redirected. Would you expect loading spinners like this?
Or would you think "The site has data, why am I waiting twice?"
Granted, it's 2020 and you wouldn't expect the site to reload after a form submit. But I wanted to figure out prefetching 😇
Prefetching data with NextJS
NextJS offers two convenient ways to pre-define data for your page:
getStaticPropsfor static data
getServerSidePropsfor dynamic server data
One is meant for SSR – server side rendering – and the other for SSH – server side generation. Which is which feels unclear from the docs.
Both enable you to bake data into the initial HTML for your page. The difference is when this baking happens.
Both work the same way:
- NextJS starts building a page
- Calls your exported
getStaticPropsor
getServerSidePropsfunction
- Function does stuff
- Returns a
propsobject
- NextJS renders your page with those props
getServerSideProps with NextJS dynamic routing
To render the
SocialCardImage with a pre-defined article title based on a URL slug, you'd write a page like this:
// pages/[slug].jsexport async function getServerSideProps(context) {const { slug } = context.paramsconst article = magicallyReadArticle(slug)return {props: {article}}}export default ArticlePreview({ article }) {return <SocialCardImage title={article.title} />}
Naming your file
[slug] gives you nextjs dynamic routing – file runs for any
/this-is-slug URL and renders the
ArticlePreview page component.
NextJS runs
getServerSideProps with the routing context and you use the slug to find your article in a storage system. We used temp files but that doesn't work in production.
The function returns your
article as a prop, it gets passed into the page component, and the user gets a preview.
And they get a spinner.
Add React Query to the mix
You can fix the spinner by manually fetching the social card in
getServerSideProps. And that means duplicating your logic, dealing with checking 2 data sources, etc.
You've built the query before. You've got a component that works. Why rebuild it all?? 🤨
Here's what you do instead:
- Wrap your app in React Query cache
- Prefetch query in
getServerSideProps
- Dehydrate the full cache on page load
- Keep frontend code the same
// pages/_app.jsconst queryCache = new QueryCache()function MyApp({ Component, pageProps }) {return (<ReactQueryCacheProvider queryCache={queryCache}><Hydrate state={pageProps.dehydratedState}><ThemeProvider theme={theme}><Component {...pageProps} /></ThemeProvider></Hydrate></ReactQueryCacheProvider>)}
Create a new query cache, wrap the app in
<ReactQueryCacheProvider> and
<Hydrate>. They're react-query's context providers for internal state sharing.
Then prefetch your queries:
async function prefetchQueries(article) {const queryCache = new QueryCache()await queryCache.prefetchQuery(["social-card", article.title],fetchSocialCard)return dehydrate(queryCache)}export async function getServerSideProps(context) {const { slug } = context.paramsconst article = magicallyReadArticle(slug)return {props: {dehydratedState: await prefetchQueries(article),article,},}}
We can't reuse
useSocialCardQuery because we're doing something different – prefetching.
Replace
useQuery with
queryCache.prefetchQuery and pass that into the
dehydrate() call from react-query. Put the full result in the
dehydratedState prop.
The
<Hydrate> component reads that from its props
<Hydrate state={pageProps.dehydratedState}>
And you get a page load with no spinners
Okay the UX around that form submit needs work but you get the idea. No spinners! 🎉
Why I like this
Way easier to use than Gatsby's
useStaticQuery. Same code works with both static data and dynamic updates later.
Data baking in Gatsby is more suited to pages that don't turn into single-page-apps. This works for both 😍️ | https://swizec.com/blog/prefetch-data-with-react-query-and-nextjs-codewithswiz-8-9 | CC-MAIN-2020-50 | refinedweb | 869 | 50.12 |
What is Refresh Controller –
In this article, I am going to discuss “What is Refresh Controller in React Native”, I am sure you see the multiple apps where when you pull the app that refresh your data, you can see this functionality in Facebook, Instagram apps.
By using Pull to refresh functionality we refresh the data in our apps, where we pull the screen towards the bottom to load new data.
Output Example –
Why we use RefreshController –
By using a refresh controller you can refresh the API when you pull, basically, we implement the API that when we refresh it call that API. below is an example of how we use the RefreshContrller in react native.
Pull to refresh is important for any app where you have data listing, which needs to be refreshed every second. It needs when your users spend a good amount of time on your app, and during that time, more data is generated to show users.
Pull to Refresh –
Pull to Refresh functionality is implemented using RefreshControl, this is a component of React Native. we use the RefreshController inside a ScrollView, ListView and Flat list to add pull to refresh functionality. When the ScrollView is at
scrollY: 0, swiping down an
onRefresh event.
In our example, we are using a FlatList component to display the list. The FlatList code with
RefreshControl looks like this
So here i am showing the example of RefreshControl, let’s start…
Post steps –
We integrate the RefreshControl functionality in the app we follow this step-by-step manner to explore the pull to refresh feature in our app. These are the steps.
STEPS –
- Creating a react-native app
- Import the component
- Set the data into state
- Design the view
- Definition of _onRefresh() function
- Run the app on an Android and iOS device and test
Note – For implementing RefreshController you didn’t need to install any third-party there is a react native component called RefreshControl which we use for refreshing the data.
Step 1 – Creating a react-native app
First we create a react-native app for implementing refresh controller.
react-native init RefreshControllerExample
Step 2 – Import the component
Import the RefreshController where you want to integrate the pull to refresh functionality.
import { RefreshControl } from 'react-native';
Step 3 – Set the data into state
Set the data into state for getting the data into list.
constructor(props) { super(props); this.state = { initialData: [ { title: "test1", id: "1" }, { title: "test2", id: "2" }, { title: "test3", id: "3" }, { title: "test4", id: "4" }, { title: "test5", id: "5" } ]; } }
Step 4 – Design the view
Now we design the view within the render method by using this FlatList, in FlatList there is a prop called refreshControl.
render(){ return( <SafeAreaView style={styles.container}> //Example with flatlist <FlatList data={initialData} renderItem={({ item }) => <Text>{item.title}<Text/>} keyExtractor={item => item.id} refreshing={this.state.refreshing} refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={this._onRefresh}/>}/> //Example with ScrollView <ScrollView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh} /> } /> //Example with ListView <View style={{flex:1}}> <ListView refreshControl={this._onRefresh()} dataSource={this.state.initialData} renderRow={(text) => this._renderListView(text)}> </ListView> </View> </SafeAreaView> ) }
Step 5 – Definition of _onRefresh() function
Here in _onRefresh function you need to implement the API, which you want to called at the time of when we pull to refresh.
_onRefresh = () => { setRefreshing(true);//here you set the loader true if (listData.length < 10) { try { let response = await fetch( ' ); let responseJson = await response.json(); this.setState({ initialData: responseJson }) setRefreshing(false)//set the loader false } catch (error) { console.error(error); } } else{ console.log('No more new data available'); setRefreshing(false)//set the loader false } }
Setup the App in iOS –
To set up the refresh control in iOS what you all need to run the following pod command to set up it in iOS.
cd ios && pod install
Run the React Native App –
Open the terminal and jump into your project path then run the following command.
react-native run-android // for android or react-native run-ios // for iOS
So we completed the react-native refresh control which is “What is Refresh Controller in React Native“.
You can find my post on medium as well click here please follow me on medium as well.
You can find my next post here.
If have any query/issue, please feel free to ask.
Happy Coding Guys. | https://www.itechinsiders.com/what-is-refresh-controller-in-react-native/ | CC-MAIN-2022-21 | refinedweb | 719 | 53.41 |
sorry for this noob question... let's say we have :
class TestMe
attr_reader :array
def initialize
@array = (1..10).to_a
end
>> a = TestMe.new
=> #<TestMe:0x00000005567228 @x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>
>> a.array.map! &:to_s
=> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
>> a.array
=> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
You cannot do much with
attr_reader, because
attr_reader :array generates the following code:
def array; @array; end
If you don't want to expose array instance, you can return Enumerator of this array (external iterator). Enumerator is a good iterator abstraction and does not allow you to modify original array.
def array; @array.to_enum; end
What good for encapsulation and what not depends on the abstraction your class presents. Generally this is not good for encapsulation to expose internal state of an object, including internal array. You may want to expose some methods that operate on the
@array instead of exposing
@array (or even its iterator) itself. Sometimes this is fine to expose array - always look at the abstraction your class presents. | https://codedump.io/share/GgeMsKI88oop/1/ruby--how-to-prevent-modification-of-an-array-instance-variable-through-an-attribute-reader | CC-MAIN-2017-51 | refinedweb | 185 | 56.76 |
Spec-ulation Keynote - Rich Hickey
646 15 51010
By appleflaxen 2017-09-20:
Rich Hickey has a wonderful talk about it.
"Spec-ulation" -
Which I fully agree with, basically there are no major, minor, patch level changes, in reality every change is a possible breaking changes, because we don't control what downstream is doing with our software..
TL;DR: use something like clojure.set/rename or clojure.set/rename-keys.
Harsh Advice
It's my impression (mostly based on) that the "clojure way" is to think about your design thoroughly enough up-front that you're willing to stick with it. (c.f. "hammock-driven development").
If you do wind up needing to make this sort of change, create another set of functions (maybe use the same names in a different ns) that use the new keyword names. Now have these call your originals, or your originals call the new ones (whichever makes more sense). Update your docs to recommend that people use the new version.
Spend more time in the hammock.
More generally (and hopefully helpfully):
Try to keep your functions small and decoupled enough that you're just passing around a few values anyway. If you're calling something that needs a :body, how much of the rest of the associated values in that map does it really need?
Can you refactor those parts into their own functions to reduce the coupling? Can you supply/return higher-order functions to isolate functionality that seems like it needs to be all snarled up with your :content handling? (The "partial" function is your friend here).
Full-blown explanation (complete with personal whining):
These days, a big part of this involves using maps with namespaced keywords, along with spec. Since you can alias your namespaces, this actually seems to make the particular problem you're addressing worse: you can't even reliably do a simple search/replace over your project.
I'm going through a lot of pain in this regard right now, revisiting some code I wrote while I was figuring this out. I realized that I got the namespaces wrong.
If anyone else were actually using my library, the real answer would be to just accept that what I started with is ugly, broken, and poorly planned. I could write new functions that are more expressive than what I have now (so, in your example, they'd use a map that contains :bar/content rather than :foo/body). Maybe mark the old functions deprecated, but accept that I can never, ever eliminate them.
Or possibly I should just deprecate that library and point existing/potential users to a new one that more closely matches what I actually want.
Actually, it's enough of a mess that the latter option is tempting. Even though I'm the only user. Renaming keys like this seems almost deliberately painful.
Based on my experience with the rest of the language, I suspect that was the case, because breaking your API is a terrible thing to do.
On the other hand, there's at least one more piece to this.
What about black-box, undocumented data that you want to be able to change at the drop of a hat? (Say you have a value that you treat like a handle, which happens to be implemented as a map). The whole OOP private undocumented implementation details stuff.
This part of your API will have functions with names like "establish-database-connection!" and "run-database-command!". The rest of it really should be pure functions that set up sequences of pending side-effects that you pass to the ones that actually change the world.
The Pedestal library is a great example of this approach. Its context maps are pretty much the exact opposite of the approach I recommended above about just using as few decoupled values as possible for any given function call...these opinions are definitely and merely my own.
Your end-user is supposed to call your functions and get back...call it a gray box. They are responsible for supplying it (without modifications) to your other functions that rely on it (which, honestly, should be pretty rare: these are really for system-boundary code that causes side-effects). If they look inside, that's their business, but I think it's fair for you to change those details.
Changing those details under the hood takes us back to your original problem: doing so is still painful.
That's another reason to be very stingy about writing code that needs this sort of thing.
Hope that helps!
Popular Videos 18
Submit Your Video
By appleflaxen 2017-09-20.
Original Thread | https://dev-videos.com/videos/oyLBGkS5ICk/Speculation-Keynote--Rich-Hickey | CC-MAIN-2018-26 | refinedweb | 778 | 62.68 |
Threading
The Java language supports concurrent programming from the ground up. This enables running two or more parts of the program concurrently. Each part of such a program is called a
thread. In a Java program, there's at least one thread, the
main thread. The main thread has the ability to create additional threads.
Thread Objects
Thread objects are created from the
Thread class. Threads can be used to run slow running processes asynchronously, such as performing networking operations of complicated Math calculations.
Defining and Starting a Thread
They are two ways to use a thread :
- Extend the Thread class
- Implement the Runnable interface
Extending the Thread Class
This is not recommended due to Java single inheritance. Once the class extends the Thread class it can no longer extend any other class.
The run method should be implemented. Code in the run method will automatically run in a separate thread when the thread object is started.
public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } }
Implement the Runnable Interface
This is the recommend way of using the threads. The class should implement the run method.
public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); } }
Starting a Thread
For a class that extends the Thread class, we can simply call the start method to start the thread as a separate execution as follows :
HelloThread thread = new HelloThread(); thread.start();
For a class that extends the Runnable interface, we can start the thread by passing it to the Thread class and calling start as follows :
HelloThread thread = new HelloThread(); new Thread(thread).start();
Or we can also use the Runnable interface anonymously as follows :
new Thread(new Runnable() { public void run() { System.out.println("Run code here in a separate thread of execution"); } }).start();
Pausing a Thread
We can pause the execution of a thread by calling the static method sleep and passing in the number of milliseconds to pause. The sleep method throws an exception, so it should be wrapped in a try-catch block.
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
Interrupting a Thread
We can interrupt a thread by calling the interrupt method. This will signal the thread to stop. | https://java-book.peruzal.com/threading/threading.html | CC-MAIN-2018-22 | refinedweb | 396 | 66.44 |
# Making C++ Exception Handling Smaller On x64
Visual Studio 2019 Preview 3 introduces a new feature to reduce the binary size of C++ exception handling (try/catch and automatic destructors) on x64. Dubbed FH4 (for \_\_CxxFrameHandler4, see below), I developed new formatting and processing for data used for C++ exception handling that is ~**60%** smaller than the existing implementation resulting in overall binary reduction of up to **20%** for programs with heavy usage of C++ exception handling.
This article in [blog](https://devblogs.microsoft.com/cppblog/making-cpp-exception-handling-smaller-x64/).
How Do I Turn This On?
----------------------
FH4 is currently **off by default** because the runtime changes required for Store applications could not make it into the current release. To turn FH4 on for non-Store applications, pass the undocumented flag “/d2FH4” to the MSVC compiler in Visual Studio 2019 Preview 3 and beyond.
We plan on enabling FH4 by default once the Store runtime has been updated. We’re hoping to do this in Visual Studio 2019 Update 1 and will update this post one we know more.
Tools Changes
-------------
Any installation of Visual Studio 2019 Preview 3 and beyond will have the changes in the compiler and C++ runtime to support FH4. The compiler changes exist internally under the aforementioned “/d2FH4” flag. The C++ runtime sports a new DLL called vcruntime140\_1.dll that is automatically installed by VCRedist. This is required to expose the new exception handler \_\_CxxFrameHandler4 that replaces the older \_\_CxxFrameHandler3 routine. Static linking and app-local deployment of the new C++ runtime are both supported as well.
Now onto the fun stuff! The rest of this post will cover the internal results from trialing FH4 on Windows, Office, and SQL, followed by more in-depth technical details behind this new technology.
Motivation and Results
----------------------
About a year ago, our partners on the [C++/WinR](https://github.com/Microsoft/xlang)[T](https://github.com/Microsoft/xlang) project came to the Microsoft C++ team with a challenge: how much could we reduce the binary size of C++ exception handling for programs that heavily used it?
In context of a program using [C++/WinRT](https://github.com/Microsoft/xlang), they pointed us to a Windows component Microsoft.UI.Xaml.dll which was known to have a large binary footprint due to C++ exception handling. I confirmed that this was indeed the case and generated the breakdown of binary size with the existing \_\_CxxFrameHandler3, shown below. The percentages in the right side of the chart are **percent of total binary size** occupied by specific metadata tables and outlined code.
[Size Breakdown of Microsoft.UI.Xaml.dll using __CxxFrameHandler3](https://40jajy3iyl373v772m19fybm-wpengine.netdna-ssl.com/cppblog/wp-content/uploads/sites/9/2019/04/fh3-breakdown-1.png)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
I won’t discuss in this post what the specific structures on the right side of the chart do (see James McNellis’s talk on how [stack unwinding works on Windows](https://www.youtube.com/watch?v=COEv2kq_Ht8) for more details). Looking at the total metadata and code however, a whopping **26.4%** of the binary size was used by C++ exception handling. This is an enormous amount of space and was hampering adoption of C++/WinRT.
We’ve made changes in the past to reduce the size of C++ exception handling in the compiler without changing the runtime. This includes dropping metadata for regions of code that cannot throw and folding logically identical states. However, we were reaching the end of what we could do in just the compiler and wouldn’t be able to make a significant dent in something this large. Analysis showed that there were significant wins to be had but required fundamental changes in the data, code, and runtime. So we went ahead and did them.
With the new \_\_CxxFrameHandler4 and its accompanying metadata, the size breakdown for Microsoft.UI.XAML.dll is now the following:
[Size Breakdown of Microsoft.UI.Xaml.dll using __CxxFrameHandler4](https://40jajy3iyl373v772m19fybm-wpengine.netdna-ssl.com/cppblog/wp-content/uploads/sites/9/2019/04/fh4-breakdown-1.png)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The binary size used by C++ exception handling drops by **64%**leading to an overall binary size decrease of **18.6%** on this binary. Every type of structure shrank in size by staggering degrees:
| | | | |
| --- | --- | --- | --- |
| **EH Data** | **\_\_CxxFrameHandler3 Size (Bytes)** | **\_\_CxxFrameHandler4 Size (Bytes)** | **% Size Reduction** |
| Pdata Entries | 147,864 | 118,260 | 20.0% |
| Unwind Codes | 224,284 | 92,810 | 58.6% |
| Function Infos | 255,440 | 27,755 | 89.1% |
| IP2State Maps | 186,944 | 45,098 | 75.9% |
| Unwind Maps | 80,952 | 69,757 | 13.8% |
| Catch Handler Maps | 52,060 | 6,147 | 88.2% |
| Try Maps | 51,960 | 5,196 | 90.0% |
| Dtor Funclets | 54,570 | 45,739 | 16.2% |
| Catch Funclets | 102,400 | 4,301 | 95.8% |
| Total | **1,156,474** | **415,063** | **64.1%** |
Combined, switching to \_\_CxxFrameHandler4 dropped the overall size of Microsoft.UI.Xaml.dll from 4.4 MB down to 3.6 MB.
Trialing FH4 on a representative set of Office binaries shows a ~10% size reduction in DLLs that use exceptions heavily. Even in Word and Excel, which are designed to minimize exception usage, there’s still a meaningful reduction in binary size.
| | | | | |
| --- | --- | --- | --- | --- |
| **Binary** | **Old Size (MB)** | **New Size (MB)** | **% Size Reduction** | **Description** |
| chart.dll | 17.27 | 15.10 | 12.6% | Support for interacting with charts and graphs |
| Csi.dll | 9.78 | 8.66 | 11.4% | Support for working with files that are stored in the cloud |
| Mso20Win32Client.dll | 6.07 | 5.41 | 11.0% | Common code that’s shared between all Office apps |
| Mso30Win32Client.dll | 8.11 | 7.30 | 9.9% | Common code that’s shared between all Office apps |
| oart.dll | 18.21 | 16.20 | 11.0% | Graphics features that are shared between Office apps |
| wwlib.dll | 42.15 | 41.12 | 2.5% | Microsoft Word’s main binary |
| excel.exe | 52.86 | 50.29 | 4.9% | Microsoft Excel’s main binary |
Trialing FH4 on core SQL binaries shows a 4-21% reduction in size, primarily from metadata compression described in the next section:
| | | | | |
| --- | --- | --- | --- | --- |
| **Binary** | **Old Size (MB)** | **New Size (MB)** | **% Size Reduction** | **Description** |
| sqllang.dll | 47.12 | 44.33 | 5.9% | Top-level services: Language parser, binder, optimizer, and execution engine |
| sqlmin.dll | 48.17 | 45.83 | 4.8% | Low-level services: transactions and storage engine |
| qds.dll | 1.42 | 1.33 | 6.3% | Query store functionality |
| SqlDK.dll | 3.19 | 3.05 | 4.4% | SQL OS abstractions: memory, threads, scheduling, etc. |
| autoadmin.dll | 1.77 | 1.64 | 7.3% | Database tuning advisor logic |
| xedetours.dll | 0.45 | 0.36 | 21.6% | Flight data recorder for queries |
The Tech
--------
When analyzing what caused the C++ exception handling data to be so large in Microsoft.UI.Xaml.dll I found two primary culprits:
1. The data structures themselves are large: metadata tables were fixed size with fields of image-relative offsets and integers each four bytes long. A function with a single try/catch and one or two automatic destructors had over 100 bytes of metadata.
2. The data structures and code generated were not amenable to merging. The metadata tables contained image-relative offsets that prevented COMDAT folding (the process where the linker can fold together identical pieces of data to save space) unless the functions they represented were identical. In addition, catch funclets (outlined code from the program’s catch blocks) could not be folded even if they were code-identical because their metadata is contained in their parents.
To address these issues, FH4 restructures the metadata and code such that:
1. Previous fixed sized values have been compressed using a variable-length integer encoding that drops >90% of the metadata fields from four bytes down to one. Metadata tables are now also variable length with a header to indicate if certain fields are present to save space on emitting empty fields.
2. All image-relative offsets that can be function-relative have been made function-relative. This allows COMDAT folding between metadata of different functions with similar characteristics (think template instantiations) and allows these values to be compressed. Catch funclets have been redesigned to no longer have their metadata stored in their parents’ so that any code-identical catch funclets can now be folded to a single copy in the binary.
To illustrate this, let’s look at the original definition for the Function Info metadata table used for \_\_CxxFrameHandler3. This is the starting table for the runtime when processing EH and points to the other metadata tables. This code is available publicly in any VS installation, look for \VC\Tools\MSVC\\include\ehdata.h:
```
typedef const struct _s_FuncInfo
{
unsigned int magicNumber:29; // Identifies version of compiler
unsigned int bbtFlags:3; // flags that may be set by BBT processing
__ehstate_t maxState; // Highest state number plus one (thus
// number of entries in unwind map)
int dispUnwindMap; // Image relative offset of the unwind map
unsigned int nTryBlocks; // Number of 'try' blocks in this function
int dispTryBlockMap; // Image relative offset of the handler map
unsigned int nIPMapEntries; // # entries in the IP-to-state map. NYI (reserved)
int dispIPtoStateMap; // Image relative offset of the IP to state map
int dispUwindHelp; // Displacement of unwind helpers from base
int dispESTypeList; // Image relative list of types for exception specifications
int EHFlags; // Flags for some features.
} FuncInfo;
```
This structure is fixed size containing 10 fields each 4 bytes long. This means every function that needs C++ exception handling by default incurs 40 bytes of metadata.
Now to the new data structure (\VC\Tools\MSVC\\include\ehdata4\_export.h):
```
struct FuncInfoHeader
{
union
{
struct
{
uint8_t isCatch : 1; // 1 if this represents a catch funclet, 0 otherwise
uint8_t isSeparated : 1; // 1 if this function has separated code segments, 0 otherwise
uint8_t BBT : 1; // Flags set by Basic Block Transformations
uint8_t UnwindMap : 1; // Existence of Unwind Map RVA
uint8_t TryBlockMap : 1; // Existence of Try Block Map RVA
uint8_t EHs : 1; // EHs flag set
uint8_t NoExcept : 1; // NoExcept flag set
uint8_t reserved : 1;
};
uint8_t value;
};
};
struct FuncInfo4
{
FuncInfoHeader header;
uint32_t bbtFlags; // flags that may be set by BBT processing
int32_t dispUnwindMap; // Image relative offset of the unwind map
int32_t dispTryBlockMap; // Image relative offset of the handler map
int32_t dispIPtoStateMap; // Image relative offset of the IP to state map
uint32_t dispFrame; // displacement of address of function frame wrt establisher frame, only used for catch funclets
};
```
Notice that:
1. The magic number has been removed, emitting 0x19930522 every time becomes a problem when a program has thousands of these entries.
2. EHFlags has been moved into the header while dispESTypeList has been phased out due to dropped support of dynamic exception specifications in C++17. The compiler will default to the older \_\_CxxFrameHandler3 if dynamic exception specifications are used.
3. The lengths of the other tables are no longer stored in “Function Info 4”. This allows COMDAT folding to fold more of the pointed-to tables even if the “Function Info 4” table itself cannot be folded.
4. (Not explicitly shown) The dispFrame and bbtFlags fields are now variable-length integers. The high-level representation leaves it as an uint32\_t for easy processing.
5. bbtFlags, dispUnwindMap, dispTryBlockMap, and dispFrame can be omitted depending on the fields set in the header.
Taking all this into account, the average size of the new “Function Info 4” structure is now 13 bytes (1 byte header + three 4 byte image relative offsets to other tables) which can scale down even further if some tables are not needed. The lengths of the tables were moved out, but these values are now compressed and 90% of them in Microsoft.UI.Xaml.dll were found to fit within a single byte. Putting that all together, this means the average size to represent the same functional data in the new handler is 16 bytes compared to the previous 40 bytes—quite a dramatic improvement!
For folding, let’s look at the number of unique tables and funclets with the old and new handler:
| | | | |
| --- | --- | --- | --- |
| EH Data | Count in \_\_CxxFrameHandler3 | Count in \_\_CxxFrameHandler4 | % Reduction |
| Pdata Entries | 12,322 | 9,855 | 20.0% |
| Function Infos | 6,386 | 2,747 | 57.0% |
| IP2State Map Entries | 6,363 | 2,148 | 66.2% |
| Unwind Map Entries | 1,487 | 1,464 | 1.5% |
| Catch Handler Maps | 2,603 | 601 | 76.9% |
| Try Maps | 2,598 | 648 | 75.1% |
| Dtor Funclets | 2,301 | 1,527 | 33.6% |
| Catch Funclets | 2,603 | 84 | ***96.8%*** |
| Total | **36,663** | **19,074** | **48.0%** |
The number of unique EH data entries drops by **48%** from creating additional folding opportunities by removing RVAs and redesigning catch funclets. I specifically want to call out the number of catch funclets italicized in green: it drops from 2,603 down to only 84. This is a consequence of C++/WinRT translating HRESULTs to C++ exceptions which generates plenty of code-identical catch funclets that can now be folded. Certainly a drop of this magnitude is on the high-end of outcomes but nevertheless demonstrates the potential size savings folding can achieve when the data structures are designed with it in mind.
Performance
-----------
With the design introducing compression and modifying runtime execution there was a concern of exception handling performance being impacted. The impact, however, is a **positive** one: exception handling performance **improves** with \_\_CxxFrameHandler4 as opposed to \_\_CxxFrameHandler3. I tested throughput using a [benchmark](https://github.com/modi1123/CPP-EH-Throughput)[program](https://github.com/modi1123/CPP-EH-Throughput) that unwinds through 100 stack frames each with a try/catch and 3 automatic objects to destruct. This was run 50,000 times to profile execution time, leading to overall execution times of:
| | | |
| --- | --- | --- |
| | **\_\_CxxFrameHandler3** | **\_\_CxxFrameHandler4** |
| **Execution Time** | 4.84s | 4.25s |
Profiling showed decompression does introduce additional processing time but its cost is outweighed by fewer stores to thread-local storage in the new runtime design.
Future Plans
------------
As mentioned in the title, FH4 is currently only enabled for x64 binaries. However, the techniques described are extensible to ARM32/ARM64 and to a lesser extent x86. We’re currently looking for good examples (like Microsoft.UI.Xaml.dll) to motivate extending this technology to other platforms—if you think you have a good use case let us know!
The process of integrating the runtime changes for Store applications to support FH4 is in flight. Once that’s done, the new handler will be enabled by default so that everyone can get these binary size savings with no additional effort.
Closing Remarks
---------------
For anybody who thinks their x64 binaries could do with some trimming down: try out FH4 (via ‘/d2FH4’) today! We’re excited to see what savings this can provide now that this feature is out in the wild. Of course, if you encounter any issues please let us know in the comments below, by e-mail ([visualcpp@microsoft.com](mailto:visualcpp@microsoft.com)), or through [Developer Community](https://developercommunity.visualstudio.com/topics/C%2B%2B.html). You can also find us on Twitter ([@VisualC](https://twitter.com/visualc)).
Thanks to Kenny Kerr for directing us to Microsoft.UI.Xaml.dll, Ravi Pinjala for gathering the numbers on Office, and Robert Roessler for trialing this out on SQL. | https://habr.com/ru/post/442996/ | null | null | 2,543 | 54.93 |
Hi,
I tried to convert docx file to pdf using Aspose. Following is the code I used to conversion. I experienced text overlapping in pdf file. Is there any mistake I have done with the code or is this a bug.
This is the code I used for conversion
Code:
Document doc = new Document(docxPath);
string xmlFile = “e:\Document.ConvertToPdf Out.xml”;
doc.Save(xmlFile, SaveFormat.AsposePdf);
Aspose.Pdf.Pdf pdf = new Aspose.Pdf.Pdf();
pdf.BindXML(xmlFile, null);
pdf.IsImagesInXmlDeleteNeeded = true;
pdf.IsBookmarked = true;
pdf.Save(pdfFilePath);
I have attached resulted pdf file and used docx file with this. The titles have overlapped with title numbers.
Thanx
Hi,
Hello Sameera,
Thanks for considering Aspose.
I have tested the scenario with conventional/Legacy method and I am able to notice the same problem. For the sake of correction, please try using the Direct-to-PDF save method of Aspose.Words. As per my observation, the output with Direct-to-PDF save method is correct. For your reference, I have also attached the resultant PDF document. Please take a look.
For more information on Direct-to-PDF save method of Aspose.Words, please visit the following link. How-to: Convert a Document to PDF
In case it does not resolve your problem or you have any further query, please feel free to contact.
We apologize for your inconvenience.
Hi,
I used that method earlier for conversion. But I need to docx file table of content to be appeared as bookmarks of pdf file. Is that possible with that method? (I don’t know much about Aspose and all the methods I used are failed for my requirement). If it is possible please let me know.
Thnx for your reply
Thanx,
Sameera
Hi
<?xml:namespace prefix = o
Thank you for additional information. In this case you can use PdfOptions.HeadingsOutlineLevels property:
Hope this helps.
Best regards.
Hi,.
Thank you for your reply.
I will try and let you know does it worked for me.
thanx,
Sameera
Hi,
It worked for me for the table of contents.
But i have another requirement. when there is no specific table of contents page, I need the headings of docx file to be appeared as bookmarks on pdf. I created new thread with this problem. There are some attachments showing the problem faced by me.
If you can please give me a way to overcome the problem.
Link to new thread :
Thanx,
Sameera
Hi
<?xml:namespace prefix = o
Thanks for your request. I just answered your question here:
Best regards. | https://forum.aspose.com/t/text-overlap-in-pdf/71876 | CC-MAIN-2021-10 | refinedweb | 424 | 70.19 |
This notebook maps instances of the linear-quadratic-Gaussian permanent income model with $\beta R = 1$ into a linear state space system, applies two different approaches to solving the model and compares outcomes from those two approaches. After confirming that answers produced by the two methods agree, it applies the quantecon LinearStateSpace class to illustrate various features of the model.
Besides being a workhorse model for analyzing consumption data, the model is good for illustrating the concepts of
* stationarity * ergodicity * ensemble moments and cross section observations * cointegration * linear-quadratic dynamic programming problems
Background readings on the linear-quadratic-Gaussian permanent income model are Robert Hall's 1978 JPE paper ``Stochastic Implications of the Life Cycle-Permanent Income Hypothesis: Theory and Evidence'' and chapter 2 of Recursive Macroeconomic Theory
Let's get started
import quantecon as qe import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt %matplotlib inline np.set_printoptions(suppress=True, precision=4)
We study a version of the linear-quadratic-Gaussian model described in section 2.12 of chapter 2 of Ljungqvist and Sargent's Recursive Macroeconomic Theory
We solve the model in two ways:
as an LQ dynamic programming problem, and
as a system of expectational difference equations with boundary conditions that advise us to solve stable roots backwards and unstable roots forwards (see appendix A of chapter 2 of Ljungqvist and Sargent).
We confirm numerically that these two methods give rise to approximately the same solution. The adverb approximately is appropriate because we use a technical trick to map the problem into a well behaved LQ dynamic programming problem.
The LQ permanent income model is an example of a ``savings problem.'' A consumer has preferences over consumption streams that are ordered by the utility functional$$ E_0 \sum_{t=0}^\infty \beta^t u(c_t), \quad, \quad(2) $$
where $y_t$ is an exogenous stationary endowment process, $R$ is a constant gross risk-free interest rate, $b_t$ is one-period risk-free debt maturing at $t$, and $b_0$ is a given initial condition. We shall assume that $R^{-1} = \beta$. Equation (2) is linear. We use another set of linear equations to model the endowment process. In particular, we assume that the endowment process has the state-space representation$$ \eqalign{ z_{t+1} & = A_{22} z_t + C_2 w_{t+1} \cr y_t & = U_y z_t \cr} \quad (3) $$
where $w_{t+1}$ is an i.i. \quad (4) $$
This condition suffices to rule out Ponzi schemes. (We impose this condition to rule out a borrow-more-and-more plan that would allow the household to enjoy bliss consumption forever.)
The state vector confronting the household at $t$ is $$ x_t = \left[\matrix{z_t \cr b_t\cr}\right]',$$ where $b_t$ is its one-period debt falling due at the beginning of period $t$ and $z_t$ contains all variables useful for forecasting its future endowment.
We shall solve the problem two ways.
First, as a linear-quadratic control dynamic programming problem that we can solve using the LQ class.
Second, as a set of expectational difference equations that we can solve with homemade programs.
We can map the problem into a linear-quadratic dynamic programming problem, also known as an optimal linear regulator problem.
The stochastic discounted linear optimal regulator problem is to choose a decision rule for $u_t$ to maximize$$ - E_0\sum_{t=0}^\infty \beta^t \{x'_t Rx_t+u'_tQu_t\},\quad 0<\beta<1,$$
subject to $x_0$ given, and the law of motion$$x_{t+1} = A x_t+ Bu_t+ C w_{t+1},\qquad t\geq 0, $$
where $w_{t+1}$ is an $(n\times 1)$ vector of random variables that is independently and identically distributed according to the normal distribution with mean vector zero and covariance matrix $Ew_t w'_t= I .$
The value function for this problem is $v(x)= - x'Px-d,$ where $P$ is the unique positive semidefinite solution of the discounted algebraic matrix Riccati equation corresponding to the limit of iterations on matrix Riccati difference equation$$P_{j+1} =R+\beta A'P_j A-\beta^2 A'P_jB(Q+\beta B'P_jB)^{-1} B'P_jA.$$
from $P_0=0$. The optimal policy is $u_t=-Fx_t$, where $F=\beta (Q+\beta B'PB)^{-1} B'PA$. The scalar $d$ is given by $ d=\beta(1-\beta)^{-1} {\rm trace} ( P C C') . $
Under an optimal decision rule $F$, the state vector $x_t$ evolves according to$$ x_{t+1} = (A-BF) x_t + C w_{t+1} $$$$ \left[\matrix{z_{t+1} \cr b_{t+1} \cr}\right] = \left[\matrix{ A_{22} & 0 \cr R(U_\gamma - U_y) & R } \right]\left[\matrix{z_{t} \cr b_{t} \cr}\right] + \left[\matrix{0 \cr R}\right] (c_t - \gamma) + \left[\matrix{ C_t \cr 0 } \right] w_{t+1} $$
or$$ x_{t+1} = A x_t + B u_t + C w_{t+1} $$
We form the quadratic form $x_t' \bar R x_t + u_t'Q u_t $ with $Q =1$ and $\bar R$ a $ 4 \times 4$ matrix with all elements zero except for a very small entry $\alpha >0$ in the $(4,4)$ position. (We put the $\bar \cdot$ over the $R$ to avoid ``recycling'' the $R$ notation!)
We begin by creating an instance of the state-space system (2) that governs the income $\{y_t\}$ process. We assume it is a second order univariate autoregressive process: $$ y_{t+1} = \alpha + \rho_1 y_t + \rho_2 y_{t-1} + \sigma w_{t+1} $$
# Possible parameters # alpha, beta, rho1, rho2, sigma params = [[10.0, 0.95, 1.2, -0.3, 1.0], [10.0, 0.95, 0.9, 0.0, 1.0], [10.0, 0.95, 0.0, -0.0, 10.0]] # Set parameters alpha, beta, rho1, rho2, sigma = params[1] # Note: LinearStateSpace object runs into iteration limit in computing stationary variance when we set # sigma = .5 -- replace with doublej2 to fix this. Do some more testing R = 1/beta A = np.array([[1., 0., 0.], [alpha, rho1, rho2], [0., 1., 0.]]) C = np.array([[0.], [sigma], [0.]]) G = np.array([[0., 1., 0.]]) # for later use, form LinearStateSpace system and pull off steady state moments mu_z0 = np.array([[1.0], [0.0], [0.0]]) sig_z0 = np.zeros((3, 3)) Lz = qe.LinearStateSpace(A, C, G, mu_0=mu_z0, Sigma_0=sig_z0) muz, muy, Sigz, Sigy = Lz.stationary_distributions() # mean vector of state for the savings problem mxo = np.vstack([muz, 0.0]) # create stationary covariance matrix of x -- start everyone off at b=0 a1 = np.zeros((3, 1)) aa = np.hstack([Sigz, a1]) bb = np.zeros((1, 4)) sxo = np.vstack([aa, bb]) # These choices will initialize the state vector of an individual at zero debt # and the ergodic distribution of the endowment process. Use these to create # the Bewley economy. mxbewley = mxo sxbewley = sxo
It turns out that the bliss level of consumption $\gamma$ in the utility function $-.5 (c_t -\gamma)^2$ has no effect on the optimal decision rule. (We shall see why below when we inspect the Euler equation for consumption.)
Now create the objects for the optimal linear regulator.
Here we will use a trick to induce the Bellman equation to respect restriction (4) on the debt sequence $\{b_t\}$. To accomplish that, we'll put a very small penalty on $b_t^2$ in the criterion function.
That will induce a (hopefully) small approximation error in the decision rule. We'll check whether it really is small numerically soon.
# # Here we create the matrices for our system # A12 = np.zeros((3,1)) ALQ_l = np.hstack([A, A12]) ALQ_r = np.array([[0, -R, 0, R]]) ALQ = np.vstack([ALQ_l, ALQ_r]) RLQ = np.array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1e-9]]) QLQ = np.array([1.0]) BLQ = np.array([0., 0., 0., R]).reshape(4,1) CLQ = np.array([0., sigma, 0., 0.]).reshape(4,1) betaLQ = beta
print("We can inspect the matrices that describe our system below") print("A = \n", ALQ) print("B = \n", BLQ) print("R = \n", RLQ) print("Q = \n", QLQ)
We can inspect the matrices that describe our system below A = [[ 1. 0. 0. 0. ] [ 10. 0.9 0. 0. ] [ 0. 1. 0. 0. ] [ 0. -1.0526 0. 1.0526]] B = [[ 0. ] [ 0. ] [ 0. ] [ 1.0526]] R = [[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]] Q = [ 1.]
Now create the appropriate instance of an LQ model
LQPI = qe.LQ(QLQ, RLQ, ALQ, BLQ, C=CLQ, beta=betaLQ)
Now create the optimal policies using the analytic formulas.
We'll save the answers and will compare them with answers we get by employing an alternative solution method.
P, F, d = LQPI.stationary_values() # Compute optimal value function and decision rule ABF = ALQ - np.dot(BLQ,F) # Form closed loop system
Now we will solve the household's optimum problem by first deducing the Euler equations that are the first-order conditions with respect to consumption and savings, then using the budget constraints and the boundary condition (4) to complete a system of expectational linear difference equations that we'll solve for the optimal consumption, debt plan.
First-order conditions for the problem are$$ E_t u'(c_{t+1}) = u'(c_t) , \ \ \forall t \geq 0. \quad (5) $$
In our linear-quadratic model, we assume the quadratic utility function $u(c_t) = -.5 (c_t - \gamma)^2$, where $\gamma$ is a bliss level of consumption. Then the consumption Euler equation becomes $$ E_t c_{t+1} = c_t . \quad (6) $$ Along with the quadratic utility specification, we allow consumption $c_t$ to be negative.
To deduce the optimal decision rule, we want to solve the system of difference equations formed by (2) and (6) subject to the boundary condition (4). To accomplish this, solve (2) forward and impose $\lim_{T\rightarrow +\infty} \beta^T b_{T+1} =0$ to get $$ b_t = \sum_{j=0}^\infty \beta^j (y_{t+j} - c_{t+j}) . \quad (7) $$ Imposing $\lim_{T\rightarrow +\infty} \beta^T b_{T+1} =0$ suffices to impose (4) on the debt path. Take conditional expectations on both sides of (7) and use (6) and the law of iterated expectations to deduce $$ b_t = \sum_{j=0}^\infty \beta^j E_t y_{t+j} - {1 \over 1-\beta} c_t \quad (8) $$ or $$ c_t = (1-\beta) \left[ \sum_{j=0}^\infty \beta^j E_t y_{t+j} - b_t\right]. \quad (9) $$ If we define the net rate of interest $r$ by $\beta ={1 \over 1+r}$, we can also express this equation as $$ c_t = {r \over 1+r} \left[ \sum_{j=0}^\infty \beta^j E_t y_{t+j} - b_t\right]. \quad (10) $$ Equation (9) or (10) asserts that consumption equals what Irving Fisher defined as economic income, namely, a constant marginal propensity to consume or interest factor ${r \over 1+r}$ times the sum of nonfinancial wealth $ \sum_{j=0}^\infty \beta^j E_t y_{t+j}$ and financial wealth $-b_t$. Notice that (9) or (10) represents $c_t$ as a function of the state $[b_t, z_t]$ confronting the household, where from $z_t$ contains all information useful for forecasting the endowment process.
Pulling together our preceding results, we can regard $z_t, b_t$ as the time $t$ state, where $z_t$ is an exogenous component of the state and $b_t$ is an endogenous component of the state vector. The system can be represented as$$ \eqalign{ z_{t+1} & = A_{22} z_t + C_2 w_{t+1} \cr b_{t+1} & = b_t + U_y [ (I -\beta A_{22})^{-1} (A_{22} - I) ] z_t \cr y_t & = U_y z_t \cr c_t & = (1-\beta) [ U_y(I-\beta A_{22})^{-1} z_t - b_t ]. \cr } \quad (11) $$
Now we'll apply the formulas in equation system (11).
Later we shall use them to get objects needed to form the system (11) as an instance of a LinearStateSpace class that we'll use to exhibit features of the LQ permanent income model.
# Use the above formulas to create the optimal policies for $b_{t+1}$ and $c_t$ b_pol = np.dot(G, la.inv(np.eye(3, 3) - beta*A)).dot(A - np.eye(3, 3)) c_pol = (1 - beta)*np.dot(G, la.inv(np.eye(3, 3) - beta*A)) #Create the A matrix for a LinearStateSpace instance A_LSS1 = np.vstack([A, b_pol]) A_LSS2 = np.eye(4, 1, -3) A_LSS = np.hstack([A_LSS1, A_LSS2]) # Create the C matrix for LSS methods C_LSS = np.vstack([C, np.zeros(1)]) # Create the G matrix for LSS methods G_LSS1 = np.vstack([G, c_pol]) G_LSS2 = np.vstack([np.zeros(1), -(1 - beta)]) G_LSS = np.hstack([G_LSS1, G_LSS2]) # use the following values to start everyone off at b=0, initial incomes zero # Initial Conditions mu_0 = np.array([1., 0., 0., 0.]) sigma_0 = np.zeros((4, 4))
A_LSS calculated as we have here should equal ABF calculated above using the LQ model.
Here comes the check. The difference between ABF and A_LSS should be zero
ABF - A_LSS
array([[ 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. ], [-0.0001, -0. , 0. , 0. ]])
Now compare pertinent elements of c_pol and -F
print(c_pol, "\n", -F)
[[ 65.5172 0.3448 0. ]] [[ 65.5172 0.3448 -0. -0.05 ]]
We have verified that the two methods give the same solution.
Now let's create an instance of a LinearStateSpace model.
To do this, we'll use the outcomes from out second method.
Now we'll generate panels of consumers. We'll study two examples that are differentiated only by the initial states with which we endow consumers. All other parameter values are kept the same in the two examples.
In the first example, consumers' nonfinancial income paths will display prounounced transients early in the sample that will affect outcomes in striking ways. Those transient effects will not be present in the second example.
Now we'll use methods that the LinearStateSpace class contains to simulate the model with our first set of intitial conditions.
25 paths of the exogenous non-financial income process and the associated consumption and debt paths. In the first set of graphs, the darker lines depict one particular sample path, while the lighter lines indicate the other 24 paths.
A second graph that plots a collection of simulations against the population distribution that we extract from the LinearStateSpace instance LSS
LSS = qe.LinearStateSpace(A_LSS, C_LSS, G_LSS, mu_0=mu_0, Sigma_0=sigma_0)
In the code below, we use the LinearStateSpace class to
compute and plot population quantiles of the distributions of consumption and debt for a population of consumers
simulate a group of 25 consumers and plot sample paths on the same graph as the population distribution
def income_consumption_debt_series(A, C, G, m0, s0, T=150, npaths=25): """ This function takes initial conditions (m0, s0) and uses the Linear State Space class from QuantEcon to simulate an economy `npaths` times for `T` periods. It then uses that information to generate some graphs related to the discussion below. """ LSS = qe.LinearStateSpace(A, C, G, mu_0=m0, Sigma_0=s0) # Simulation/Moment Parameters moment_generator = LSS.moment_sequence() # Simulate various paths bsim = np.empty((npaths, T)) csim = np.empty((npaths, T)) ysim = np.empty((npaths, T)) for i in range(npaths): sims = LSS.simulate(T) bsim[i, :] = sims[0][-1, :] csim[i, :] = sims[1][1, :] ysim[i, :] = sims[1][0, :] # Get the moments cons_mean = np.empty(T) cons_var = np.empty(T) debt_mean = np.empty(T) debt_var = np.empty(T) for t in range(T): mu_x, mu_y, sig_x, sig_y = next(moment_generator) cons_mean[t], cons_var[t] = mu_y[1], sig_y[1, 1] debt_mean[t], debt_var[t] = mu_x[3], sig_x[3, 3] return bsim, csim, ysim, cons_mean, cons_var, debt_mean, debt_var def consumption_income_debt_figure(bsim, csim, ysim): # Get T T = bsim.shape[1] # Create first figure fig, ax = plt.subplots(2, 1, figsize=(10, 8)) xvals = np.arange(T) # Plot consumption and income ax[0].plot(csim[0, :], label="c", color="b") ax[0].plot(ysim[0, :], label="y", color="g") ax[0].plot(csim.T, alpha=.1, color="b") ax[0].plot(ysim.T, alpha=.1, color="g") ax[0].legend(loc=4) ax[0].set_xlabel("t") ax[0].set_ylabel("y and c") # Plot debt ax[1].plot(bsim[0, :], label="b", color="r") ax[1].plot(bsim.T, alpha=.1, color="r") ax[1].legend(loc=4) ax[1].set_xlabel("t") ax[1].set_ylabel("debt") fig.suptitle("Nonfinancial Income, Consumption, and Debt") return fig def consumption_debt_fanchart(csim, cons_mean, cons_var, bsim, debt_mean, debt_var): # Get T T = bsim.shape[1] # Create Percentiles of cross-section distributions cmean = np.mean(cons_mean) c90 = 1.65*np.sqrt(cons_var) c95 = 1.96*np.sqrt(cons_var) c_perc_95p, c_perc_95m = cons_mean + c95, cons_mean - c95 c_perc_90p, c_perc_90m = cons_mean + c90, cons_mean - c90 # Create Percentiles of cross-section distributions dmean = np.mean(debt_mean) d90 = 1.65*np.sqrt(debt_var) d95 = 1.96*np.sqrt(debt_var) d_perc_95p, d_perc_95m = debt_mean + d95, debt_mean - d95 d_perc_90p, d_perc_90m = debt_mean + d90, debt_mean - d90 # Create second figure fig2, ax2 = plt.subplots(2, 1, figsize=(10, 8)) xvals = np.arange(T) # Consumption fan ax2[0].plot(xvals, cons_mean, color="k") ax2[0].plot(csim.T, color="k", alpha=.25) ax2[0].fill_between(xvals, c_perc_95m, c_perc_95p, alpha=.25, color="b") ax2[0].fill_between(xvals, c_perc_90m, c_perc_90p, alpha=.25, color="r") ax2[0].set_ylim((cmean-15, cmean+15)) ax2[0].set_ylabel("consumption") # Debt fan ax2[1].plot(xvals, debt_mean, color="k") ax2[1].plot(bsim.T, color="k", alpha=.25) ax2[1].fill_between(xvals, d_perc_95m, d_perc_95p, alpha=.25, color="b") ax2[1].fill_between(xvals, d_perc_90m, d_perc_90p, alpha=.25, color="r") # ax2[1].set_ylim() ax2[1].set_ylabel("debt") fig2.suptitle("Consumption/Debt over time") ax2[1].set_xlabel("t") return fig2
# Creates pictures with initial conditions of 0.0 for y and b out = income_consumption_debt_series(A_LSS, C_LSS, G_LSS, mu_0, sigma_0) bsim0, csim0, ysim0 = out[:3] cons_mean0, cons_var0, debt_mean0, debt_var0 = out[3:] fig_0 = consumption_income_debt_figure(bsim0, csim0, ysim0) fig_02 = consumption_debt_fanchart(csim0, cons_mean0, cons_var0, bsim0, debt_mean0, debt_var0) fig_0.show() fig_02.show()
Here is what is going on in the above graphs.
Because we have set $y_{-1} = y_{-2} = 0$, nonfinancial income $y_t$ starts far below its stationary mean $\mu_{y, \infty}$ and rises early in each simulation.
To help interpret the behavior above graph, recall that we can represent the optimal decision rule for consumption in terms of the co-integrating relationship $$ (1-\beta) b_t + c_t = (1-\beta) E_t \sum_{j=0}^\infty \beta^j y_{t+j}, $$ For our simulation, we have set initial conditions $b_0 = y_{-1} = y_{-2} = 0$ (please see the code above). So at time $0$ we have $$ c_0 = (1-\beta) E_0 \sum_{t=0}^\infty \beta^j y_{t} . $$ This tells us that consumption starts at the value of an annuity from the expected discounted value of nonfinancial income. To support that level of consumption, the consumer borrows a lot early on, building up substantial debt. In fact, he or she incurs so much debt that eventually, in the stochastic steady state, he consumes less each period than his income. He uses the gap between consumption and income mostly to service the interest payments due on his debt.
Thus, when we look at the panel of debt in the accompanying graph, we see that this is a group of ex ante indentical people each of whom starts with zero debt. All of them accumulate debt in anticipation of rising nonfinancial income. The expect their nonfinancial income to rise toward the invariant distribution of income, a consequence of our having started them at $y_{-1} = y_{-2} = 0$.
The LQ permanent income model is a good one for illustrating the concept of cointegration.
The following figure plots realizations of the left side of $$ (1-\beta) b_t + c_t = (1-\beta) E_t \sum_{j=0}^\infty \beta^j y_{t+j}, \quad (12) $$ which is called the cointegrating residual.
Notice that it equals the right side, namely, $(1-\beta) E_t \sum_{j=0}^\infty \beta^j y_{t+j}$, which equals an annuity payment on the expected present value of future income $E_t \sum_{j=0}^\infty \beta^j y_{t+j}$.
Early along a realization, $c_t$ is approximately constant while $(1-\beta) b_t$ and $(1-\beta) E_t \sum_{j=0}^\infty \beta^j y_{t+j}$ both rise markedly as the household's present value of income and borrowing rise pretty much together.
Note: This example illustrates the following point: the definition of cointegration implies that the cointegrating residual is asymptotically covariance stationary, not covariance stationary. The cointegrating residual for the specification with zero income and zero debt initially has a notable transient component that dominates its behavior early in the sample. By specifying different initial conditions, we shall remove this transient in our second example to be presented below.
def cointegration_figure(bsim, csim): """ Plots the cointegration """ # Create figure fig, ax = plt.subplots(figsize=(10, 8)) ax.plot((1-beta)*bsim[0, :] + csim[0, :], color="k") ax.plot((1-beta)*bsim.T + csim.T, color="k", alpha=.1) fig.suptitle("Cointegration of Assets and Consumption") ax.set_xlabel("t") ax.set_ylabel("") return fig
fig = cointegration_figure(bsim0, csim0) fig.show()
When we set $y_{-1} = y_{-2} = 0$ and $b_0 =0$ in the preceding exercise, we make debt "head north" early in the sample. Average debt rises and approaches asymptote.
We can regard these as outcomes of a ``small open economy'' that borrows from abroad at the fixed gross interest rate $R$ in anticipation of rising incomes.
So with the economic primitives set as above, the economy converges to a steady state in which there is an excess aggregate supply of risk-free loans at a gross interest rate of $R$. This excess supply is filled by ``foreigner lenders'' willing to make those loans.
We can use virtually the same code to rig a "poor man's Bewley model" in the following way.
as before, we start everyone at $b_0 = 0$.
But instead of starting everyone at $y_{-1} = y_{-2} = 0$, we draw $\begin{bmatrix} y_{-1} \cr y_{-2} \end{bmatrix}$ from the invariant distribution of the $\{y_t\}$ process.
This rigs a closed economy in which people are borrowing and lending with each other at a gross risk-free interest rate of $R = \beta^{-1}$. Here within the group of people being analyzed, risk-free loans are in zero excess supply. We have arranged primitives so that $R = \beta^{-1}$ clears the market for risk-free loans at zero aggregate excess supply. There is no need for foreigners to lend to our group.
The following graphs confirm the following outcomes:
as before, the consumption distribution spreads out over time. But now there is some initial dispersion because there is ex ante heterogeneity in the initial draws of $\begin{bmatrix} y_{-1} \cr y_{-2} \end{bmatrix}$.
as before, the cross-section distribution of debt spreads out over time.
Unlike before, the average level of debt stays at zero, reflecting that this is a closed borrower-and-lender economy.
Now the cointegrating residual seems stationary, and not just asymptotically stationary.
# Creates pictures with initial conditions of 0.0 for b and y from invariant distribution out = income_consumption_debt_series(A_LSS, C_LSS, G_LSS, mxbewley, sxbewley) bsimb, csimb, ysimb = out[:3] cons_meanb, cons_varb, debt_meanb, debt_varb = out[3:] fig_0 = consumption_income_debt_figure(bsimb, csimb, ysimb) fig_02 = consumption_debt_fanchart(csimb, cons_meanb, cons_varb, bsimb, debt_meanb, debt_varb)
fig = cointegration_figure(bsimb, csimb) fig.show() | http://nbviewer.jupyter.org/github/QuantEcon/QuantEcon.notebooks/blob/master/permanent_income.ipynb | CC-MAIN-2017-04 | refinedweb | 3,852 | 55.84 |
Computer Systems Org I - Prof. Grishman
Lecture 15 - Oct. 25, 2005
IO with putchar and getchar
The C functions getchar and putchar read one character from standard input and write one character to standard output. So, for example, to copy from input to output until you find a 'q',
#include <stdio.h>
main() {
char c;
/* copy input characters to output until we find a 'q' */
while ((c = getchar()) != 'q') putchar(c);
}
Redirection
getchar
reads a character from standard input;
putchar
writes a character to standard output.
In Unix (and systems using similar shells, like Linux and Cygwin) standard input can be redirected to read from a file
./a <sometext
reads from file 'sometext' instead of standard input;
./a <sometext >moretext
reads from file 'sometext' and writes to file 'moretext'. This allows a program to be tested first interactively and then -- without changing the program, to use a data file as input.
EOF
If getchar is reading from a file and encounters an end-of-file, it returns the value
EOF
, which is defined as part of stdio.h. So a program to copy a complete file from input to output would be
#include <stdio.h>
main() {
char c;
/* copy input characters to output until end of file */
while ((c = getchar()) != EOF) putchar(c);
}
Note: because EOF is an integer but not a character, it would be better to declare c an int in this program; however, a char declaration will work on most machines. | http://cs.nyu.edu/courses/fall05/V22.0201-002/lecture15.html | CC-MAIN-2014-10 | refinedweb | 244 | 71.24 |
Now that you've seen the details of class inheritance in the previous chapter, it is a good time to take a step back and look at Scala's class hierarchy as a whole. In Scala, every class inherits from a common superclass named Any. Because every class is a subclass of Any, the methods defined in Any are "universal" methods: they may be invoked on any object. Scala also defines some interesting classes at the bottom of the hierarchy, Null and Nothing, which essentially act as common subclasses. For example, just as Any is a superclass of every other class, Nothing is a subclass of every other class. In this chapter, we'll give you a tour of Scala's class hierarchy.
Figure 11.1 shows an outline of Scala's class hierarchy. At the top of the hierarchy is class Any, which defines methods that include the following:
final def ==(that: Any): Boolean final def !=(that: Any): Boolean def equals(that: Any): Boolean def hashCode: Int def toString: StringBecause every class inherits from Any, every object in a Scala program can be compared using ==, !=, or equals; hashed using hashCode; and formatted using toString. The equality and inequality methods, == and !=, are declared final in class Any, so they cannot be overridden in subclasses. In fact, == is always the same as equals and != is always the negation of equals. So individual classes can tailor what == or != means by overriding the equals method. We'll show an example later in this chapter.
The root class Any has two subclasses: AnyVal and AnyRef. AnyVal is the parent class of every built-in value class in Scala. There are nine such value classes: Byte, Short, Char, Int, Long, Float, Double, Boolean, and Unit. The first eight of these correspond to Java's primitive types, and their values are represented at run time as Java's primitive values. The instances of these classes are all written as literals in Scala. For example, 42 is an instance of Int, 'x' is an instance of Char, and false an instance of Boolean. You cannot create instances of these classes using new. This is enforced by the "trick" that value classes are all defined to be both abstract and final. So if you were to write:
scala> new Intyou would get:
<console>:5: error: class Int is abstract; cannot be instantiated new Int ^
The other value class, Unit, corresponds roughly to Java's void type; it is used as the result type of a method that does not otherwise return an interesting result. Unit has a single instance value, which is written (), as discussed in Section 7.2.
As explained in Chapter 5, the value classes support the usual arithmetic and boolean operators as methods. For instance, Int has methods named + and *, and Boolean has methods named || and &&. Value classes also inherit all methods from class Any. You can test this in the interpreter:
scala> 42.toString res1: java.lang.String = 42Note that the value class space is flat; all value classes are subtypes of scala.AnyVal, but they do not subclass each other. Instead there are implicit conversions between different value class types. For example, an instance of class scala.Int is automatically widened (by an implicit conversion) to an instance of class scala.Long when required.
scala> 42.hashCode res2: Int = 42
scala> 42 equals 42 res3: Boolean = true
As mentioned in Section 5.9, implicit conversions are also used to add more functionality to value types. For instance, the type Int supports all of the operations below:
scala> 42 max 43 res4: Int = 43Here's how this works: The methods min, max, until, to, and abs are all defined in a class scala.runtime.RichInt, and there is an implicit conversion from class Int to RichInt. The conversion is applied whenever a method is invoked on an Int that is undefined in Int but defined in RichInt. Similar "booster classes" and implicit conversions exist for the other value classes. Implicit conversions will be discussed in detail in Chapter 21.
scala> 42 min 43 res5: Int = 42
scala> 1 until 5 res6: Range = Range(1, 2, 3, 4)
scala> 1 to 5 res7: Range.Inclusive = Range(1, 2, 3, 4, 5)
scala> 3.abs res8: Int = 3
scala> (-3).abs res9: Int = 3
The other subclass of the root class Any is class AnyRef. This is the base class of all reference classes in Scala. As mentioned previously, on the Java platform AnyRef is in fact just an alias for class java.lang.Object. So classes written in Java as well as classes written in Scala all inherit from AnyRef.. The idea is that the ScalaObject contains methods that the Scala compiler defines and implements in order to make execution of Scala programs more efficient. Right now, Scala object contains a single method, named $tag, which is used internally to speed up pattern matching.):
// This is Java boolean isEqual(Integer x, Integer y) { return x == y; } System.out.println(isEqual(421, 421));You will find that you get false! What happens is that the number 421 gets boxed twice, so that the arguments for x and y are two different objects. Because == means reference equality on reference types, and Integer is a reference type, the result is false. This is one aspect where it shows that Java is not a pure object-oriented language. There is a difference between primitive types and reference types that can be clearly observed.
Now try the same experiment in Scala:
scala> def isEqual(x: Int, y: Int) = x == y isEqual: (Int,Int)BooleanIn fact, the equality operation == in Scala is designed to be transparent with respect to the type's representation. For value types, it is the natural (numeric or boolean) equality. For reference types, == is treated as an alias of the equals method inherited from Object. That method is originally defined as reference equality, but is overridden by many subclasses to implement their natural notion of equality. This also means that in Scala you never fall into Java's well-known trap concerning string comparisons. In Scala, string comparison works as it should:
scala> isEqual(421, 421) res10: Boolean = true
scala> def isEqual(x: Any, y: Any) = x == y isEqual: (Any,Any)Boolean
scala> isEqual(421, 421) res11: Boolean = true
scala> val x = "abcd".substring(2) x: java.lang.String = cdIn Java, the result of comparing x with y would be false. The programmer should have used equals in this case, but it is easy to forget.
scala> val y = "abcd".substring(2) y: java.lang.String = cd
scala> x == y res12: Boolean = true
However, there are situations where you need reference equality instead of user-defined equality. For example, in some situations where efficiency is paramount, you would like to hash cons with some classes and compare their instances with reference equality.[2] For these cases, class AnyRef defines an additional eq method, which cannot be overridden and is implemented as reference equality (i.e., it behaves like == in Java for reference types). There's also the negation of eq, which is called ne. For example:
scala> val x = new String("abc") x: java.lang.String = abcEquality in Scala is discussed further in Chapter 28.
scala> val y = new String("abc") y: java.lang.String = abc
scala> x == y res13: Boolean = true
scala> x eq y res14: Boolean = false
scala> x ne y res15: Boolean = true
At the bottom of the type hierarchy in Figure 11.1 you see the two classes scala.Null and scala.Nothing. These are special types that handle some "corner cases" of Scala's object-oriented type system in a uniform way.
Class Null is the type of the null reference; it is a subclass of every reference class (i.e., every class that itself inherits from AnyRef). Null is not compatible with value types. You cannot, for example, assign a null value to an integer variable:
scala> val i: Int = null <console>:4: error: type mismatch; found : Null(null) required: Int
Type Nothing is at the very bottom of Scala's class hierarchy; it is a subtype of every other type. However, there exist no values of this type whatsoever. Why does it make sense to have a type without values? As discussed in Section 7.4, one use of Nothing is that it signals abnormal termination. For instance there's the error method in the Predef object of Scala's standard library, which is defined like this:
def error(message: String): Nothing = throw new RuntimeException(message)The return type of error is Nothing, which tells users that the method will not return normally (it throws an exception instead). Because Nothing is a subtype of every other type, you can use methods like error in very flexible ways. For instance:
def divide(x: Int, y: Int): Int = if (y != 0) x / y else error("can't divide by zero")
The "then" branch of the conditional, x / y, has type Int, whereas the else branch, the call to error, has type Nothing. Because Nothing is a subtype of Int, the type of the whole conditional is Int, as required.
In this chapter we showed you the classes at the top and bottom of Scala's class hierarchy. Now that you've gotten a good foundation on class inheritance in Scala, you're ready to understand mixin composition. In the next chapter, you'll learn about traits.
[1] The reason the AnyRef alias exists, instead of just using the name java.lang.Object, is because Scala was designed to work on both the Java and .NET platforms. On .NET, AnyRef is an alias for System.Object.
[2] You hash cons instances of a class by caching all instances you have created in a weak collection. Then, any time you want a new instance of the class, you first check the cache. If the cache already has an element equal to the one you are about to create, you can reuse the existing instance. As a result of this arrangement, any two instances that are equal with equals() are also equal with reference equality. | http://www.artima.com/pins1ed/scalas-hierarchyP.html | CC-MAIN-2015-11 | refinedweb | 1,690 | 64.61 |
** Also: I assume you've already covered the basics of Java programming and object-oriented design concepts (to some degree, at least). If you need to, I reccommend Jhin's Hello World tutorial, it's really quite good.
Now that that's over, let's get started with some vocab.:
The Frame
The frame is the border of the window that will "hold" all your components - your text fields, labels, radio buttons, etc.. Every window must have a frame to place components, just as every book must have a cover to hold pages.
Content Pane (or just pane)
The content pane is where all components will be placed. You could think of it as the background. Every GUI must have a content pane, just as books must have pages.
Layout Manager
The layout manager places the components in the pane in a certain configuration, depending on which layout manager you specify. If you set it to "null" as I often do, you must specify the exact coordinates (in pixels) for each component. Layout managers can be nice, but they can also cause lots of headaches.
Coordinates
Coordinates are specified rather intuitively in Java. If you remember your high school algebra - or at least how to plot points on an x-y graph - you'll be fine. Java's coordinate system uses standard (x, y) coordinates, but they're plotted like this: A point (x, y) is located x pixels to the right and y pixels down from the top-left corner of the pane.
Here's a couple of pictures for you visual types:
How it Works
Here's basically what we're going to do:
- Make a frame
- Get a hold of the content panel
- Make our components
- Add our components to the GUI
- Set up event handlers
Now for the fun part: the code.
Ok, we'll need to import these: javax.swing.JFrame;, java.awt.event.*; and java.awt.*; - they'll come in handy.
*Almost all of the code for this project will be put in the class' constructor. Very little code will actually go into the main method.
To make a frame, our class has to extend JFrame, which also allows us to manipulate the frame. When we create a frame, we have to specify a few things: dimensions, title, default close operation, and visibility.
Yup. If a window is set as visible, the user can see it on his screen. As straight-forward as it sounds, this is one of the most commonly forgotten frame attributes and makes for a very frustrated prorgammer. Default close operation is a bit outside the scope of this tutorial, so we'll just keep it simple and leave it set to EXIT_ON_CLOSE. Basically, it just defines how the window reacts when the user presses the big 'x'.
What does all this look like? Here are those methods in action:
import javax.swing.JFrame; import java.awt.*; public class RectangleProgram extends JFrame { private static final int WIDTH = 400; private static final int HEIGHT = 300; public RectangleProgram() { setTitle("Sample Title: Area of a Rectangle"); setSize(WIDTH, HEIGHT); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } }
Now, we've got our frame. Next: content panel.
We use a Container object to manipulate the content pane (CP) along with a nifty statement: getContentPane(). The class Container only has two methods that we need to mess with: add and setLayout. Let's save add for later, but we'll set the layout (manager) to a simple grid layout with 4 rows and 2 columns.
Here's the code for what we just did:
Container pane = getContentPane(); pane.setLayout(new GridLayout (4, 2));
Components, Components, Components
In this tutorial you will be introduced to three components: JLabel, JTextField, JButton. (Betcha' can't figure out what they do.
We declare & instantiate them just like any other object. The JLabel constructor accepts two arguments: a string of text (the prompt) and an alignment constant. JTextField: and integer specifying the size of the field in characters. JButton: an String that will be the text on the button. One thing to note: we declare the components outside the class' constructor, but we instantiate them inside the constructor - like other instance variables.
Next, we have to add the components to the CP. To do that, just use pane.add(<Component>); - where Component refers to the reference variable for the component you want to add.
Here's the program now:
import java.awt.*; import javax.swing.*; public class RectangleProgram extends JFrame { private static final int WIDTH = 400; private static final int HEIGHT = 300; private JLabel lengthL, widthL, areaL, perimeterL; private JTextField lengthTF, widthTF, areaTF, perimeterTF; private JButton calculateB, exitB; public RectangleProgram() { //Instantiate the labels: lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT); widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT); areaL = new JLabel("Area: ", SwingConstants.RIGHT); perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT); //Text fields next: lengthTF = new JTextField(10); widthTF = new JTextField(10); areaTF = new JTextField(10); perimeterTF = new JTextField(10); //Buttons too: calculateB = new JButton("Calculate"); exitB = new JButton("Exit"); //Set the window's title. setTitle("Sample Title: Area of a Rectangle"); //Get the content pane (CP). Container pane = getContentPane(); //Set the layout. pane.setLayout(new GridLayout(5, 2)); //Other JFrame stuff. setSize(WIDTH, HEIGHT); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } }
Ok. All our components are ready; steps 3 & 4 are done. What's left? Well, right now those buttons won't do a thing - we haven't told them what to do when they're pressed.
When something happens in a GUI window, it's called an event. If we want to be able to react to events (like button clicks), we have to register an action listener that waits & listens for something to happen. When it "hears" something, it executes the code we put in the abstract method actionPerformed, which is where we'll be putting our area formula and output statements. For us, each button will have a different "handler" that handles each button's function using (implementing) the ActionListener. Notice that the handler we specified is the argument used when adding the ActionListener.
Also, notice the we use the getText and setText methods to manipulate the data entered into the text fields. Also, let's use the setEditable() statement on areaTF since it's solely an output field, and we don't want to confuse our user too much.
And so, here we are. Already, the final product is nearly ready. All we have to to is add a main method to start the ball rolling, and we're done. There is only one line in main: RectangleProgram rectObj = new RectangleProgram();
So, here it is:
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class RectangleProgram extends JFrame { private static final int WIDTH = 400; private static final int HEIGHT = 300; private JLabel lengthL, widthL, areaL; private JTextField lengthTF, widthTF, areaTF; private JButton calculateB, exitB; //Button handlers: private CalculateButtonHandler cbHandler; private ExitButtonHandler ebHandler; public RectangleProgram() { lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT); widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT); areaL = new JLabel("Area: ", SwingConstants.RIGHT); lengthTF = new JTextField(10); widthTF = new JTextField(10); areaTF = new JTextField(10); //SPecify handlers for each button and add (register) ActionListeners to each button. calculateB = new JButton("Calculate"); cbHandler = new CalculateButtonHandler(); calculateB.addActionListener(cbHandler); exitB = new JButton("Exit"); ebHandler = new ExitButtonHandler(); exitB.addActionListener(ebHandler); setTitle("Sample Title: Area of a Rectangle"); Container pane = getContentPane(); pane.setLayout(new GridLayout(4, 2)); //Add things to the pane in the order you want them to appear (left to right, top to bottom) pane.add(lengthL); pane.add(lengthTF); pane.add(widthL); pane.add(widthTF); pane.add(areaL); pane.add(areaTF); pane.add(calculateB); pane.add(exitB); setSize(WIDTH, HEIGHT); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } private class CalculateButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { double width, length, area; length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields. width = Double.parseDouble(widthTF.getText()); area = length * width; areaTF.setText("" + area); } } public class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } public static void main(String[] args) { RectangleProgram rectObj = new RectangleProgram(); } }
Admittedly, this isn't exactly the most exciting or flashy GUI you'll ever see. However, it accomplishes a task: to introduce broad concepts. Hopefully, from here, you will go on to expand your knowledge, building on the foundation we've established here. As far as resources go, there is no shortage of them - go look for some basic Java GUI books at the library, or free e-books online, and - as always - be sure to check </DIC> for other tutorials, code snippets, and more resources than you'll know what to do with.
Diagrams from Sun's Website
RectangleProgram adapted from Java Programming, From Programming Analysis To Design, Second Edition by DS Malik (a horrible book, by the way)
This post has been edited by SPlutard: 09 August 2006 - 03:14 PM | https://www.dreamincode.net/forums/topic/17705-basic-gui-concepts/ | CC-MAIN-2020-05 | refinedweb | 1,486 | 55.13 |
Destroy a synchronization object
#include <sys/neutrino.h> int SyncDestroy( sync_t* sync ); int SyncDestroy_r ( sync_t* sync );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The SyncDestroy() and SyncDestroy_r() kernel calls destroy a synchronization object previously allocated by a call to SyncTypeCreate(). You can destroy a locked mutex only if you're its owner. If the object is a condition variable with waiting threads, the call fails. Any attempt to use sync after it is destroyed fails.
These functions are identical except in the way they indicate errors. See the Returns section for details.
Blocking states
These calls don't block.
The only difference between these functions is the way they indicate errors: | http://www.qnx.com/developers/docs/6.6.0_anm11_wf10/com.qnx.doc.neutrino.lib_ref/topic/s/syncdestroy.html | CC-MAIN-2018-22 | refinedweb | 123 | 60.51 |
You could be wondering what is so special about React; What we will do is pick up from a previous post about React components and put to practice the theories we discussed following community best practices as always.
As the topic implies, we are going to be building a To-Do application with React. Do not expect any surprises such as managing state with a state management library like Flux or Redux. I promise it will strictly be React. Maybe in following articles we can employ something like Redux but we want to focus on React and make sure everybody is good with React itself.
Prerequisites
Table of Contents
You don't need much requirements to setup this project because we will make use of CodePen for demos. You can follow the demo or setup a new CodePen pen. You just need to import React and ReactDOM library:
<html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>To-Do</title> </head> <body> <div class="container"> <div id="container" class="col-md-8 col-md-offset-2"> </div> </div> <script src=""></script> <script src=""></script> </body> </html>
ReactDOM is a standalone library that is used to render React components on the DOM.
Types of Components
There are two types of component. These types are not just react-based but can be visualized in any other component-based UI library or framework. They include:
- Presentation Component
- Container Component
Presentation Component: These are contained components that are responsible for UI. They are composed with JSX and rendered using the render method. The key rule about this type of component is that they are stateless meaning that no state of any sort is needed in such components. Data is kept in sync using
props.
If all that a presentation component does is render HTML based on
props, then you can use stateless function to define the component rather than classes.
Container Component: This type of component complements presentation component by providing states. It's always the guy at the top of the family tree, making sure that data is coordinated.Essential Reading: Learn React from Scratch! (2019 Edition)
You do not necessarily need a state management tool outside of what React provides if what you are building does not have too much nested children and less complex. A To-Do is is simple so we can do with what React offers for now provided we understand how and when to use a presentation or container component
Recognizing Presentation Components
It is a recommended practice to have a rough visual representation of what you are about to build. This practice is becomes very important when it comes to component-based designs because it is easier to recognize presentation components.
Your image must not be a clean sketch made with a sketch app. It can just be a pencil work. The most important thing is that you have a visual representation of the task at hand.
From the above diagram, we can fish out our presentation components:
- TodoForm : purple
- Title: green
- TodoList: red
- Todo: grey
Todo Form
Functional components (a.k.a stateless components) are good for presentation components because they are simple to manage and reason about when compared with class components.
For that sake, we will create the first presentation component,
TodoForm, with a functional component:
const TodoForm = ({addTodo}) => { // Input tracker let input; return ( <div> <input ref={node => { input = node; }} /> <button onClick={() => { addTodo(input.value); input.value = ''; }}> + </button> </div> ); };
Functional components just receive props (which we destructured with ES6) as arguments and return JSX to be rendered.
TodoForm has just one prop which is a handler that handles the click event for adding a new todo.
The value of the input is passed to the
input member variable using React's ref.
Todo & Todo List
These components present the list of to-do.
TodoList is a
ul element that contains a loop of
Todo components (made of
li elements`):
const Todo = ({todo, remove}) => { // Each Todo return (<li onClick(remove(todo.id))>{todo.text}</li>); } const TodoList = ({todos, remove}) => { // Map through the todos const todoNode = todos.map((todo) => { return (<Todo todo={todo} key={todo.id} remove={remove}/>) }); return (<ul>{todoNode}</ul>); }
See the Pen AXNJpJ by Chris Nwamba (@christiannwamba) on CodePen.
The
remove property is an event handler that will be called when the list item is clicked. The idea is to delete an item when it is clicked. This will be taken care of in the container component.
The only way the
remove property can be passed to it's to the
Todo component is via it's parent (not grand-parent). For this sake, in as much as the container component that will own
TodoList should handle item removal, we still have to pass down the handler from grand-parent to grand-child through the parent.
This is a common challenge that you will encounter in a nested component when building React applications. If the nesting is going to be deep, it is advised you use container components to split the hierarchy.
Title
The title component just shows the title of the application:
const Title = () => { return ( <div> <div> <h1>to-do</h1> </div> </div> ); }
Container Component (Todo App)
This will eventually become the heart of this application by regulating props and managing state among the presentation components. We already have a form and a list that are independent on each other but we need to do some tying together where needed.
// Contaner Component // Todo Id window.id = 0; class TodoApp extends React.Component{ constructor(props){ // Pass props to parent class super(props); // Set initial state this.state = { data: [] } } // Add todo handler addTodo(val){ // Assemble data const todo = {text: val, id: window.id++} // Update data this.state.data.push(todo); // Update state this.setState({data: this.state.data}); } // Handle remove handleRemove(id){ // Filter all todos except the one to be removed const remainder = this.state.data.filter((todo) => { if(todo.id !== id) return todo; }); // Update state with filter this.setState({data: remainder}); } render(){ // Render JSX return ( <div> <Title /> <TodoForm addTodo={this.addTodo.bind(this)}/> <TodoList todos={this.state.data} remove={this.handleRemove.bind(this)} /> </div> ); } }
We first setup the component's constructor by passing props to the parent class and setting the initial state of our application.
Next we create handlers for adding and removing todo which the events are fired in
TodoForm component and
Todo component respectively.
setState method is used to update the application state at any point.
As usual, we render the JSX passing in our props which will be received by the the child components.
DOM Rendering
We have been rendering our demo components to the browser without discussing how but can be seen in the CodePen samples. React abstracts rendering to a different library called ReactDOM which takes your app's root component and renders it on a provided DOM using an exposed render method:
ReactDOM.render(<TodoApp />, document.getElementById('container'));
The first argument is the component to be rendered and the second argument is the DOM element to render on.
Working with a Server
We could step up our game by working with a HTTP server rather than just a simple local array. We do not have to bear the weight of jQuery to make HTTP request, rather we can make use of a smaller library like Axios.
<script src=""></script>
React lifecycle methods help you hook into React process and perform some actions. An example is doing something once a component is ready. This is done in the
componentDidMount lifecycle method. Lifecycle methods are just like normal class methods and cannot be used in a stateless component.
class TodoApp extends React.Component{ constructor(props){ // Pass props to parent class super(props); // Set initial state this.state = { data: [] } this.apiUrl = '' } // Lifecycle method componentDidMount(){ // Make HTTP reques with Axios axios.get(this.apiUrl) .then((res) => { // Set state with result this.setState({data:res.data}); }); } }
Mock API is a good mock backend for building frontend apps that needs to consume an API in the future. We store the API URL provided by Mock API as a class property so it can be accessed by different members of the class just as the
componentDidMount lifecycle method is. Once there is a response and the promise resolves, we update the state using:
this.setState()
The add and remove methods now works with the API but also optimized for better user experience. We do not have to reload data when there is new todo, we just push to the existing array. Same with remove:
// Add todo handler addTodo(val){ // Assemble data const todo = {text: val} // Update data axios.post(this.apiUrl, todo) .then((res) => { this.state.data.push(res.data); this.setState({data: this.state.data}); }); } // Handle remove handleRemove(id){ // Filter all todos except the one to be removed const remainder = this.state.data.filter((todo) => { if(todo.id !== id) return todo; }); // Update state with filter axios.delete(this.apiUrl+'/'+id) .then((res) => { this.setState({data: remainder}); }) }
Count and Style
We could keep track of the total items in our To-Do with the Title component. This one is easy, place a property on the Title component to store the count and pass down the computed count from TodoApp:
// Title const Title = ({todoCount}) => { return ( <div> <div> <h1>to-do ({todoCount})</h1> </div> </div> ); } // Todo App class TodoApp extends React.Component{ //... render(){ // Render JSX return ( <div> <Title todoCount={this.state.data.length}/> <!--...--> </div> ); } //... }
The app works as expected but not pretty enough for consumption. Bootstrap can take care of that. The following CodePen demo shows some updates made to change the look of the app:
See the Pen PzVyRm by Chris Nwamba (@christiannwamba) on CodePen.
What Next
We violated minor best practices for brevity but most importantly, you get the idea of how to build a React app following community recommended patterns.
As I mentioned earlier, you don't need to use a state management library in React applications if your application is simpler. Anytime you have doubt if you need them or not, then you don't need them. (YAGNI).
On the other hand, expect an article on Redux from Scotch soon. | https://scotch.io/tutorials/create-a-simple-to-do-app-with-react?utm_source=scotch&utm_campaign=share&utm_medium=facebook | CC-MAIN-2019-30 | refinedweb | 1,694 | 54.12 |
Introduction chose this because I am in the process of porting my Find Amber app from Windows Phone to Windows 8 and I wanted to transition the app without drifting too far from the spirit of the original app.You can see from the screen shot that I had already used the [RadControls for Windows Phone](), so now I can bring some of the design through.
The controls do support both HTML and XAML design, if the current version of the controls do not include either or; I assure you the version you seek is in development and on its way.
Getting Started
The RadCustomHubTile allows **any **user-defined content rather than predefined parts that you may find in a RadHubTile or RadSlideTile, and as in most if not all of the Telerik controls; MVVM as well as code based binding is supported.
Prior to trying this example, please download the controls from Telerik and note that I am using MVVM Light as the MVVM Framework. You can see how to install MVVM Light via nuget by opening the Package Manager console and running "Install-Package mvvmlight". If you have any trouble with that please see or contact me via twitter (@spboyer) OR see my blog post on how to get started with Windows 8 and MVVM Light.
In the following example you will see:
- MVVM Binding
- Content locally bound
- Content bound from an internet URI
- Complex front and back content for the tileThis is a moderately simply example. I started with a Blank Solution in Visual Studio 2012 and called it RadCustomHubTile (in retrospect probably should have stuck with App1).
Install the MVVM Light Framework via nuget (see above), you will have to make a change to the App.xaml file. When installing this, it adds the reference to the namespace in the old way
_ xmlns:vm="clr-namespace:RadHubTile.ViewModel" _
you need to change this to:
_ xmlns:vm="using:RadHubTile.ViewModel" _
A little house keeping to make it look nice. Yes I care what it looks like even for this. Go ahead and add the following below the <Grid> tag to add the header to the initial page. You can change the title if you like and run (F5).
<Grid.RowDefinitions> <RowDefinition Height="140"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Button x: <TextBlock x: </Grid>
Next, lets add the RadCustomHubTile Control, and the best way to do this is to simply drag it from the toolbox right into the spot within the XAML. This is something you could not do in Windows Phone which is a big step in my opinion.
It will add the namespace and the references to the project.
To clean it up a little and make sure that you are using within the design guidelines, wrap the RadHubControl with a Grid with the following settings.
<Grid Grid. <Primitives:RadCustomHubTile /> </Grid>
If you are wondering why my RadCustomHubTile is prefixed, it is because I have changed or altered the declaration at the top of the page to be the following (this matches my Phone app stuff).
xmlns:Primitives="using:Telerik.UI.Xaml.Controls.Primitives"
Setting Front and Back Content
The content for the front and back are defined by setting the content within the <radcustomhubtile.frontcontent> and <radcustomhubtile.backcontent> respectively. Pretty simple, so here is an example:</radcustomhubtile.backcontent></radcustomhubtile.frontcontent>
<Primitives:RadCustomHubTileNote that you will want to wrap your content with the FrontContent / BackContent tags in Grid, StackPanel etc as the designer will give you the "Content cannot be set more than once error".
<Primitives:RadCustomHubTile.FrontContent>
<Grid>
<Image x:
<Rectangle Height="65" Fill="#99000000" VerticalAlignment="Bottom" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="Blogger:"
Foreground="White" Width="126" Height="43"
VerticalAlignment="Bottom"
Margin="10,0,0,14" Style="{StaticResource SubheaderTextStyle}"
HorizontalAlignment="Left" />
<TextBlock Text="{Binding UserName}" Foreground="White" Height="43" VerticalAlignment="Bottom" Margin="0,0,0,14" Style="{StaticResource SubheaderTextStyle}"/>
</StackPanel>
</Grid>
</Primitives:RadCustomHubTile.FrontContent>
<Primitives:RadCustomHubTile.BackContent>
<Grid>
<Image x:
<Rectangle Height="65" Fill="#99000000" VerticalAlignment="Bottom" />
<TextBlock Text="{Binding Title, Mode=TwoWay}"
Foreground="White" Width="270" Height="30"
VerticalAlignment="Bottom"
Margin="0,0,0,30" Style="{StaticResource BasicTextStyle}" />
<TextBlock Text="{Binding SubTitle, Mode=TwoWay}"
Foreground="White" Width="270" Height="30"
VerticalAlignment="Bottom" Margin="0,0,0,5"
Style="{StaticResource BasicTextStyle}"/>
</Grid>
</Primitives:RadCustomHubTile.BackContent>
</Primitives:RadCustomHubTile>
Here is the MainViewModel that is bound. Note that the Blogger image (me), is pulled from an internet source uri and the back image is pulled from the project itself. The string properties are bound simply.
using GalaSoft.MvvmLight; using System; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; namespace RadHubTile.ViewModel { public class MainViewModel : ViewModelBase { /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { } public string Photo { get { return ""; } } public string UserName { get { return "Shayne Boyer"; } } public ImageSource Thumbnail { get { return new BitmapImage(new System.Uri(new Uri("ms-appx:"), "/Assets/RadCustomHubTile.png"));} } public string Title { get { return "Telerik Windows 8 UI Controls"; } } public string SubTitle { get { return "RadCustomHubTile"; } } } }
So what does it all look like?
Front
Back
One other item to note is that you can alter the duration of the flip/rotation by setting the UpdateInterval which is a TimeSpan. So setting the value to "0:0:5" would be equal to 5 seconds. There is also FlowDirection and many other properties to customize the Tile to your liking. I'd like to see what you can do with it. Download the controls today and let me know what you working on and if you have any questions. | https://tattoocoder.com/rad_custom_hub_tile_from_telerik_for_windows_8_ui/ | CC-MAIN-2021-31 | refinedweb | 932 | 53 |
Code Focused
Learn how to extend support for Microsoft C#-only BlankExtension/BizType projects to Visual Basic.
In my recent article, "Is Visual Studio LightSwitch the New Access?", I looked at the suitability of LightSwitch as a replacement tool for departmental applications developed in Microsoft Access. LightSwitch is being positioned as a tool for the power user to develop Microsoft .NET Framework applications without having to face the substantial learning curve of the full .NET technology stack. I described each of the six extension types available to add the functionality to LightSwitch that an experienced .NET developer might want to use to make development in LightSwitch easier, or that a designer may want to use to build a visually appealing application.
This article demonstrates the usefulness of LightSwitch extension points by showing how to build a custom business data type to provide automatic encryption to a database string field. Once installed, the "Encrypted String" field data type can be available for use in any table in a LightSwitch project with the extension enabled. When a field of the Encrypted String data type is used in a LightSwitch screen, the field automatically decrypts itself when the cursor enters the field and automatically encrypts itself whenever the cursor leaves the field. The LightSwitch developer can store sensitive information in the database in encrypted form with no more effort than selecting the "Encrypted String" data type when designing the table.
Figure 1 shows an example of a LightSwitch grid with two rows of data, each row having User Name and Password as the Encrypted String data type. The cursor is in the Password field of the first row, so it's shown and editable as plain text -- which is automatically encrypted when the cursor leaves the field. The Comments column shows the decrypted value of each field. The database sees and saves the field value in its encrypted form; be sure to allow sufficient length in the database field for the encrypted string value.
Installing and Using the Encrypted String Business Type
In order to run LightSwitch, you must be using Visual Studio Professional or higher with Service Pack 1 installed, and also the Visual Studio LightSwitch beta 2 (available for download here). Beta 1 must be uninstalled before installing beta 2.
To install the Encrypted String business type into LightSwitch, download the code from this article and extract all files. Close all instances of Visual Studio. Double-click the Blank.Vsix.vsix file found in the Blank.VSIX\bin folder. You'll see the Visual Studio Extension Installer dialog box. Make sure the Microsoft LightSwitch checkbox is checked and click the Install button. You'll see an Installation Complete confirmation dialog box once the install is done. The Visual Studio Extension Manager will now show Encrypted String Extension in the Installed Extensions list.
The Encrypted String extension must be enabled in any LightSwitch project that wishes to use it. In the LightSwitch project, right-click on the project's properties and choose the Extensions tab. Click on the Encrypted String Extension item to activate it for the project, as shown in Figure 2. Now the Encrypted String data type is available for use when creating a table in the same manner as an Integer, Date Time or String field.
To remove existing LightSwitch extensions, go to the Extension Manager in Visual Studio. Choose Tools and then Extension Manager, then select the extension and choose Uninstall. Close Visual Studio for the change to take effect.
Creating the Custom Business Type Extension
On March 16, 2011, the LightSwitch team published the "LightSwitch Beta 2 Extensibility Cookbook". In addition to the Cookbook document, the post has a BlankExtension.zip file, which is the completed version of the Cookbook's instructions to create a sample extension of each type in the Cookbook. This completed sample will serve as the starting point to create the Encrypted String custom business type extension. The instructions in this section serve as a guide for how you can modify this sample project to implement your own custom business type, as I did.
Download the BlankExtension.zip file and extract the "Blank Extension - BizType" project to a location of your choosing. Load the BlankExtension solution into Visual Studio. Examine each project in the Blank Extension solution to ensure all LightSwitch references are correct in the Blank.Client, Blank.ClientDesign and Blank.Common projects. Note that the LightSwitch beta 2 product does not install into the Global Assembly Cache, or GAC, but instead into the C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\LightSwitch\1.0 folder. Remove any incorrect references and browse to the needed assemblies in the Client subfolder of the LightSwitch folder.
You may have already noticed that this is a C# language solution; a Visual Basic version of the BlankExtension - BizType project is not available. We'll be able to add a Visual Basic class project to hold our custom encrypted string business logic, but we'll need to make a few modifications in the existing C# code to call that class.
Next, we modify the project to identify the extension in the Visual Studio Extension Manager. In the BlankModule.cs file of the BlankModule.Common project, change the Name constant from "Blank" to "EncryptedStringBizType" and modify the source.extension.vsixmanifest file, as shown in Figure 3. The ID field must match the Name constant and the Product Name field value must be unique for all extensions, as it will be the folder where the extension will be installed. The path where extensions are installed in Windows 7 is C:\Users\{UserName}\AppData\Local\Microsoft\VisualStudio\10.0\Extensions\{VSIX Author}\{VSIX Product Name}\1.0\. This must result in a unique path for each extension to be installed.
To have the VSIX file reflect the identity of the extension, change the Assembly Name to "EncryptedStringBizType.Vsix" in the Application tab of the Blank.Vsix project property page. Leave the Default namespace as Blank.Vsix. Also change the Module Name property to "EncryptedStringBizType" in the BlankModule.lsml file in the Metadata folder of the Blank.Common project. Here's the code:
<?xml version="1.0" encoding="utf-8" ?>
<ModelFragment
xmlns=""
xmlns:
<Module Name="EncryptedStringBizType" />
</ModelFragment>
Remove the <AttributeProperty Name="Business" MetaType="Int32"> tag and its contents, as it's part of the Cookbook example and not relevant to our Encrypted String data type. See Listing 1 for the revised BlankPresentation.lsml file.
This is sufficient for the business type extension to be unique in the Visual Studio Extension Manager. From this point forward you can test the extension at any time by uninstalling any previous version in the Visual Studio Extension Manager, and double-clicking the EncryptedString.vsix file in the bin\Release folder of the Blank.vsix project to install it.
Next, change the name of the extension in the solution from the "MyBusiness" of the Cookbook example to "EncryptedString" using a global search and replace across the entire solution. Compile the solution to ensure the changes have no errors. In my experience, there were 51 changes and no errors created.
Next, remove the validations that were placed into the Blank-Solution as part of the MyBusiness sample. Go to the MyBusinessValidator.cs file of the Blank.Client project and comment out the contents of the Validate method in the EncryptedStringValidator class. This will remove the restriction from the MyBusiness sample that the encrypted field can only be 15 characters maximum length.
Finally, we add the Visual Basic project that will contain our Encrypted String business logic. Add a Visual Basic Silverlight 4 class library to the solution and name it EncryptedString.
Rename the automatically generated class file and class name to EncryptedString, as shown in Figure 4.
Next, modify the EncryptedString class (as shown in Listing 2) to provide the string encryption and decryption services to the editor control. The encryption password is based on the GUID of the EncryptedString project. While this is convenient as a password for the purposes of this article, for best security of the encrypted data, you should modify the EncryptedString class to obtain the GUID from a source outside the application. Changing the GUID in the AssemblyInfo.vb file of the EncryptedString Visual Basic project and re-compiling the solution will change the password from the code download for some additional security.
The Rfc2898DeriveBytes method implements key stretching based on the Password-Based Key Derivation Function (PBKDF2) and is applied 10,000 times to the GUID to make cracking the password significantly more difficult. This process generates a pseudo-random Key and Initialization Vector, or IV, for use as the cryptographic keys in the EncryptString and DecryptString methods in EncryptedString.vb.
In the spirit of language parity, I've implemented identical functionality in C#. I've also updated the BlankModule.cs file in the Blank.Common project to reflect this functionality. The needed using statements are included in the online listing as comments.
Next, we modify the Silverlight Client editor control to call the DecryptString method when the cursor enters the editor field, and to call the EncryptString method when the cursor leaves the editor field. The Blank.Client project needs a reference to the Encrypt-edString.dll assembly (not a Project reference). Browse to the Bin\Release folder of the EncryptedString project to add the reference.
Create event handlers for the editor's GotFocus and LostFocus events. Open the MyBusinessControl.xaml file in the Blank.Client project, highlight the Silverlight control, click on the Events property tab and double-click both the GotFocus and LostFocus events to create default event handlers. Modify the MyBusinessControl.xaml.cs with the code shown in Listing 3 to call the proper encryption methods. If desired, the C# version of the EncryptedString methods can be called by uncommenting the C# class instantiation and commenting out the Visual Basic instantiation.
Finally, we need to include the Visual Basic EncryptedString.dll assembly into the LsPkg that's part of the VSIX extension file, so it can be available for use at runtime. This requires editing the Blank.Lspkg.csproj file in the Blank.LsPkg project in Notepad. Locate the two <ItemGroup> sections and add the lines containing EncryptedString, as shown in Listing 4 (we must add entries for ClientGeneratedReference, IDEReference, ServerGeneratedReference and ProjectReference).
Build the solution and ensure there are no errors. Now install and test the extension using the procedures outlined at the beginning of this article. Remember that Visual Studio must be restarted each time there are changes to the Extensions, in order for the changes to be seen by the IDE.
LightSwitch Shows its Youth
The process described in this article relies on the BlankExtension - BizType sample provided by the LightSwitch team. If you follow this same process to create a second BizType extension, you'll find that both will successfully load into the Visual Studio Extension Manager, but only one can be active in the LightSwitch project at a time. It's not clear why this is the case. Further guidance from Microsoft is needed to produce truly independent, custom BizType extensions.
The custom business type extension in LightSwitch provides the experienced .NET developer with a means to add useful data types for the LightSwitch developer to easily consume, as shown by the EncryptedString data type produced in this article. I'm confident that the process of creating extensions will become easier as the product matures. It's very impressive that the LightSwitch team has invested heavily in providing extension capabilities as a core feature of the product. This speaks well to the future success of LightSwitch as a product that will provide easier .NET application development for a wide variety of needs. LightSwitch beta 2 is already a great product that will only get better with age.
Printable Format
> More TechLibrary
I agree to this site's Privacy Policy.
> More Webcasts | https://visualstudiomagazine.com/articles/2011/07/01/pcovb_biztype.aspx | CC-MAIN-2015-48 | refinedweb | 1,981 | 56.05 |
Say I have a
fabfile.py
def setup():
pwd = getpass('mysql password: ')
run('mysql -umoo -p%s something' % pwd)
[host] run: mysql -umoo -pTheActualPassword
[host] run: mysql -umoo -p*******
Rather than modifying / overriding Fabric, you could replace stdout (or any iostream) with a filter.
Here's an example of overriding stdout to censor a specific password. It gets the password from Fabric's
env.password variable, set by the
-I argument. Note that you could do the same thing with a regular expression, so that you wouldn't have to specify the password in the filter.
I should also mention, this isn't the most efficient code in the world, but if you're using fabric you're likely gluing a couple things together and care more about manageability than speed.
#!/usr/bin/python import sys import string from fabric.api import * from fabric.tasks import * from fabric.contrib import * class StreamFilter(object): def __init__(self, filter, stream): self.stream = stream self.filter = filter def write(self,data): data = data.replace(self.filter, '[[TOP SECRET]]') self.stream.write(data) self.stream.flush() def flush(self): self.stream.flush() @task def can_you_see_the_password(): sys.stdout = StreamFilter(env.password, sys.stdout) print 'Hello there' print 'My password is %s' % env.password
When run:
fab -I can_you_see_the_password Initial value for env.password:
this will produce:
Hello there My password is [[TOP SECRET]] | https://codedump.io/share/oZRX2UIkiFhe/1/how-to-hide-the-password-in-fabric-when-the-command-is-printed-out | CC-MAIN-2017-13 | refinedweb | 228 | 52.97 |
Your answer is one click away!
I have three threads ThreadA, ThreadB and ThreadC printing values A, B and C respectively in loop.
I want output to be like A,B,C and then again A, B and C till loops are executing in threads.I want to write this sample program using wait and notify. Below code is printing the desired output but sometimes I am just seeing "A" in output, I am not able to figure out the case.
public class ThreadOrder { public static void main(String[] args) { Object lockAB = new Object(); Object lockBC = new Object(); Object lockCA = new Object(); Thread threadA = new Thread(new ThreadOrder().new ThreadA(lockAB, lockCA)); Thread threadB = new Thread(new ThreadOrder().new ThreadB(lockAB, lockBC)); Thread threadC = new Thread(new ThreadOrder().new ThreadC(lockBC, lockCA)); threadA.start(); threadB.start(); threadC.start(); } class ThreadA implements Runnable { Object lockAB; Object lockCA; public ThreadA(Object lockAB, Object lockCA) { this.lockAB = lockAB; this.lockCA = lockCA; } @Override public void run() { for(int i=0; i<3; i++) { if(i!=0) { try { synchronized (lockCA) { lockCA.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("A"); synchronized (lockAB) { lockAB.notify(); } } } } class ThreadB implements Runnable { Object lockAB; Object lockBC; public ThreadB(Object lockAB, Object lockBC) { this.lockAB = lockAB; this.lockBC = lockBC; } @Override public void run() { for(int
Consider creating a ring of threads connected to one another by blocking queues. Then you can pass a token around the ring. Each thread waits to receive the token, prints its output, passes the token on to the next thread in the ring, and goes back to waiting.
You call
wait, but you haven't tested if there's anything to wait for. You call
notify, but you haven't changed anything that you would need to notify another thread about. You have all these
synchronized methods, but no shared state for the synchronization to protect.
Nothing in your code makes any sense and it seems that you fundamentally don't understand what the
wait/
notify mechanism does. The
wait function allows a thread to wait for some shared state to change, and the
notify function allows one thread to tell others that some shared state has changed. But there has to be some shared state because the
wait/
notify mechanism (unlike a lock or sempahore) is internally stateless.
You should probably have some shared state protected by the synchronization. It should encode which thread should go next. If you need to print, but the shared state says it's not your turn, then you have something to
wait for. When you print and make it some other thread's turn to print next, then you have something to
notify other threads about. | http://www.devsplanet.com/question/35274824 | CC-MAIN-2017-22 | refinedweb | 449 | 74.59 |
Views: 930
Muhammad Asad Khan gud keep it up &.
any one here to ans me about this qstn
ma puri book chain mari nhn milya ans kndly mjy anssssssssssssssssss bta to is
Write down the TSR program that intercepts the interrupt 17H and gives all the spaces in print document.? of cs609
I think TSR interrupt 17H question was in one of the assignments in this or last semester.
sample program at page 88 of handout modified version
#include <dos.h>
void interrupt (*old)( );
void interrupt newint ( );
main( )
{
old = getvect(0x17);
setvect(0x17,newint);
keep(0,1000);
}
void interrupt new ()
{ if (_AH==0)
{
_AL=0x20 //setting the AL register that contains the ASCII code of char to be displayed space=20
(*old)();
}
}
asad khan and tyyyaba rehman thanx for sharing the paper
plz koe aj ka paper bhe send kar dy mara kal paper ha.plz
My today cs609 paper (3 march 2013)
Q#1 In how many ways higher PC can operate?
Q#2 In FAT32, what is the size of FSInfo?
Q#3 A disk is divided into three partition. What type of information is represented in code part of partition table?
Q#4 Differences between FAT16 and FAT32
Q#5 How ISR sends EOI (End of interrupt) signals to master and slave .Required statement must be in C program
Q#6?
Q#7 Distinguish between 80287 and 80387
Q#8 Write down procedure to convert a cluster number into sector number
Q#9 Describe how a chain of cluster in FAT12 is managed?
Q#10 How a PC operates in protected mode?
© 2021 Created by + M.Tariq Malik.
Promote Us | Report an Issue | Privacy Policy | Terms of Service | https://vustudents.ning.com/group/cs609systemprogramming/forum/topics/my-cs609-finalterm-current-paper-24-feb-2013-11-am-sunday-by?commentId=3783342%3AComment%3A2286603&groupId=3783342%3AGroup%3A59533 | CC-MAIN-2021-49 | refinedweb | 281 | 70.84 |
You did not run "echo your hostname > /etc/hostname. The Arch wiki has detailed instructions give it a read.
Take One Tablet By Mouth Twice A Day! Better to vote for a short term political guardian then to be ruled by a monarchy.
Offline
Just to clarify, is this a support question (as rm_/etc is assuming) or why "localhost.localdomain" instead of just "localhost"?
Steven [ web : git ]
GPG: 327B 20CE 21EA 68CF A7748675 7C92 3221 5899 410C
Do not email: honeypot@stebalien.com
Offline
You are talking about in /etc/hosts correct?
localhost is a hostname
localdomain is a domain name
localhost.localdomain is a FQDM... well fully qualified on the localsystem
You need that record because it is suppose to be there. It is a standard. If you remove it some software you may run may not work correctly.
OpenBSD-current Thinkpad X230, i7-3520M, 16GB CL9 Kingston, Samsung 830 256GB
Contributor: linux-grsec
Offline
Sorry, it appeared I wasn't subscribed to topics I post in.
Just to clarify, is this a support question (as rm_/etc is assuming) or why "localhost.localdomain" instead of just "localhost"?
the latter
It is a standard.
De-facto standard you mean? Which distribution adhere to it?
Others on this list have pointed out that some applications expect
127.0.0.1 to resolve to localhost. When the resolver uses /etc/hosts,
it returns the first host in the list and the others are considered
aliases. In the first example above, localhost.localdomain would be
returned when resolving 127.0.0.1; this is because it is listed before
localhost. If /etc/hosts were changed to:
127.0.0.1 localhost localhost.localdomain
Resolution of 127.0.0.1 would properly return localhost.
I've been unable to find any specific reference to a required structure
of a hosts file nor any specific requirement that a resolver should
resolve 127.0.0.1 to localhost. However, consider the following two
points:
1 -- When configuring DNS, 127.0.0.1 must resolve to localhost and vice
versa [1]. Configuring an /etc/hosts file that resolves 127.0.0.1 to
localhost.localdomain is inconsistent. On the same host, resolving
127.0.0.1 by gethostbyname() and running nslookup will return two
different answers (provided nsswitch.conf is configured with "files
dns"). [1] RFC 1912 -
2 -- Virtually all systems with a hosts file read something like this:
127.0.0.1 localhost <alias> <another alias> <...>
There is a long historical precedent for listing localhost first,
followed by other aliases. This results in the resolver properly
returning localhost when resolving 127.0.0.1.
In summary: (1) It's reasonable to expect DNS and file based resolution
to function the same in regard to 127.0.0.1/localhost (proper DNS
resolution of 127.0.0.1 is documented in RFC 1912). (2) There is a long
historical precedent for localhost preceding all aliases of 127.0.0.1 in
a hosts file.
Thanks! … 00559.html
I consider using hostname -f for anything other then the initial default value
broken because computers can have multiple network cards, multiple IP
addresses, multiple domains, etc. I generally like to assume my computer isn't
going to break badly because I have to change the output hostname -f returns.
Also, FQDNs are really not applicable to, say laptops, which frequently change
from one network to another. Or some desktops even. I notice on this Ubuntu
laptop `hostname` == `hostname -f` perhaps for this reason. … 00778.html
The only reason debian had it for some time is because Red Hat had it for some reason. AFAIU debian got rid of it since 14 Oct 2005 and it somehow works since then.
Offline
As an extra data point: I run all of my systems (Linux and NetBSD) without any reference to 127.0.0.1 in /etc/hosts, only ::1 (the IPv6 equivalent), resolving to "localhost" and nothing else. I only had to change the config of some applications to refer to "localhost" instead of "127.0.0.1" explicitly. An easy grep 127.0.0.1 /etc finds most of them.
On most of those systems (except one where I need to support a proprietary IPv4-only VPN client which breaks on it), I actually remove the 127.0.0.1 address from the loopback interface, having only ::1 configured, ie. an IPv6-only localhost. Works fine.
There's to many mysticism around all this. Applications should use "localhost" for local connections or port bindings, and you define what it resolves to (some loopback interface). "localhost.localdomain" is a brain fart of someone who misunderstoond "FQDN", and is nowhere standardized.
Offline
hunterthomson wrote:
It is a standard.
De-facto standard you mean? Which distribution adhere to it?
It is a standard on every operating system I know of. It is a networking standard. If it is a networked OS it is localhost.localdomain. Like I said though, "it may"... Sure, if you are not running any server software configured to use that then you will not notice any problems. However that is what it is for and why it is there.
Last edited by hunterthomson (2013-01-19 10:11:11)
OpenBSD-current Thinkpad X230, i7-3520M, 16GB CL9 Kingston, Samsung 830 256GB
Contributor: linux-grsec
Offline
hunterthomson, judging from your response:
1) you don't know which distributions (except for Arch Linux) resort to using localhost.localdomain,
2) no RFC or any other standard enforces specifying localhost.localdomain as a FQDN for localhost.
Sure, if you are not running any server software configured to use that then you will not notice any problems.
Sure, it's not the case.
Offline
Dude, basically it is there as a filler to make the /etc/hosts file consistent i.e. IP hostname.domain hostname
RedHat has it and I guess Debian as well. That is like.... just guessing 70-90% of the Linux Server market. If you don't like it in there then delete it and see what happens. Why would you expect me or anyone ells to search for RFC's # and other distro's for you?
I know Postfix SMTP server has a configuration for Hostname and Domain name. So, if you don't have localhost.localdomain you will have problems, because you don't have a local domain.
CentOS 5
/etc/postfix/main.cf
# = localhost.localdomain # The mydomain parameter specifies the local internet domain name. # The default is to use $myhostname minus the first component. # $mydomain is used as a default value for many other configuration # parameters. # mydomain = localdomain
Last edited by hunterthomson (2013-01-28 10:29:00)
OpenBSD-current Thinkpad X230, i7-3520M, 16GB CL9 Kingston, Samsung 830 256GB
Contributor: linux-grsec
Offline
Dude, basically it is there as a filler to make the /etc/hosts file consistent i.e. IP hostname.domain hostname
In other words, you mean the point is in every hostname having its FQDN? But why do you prefer this consistency over consistency between /etc/hosts and bind (DNS)?. On top of it, localhost.localdomain is yet another special case.
I guess Debian as well
AFAIU debian got rid of it since 14 Oct 2005 and it somehow works since then.
Are you even reading my replies?
netcfg is the package responsible for creating initial /etc/hosts file in debian. Here is the quotation from Changelog:
netcfg (1.17) unstable; urgency=low
[ Thomas Hood ]
* Don't make 'localhost.localdomain' the canonical hostname of 127.0.0.1.
See Oct 2005 debian-devel discussion with Subject: localhost.localdomain,
e.g., … 00559.html
-- Frans Pop <fjp@debian.org> Tue, 15 Nov 2005 20:59:54 +0100
And here is the code, which creates /etc/hosts file:
if ((fp = file_open(HOSTS_FILE, "w"))) { fprintf(fp, "127.0.0.1\tlocalhost"); if (!empty_str(ipaddress)) { if (domain_nodot && !empty_str(domain_nodot)) fprintf(fp, "\n%s\t%s.%s\t%s\n", ipaddress, hostname, domain_nodot, hostname); else fprintf(fp, "\n%s\t%s\n", ipaddress, hostname); } else { #if defined(__linux__) || defined(__GNU__) if (domain_nodot && !empty_str(domain_nodot)) fprintf(fp, "\n127.0.1.1\t%s.%s\t%s\n", hostname, domain_nodot, hostname); else fprintf(fp, "\n127.0.1.1\t%s\n", hostname); #else fprintf(fp, "\t%s\n", hostname); #endif } fprintf(fp, "\n" IPV6_HOSTS); fclose(fp); }
RedHat has it and I guess Debian as well. That is like.... just guessing 70-90% of the Linux Server market.
Let us see (these are output from freshly installed systems):
$ cat /etc/centos-release CentOS release 6.3 (Final) $ cat /etc/hosts 127.0.0.1 localhost.localdomain localhost ::1 localhost6.localdomain6 localhost6 $ hostname localhost.localdomain $ hostname -f localhost.localdomain
$ cat /etc/redhat-release Fedora release 18 (Spherical Cow) $ cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 $ hostname localhost.localdomain $ hostname -f localhost
$ cat /etc/debian_version 6.0.6 $ cat /etc/hosts 127.0.0.1 localhost 127.0.1.1 t yuri@tdeb:~$ hostname yuri-pc yuri@tdeb:~$ hostname -f yuri-pc
$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 12.10 Release: 12.10 Codename: quantal $ cat /etc/hosts 127.0.0.1 localhost 127.0.1.1 tub $ hostname yuri-pc $ hostname -f yuri-pc
Consistency you say? Debian and ubuntu got rid of it. What is redhat doing? Beats me. Can someone explain?
If you don't like it in there then delete it and see what happens.
My servers work that way for at least several years.
Why would you expect me or anyone ells to search for RFC's # for you?
One might say, that if you say that it's a standard it's up to you to come up with a proof. But why don't you just tell us how things stand: you don't know if it's in any standard and you have no time/desire to prove it?
I know Postfix SMTP server has a configuration for Hostname and Domain name. So, if you don't have localhost.localdomain you will have problems, because you don't have a local domain.
Let us see what Arch Linux suggests to use for these settings. They are just placeholders for real data
Some more consistency:
MUAs again
~~~~~~~~~~
Different MUAs have very different ways of coming up with the
"host" part of message i.d.s.
* /usr/bin/mail in the mailx package uses $(/bin/hostname)
* elm (or, rather, postfix) uses whatever postfix's "myhostname"
parameter is set to in /etc/postfix/main.cf
* mutt uses $(cat /etc/mailname)
* evolution mail uses $(/bin/hostname --fqdn)
* mozilla mail uses the host part of the sender's e-mail address
* balsa uses $(hostname) from the time that X starts
* sylpheed tacks on the whole sender e-mail address
Clearly we should not allow the practices of mail software to
govern our decision about what we put into /etc/hosts. … =247734#27
P.S. Here's the discussion I mentioned in OP but in much more readable and easy to get familiarized with format. Or so I believe. Non-relevant/non-interesting parts are marked grey. There is not much left to read.
Offline
Btw, do note how localhost.localdomain was introduced in debian:
I can not remember precisely. I think that at that time I was testing the debian-installer and I saw it was taken a long while to boot. I saw that my system had no FQDN (hostname -f). When you add .localdomain, the FQDN is complete and it helps to solve timeout in several application.
So it was just papering over a real bug, namely the existence of the “-f” option of hostname. “hostname -f” assumes that the hostname (as returned by gethostname(3)) has something to do with networking, which is false. It also assumes that the system has just one IP address with one FQDN which is also false.
This is a perfect example of a long-standing assumption that was wrong from the start but tended to work in the past when the wast majority of computers had really just one network interface with one IP address, and the few machines having multiple NICs/multiple IP addresses had good sysadmins who could deal with the breakage caused by this assumption.
Nowadays even desktop boards start to come with multiple NICs on-board so this “one IP – one FQDN” assumption must be stopped. “hostname -f” must be killed, and everything that uses it must be fixed. Well, it may take some time to sort out all the details, there are a lot of broken programs out there…
Offline | https://bbs.archlinux.org/viewtopic.php?pid=1217284 | CC-MAIN-2016-40 | refinedweb | 2,113 | 60.31 |
Ok im making a program to help build my IRC client.
The program is designed to break up a sentence, copy them to other variables, then let me print out the variables in a fashion i choose.
I have a few problems though. Im storing the original sentence in an array, then copying them to other arrays, but i cant set up the code so that when they user has finished entering what they want (for example, hitting the enter key) it stops scanning in characters.
Can you please take a look at this code and see how you can imporve it.
I will add some documentation so it makes a bit more sense.
Thanks to anyone who bothers.
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <windows.h>
void main()
{
int asciinum, *pointer;
char spacechar;
int index;
char NULLchar, ch;
int asciinum2, *pointer2;
//Pointers that point at the ' ' char, so i can actually parse the line //
asciinum = 32;
pointer = &asciinum;
spacechar = *pointer;
char userentry[75];
userinputscreen:
printf ("Enter information in the following syntax...\n\n");
printf ("![Name] [Ident@Hostname] [Command] [Parameter]#\n");
printf ("[Name] = Less than 8 Characters\n");
printf ("[Ident@Hostname] = Less than 30 Characters\n");
printf ("[Command] = Less than 12 Characters\n");
printf ("[Parameter] = Less than 20 Characters\n");
printf ("End the statement with a #");
printf (":");
//This part of the code lacks something to stop it, because i couldnt set up pointers to do it. //
for (index = 0; index < 75; index++){
if (index > 74){
system("CLS");
printf ("You have exceeded the maximum ammount of Characters..\n");
printf ("Please re-enter your details\n\n");
main();
}
scanf ("%c",&userentry[index]);
}
printf ("\n\n");
printf ("\n\n");
index = 0;
if (userentry[index] != '!') {
system("CLS");
printf ("Inappropriate Syntax. ! must be before the nickname.");
main();
}
char username[9];
for (index = 0; index <8; index++){
if (userentry[index] = spacechar){
printf ("Space Character Found, Terminating Loop...");
}
userentry[index] = username[index];
}
//Prints out the user name, it currently prints out nothing or some general ascii crap//
printf("\n\n...:::");
for (index = 1; index < 7; index++){
printf ("%c", username[index]);
}
printf(":::...");
printf ("\n\n");
system("PAUSE");
return 0;
} | http://cboard.cprogramming.com/c-programming/4234-quite-stuffed-bit-code-actually.html | CC-MAIN-2016-07 | refinedweb | 361 | 64.91 |
VGUI Creating A Custom Screen
Contents
Quick Briefing
We will be trying to achieve the act of rendering vgui components in to our world. This is done via VGUI screens. A much more polished example is what you might see below:
TestScreen.h
Create a new header file, "TestScreen.h"
- Create a new class, called TestScreen, which inherits from CVGuiScreenPanel found in c_vguiscreen.h. As described in the header, this is the base class for all vgui screens.
- Use DECLARE_CLASS to give the source sdk some recognition to your class if need be later.
- Define your class constructor and destructor as you see below. Your constructor is expected to take two arguments, one is a pointer to the panel which is going to be your screen's parent. The other is string describing the meta class name you are to be creating (We'll get in to what these are a little later.)
- Declare two virtual functions which overload that of our super class. OnTick (so we can keep track of time...) as well as the function Init.
- Declare a pointer to a label, counter, that we will be incrementing at intervals of one second in length. When Init is called, we will initilize this pointer such that it points to the actual Label in our panel.
- Declare a new unsigned integer, which will keep track of what number our counter is currently reading.
TestScreen.h
#pragma once #include "cbase.h" #include "c_vguiscreen.h" #include "vgui_controls/Label.h" class TestScreen : public CVGuiScreenPanel { private: DECLARE_CLASS(TestScreen, CVGuiScreenPanel); vgui::Label* m_pLblCount; unsigned int m_uiCounter; public: TestScreen(vgui::Panel *pParent, const char *pMetaClassName); virtual ~TestScreen(); virtual void OnTick(); virtual bool Init(KeyValues* pKeyValues, VGuiScreenInitData_t* pInitData ); };
TestScreen.cpp
- At the end (or start) of your source file, place a macro DECLARE_VGUI_SCREEN_FACTORY. The first argument is the class which will be acting as a screen factory, and the second argument is the name of your screen factory. Later, you will reference this name in vgui_screens.txt when you are describing your screens.
- In the constructor, we simply initilize our label pointer & our counter to zero and call the base class's constructor.
- Per every tick, as can be seen in our implementation of OnTick, we call the base class's OnTick routine, and then increment our counter. We also set the text for our label (and format it using a stringstream.)
- In TestScreen::Init, we simply setup our frame's Tick signal, and have it tick at intervals of 1 second (1000 ms)
- The general trend within the source sdk engine (or so I have seen) is that the pMetaClassName member in our constructor is simply ignored and passed down to the super class. With that said, you can make several different kinds of forms with your factory depending on the "MetaClassName" argument (we'll get in to what this actually is when we edit vgui_screens.txt).
DECLARE_VGUI_SCREEN_FACTORY( TestScreen, "TestScreen" );
- In your constructor, initilize your
#include "cbase.h" #include "TestScreen.h" #include "vgui/IVGui.h" #include <sstream> TestScreen::TestScreen(vgui::Panel *pParent, const char *pMetaClassName) : CVGuiScreenPanel(pParent, pMetaClassName) { m_pLblCount = 0; m_uiCounter = 0; } TestScreen::~TestScreen() { } bool TestScreen::Init(KeyValues* pKeyValues, VGuiScreenInitData_t* pInitData) { if(!CVGuiScreenPanel::Init(pKeyValues, pInitData)) return false; vgui::ivgui()->AddTickSignal(GetVPanel(), 1000); m_pLblCount = dynamic_cast<vgui::Label*>(FindChildByName("lblCount")); return true; } void TestScreen::OnTick() { CVGuiScreenPanel::OnTick(); if(!m_pLblCount) return; m_pLblCount->SetText(VarArgs("Count: %i", m_uiCounter % 21)); m_uiCounter++; } DECLARE_VGUI_SCREEN_FACTORY( TestScreen, "TestScreen" );
Setting up vgui_screens.txt
Found in the directory: <your mod>\scripts. I.e, mine is:
C:\Program Files (x86)\Steam\steamapps\sourcemods\cj\scripts
In here, add the following under "VGUI_Screens";
- The "TestScreen" you see is the name of the factory that will be constructing the screen.
- We reference the resource file that describes the appearence of our screen in the "resfile" property. As you can see, we will be storing this resource file in "<your mod>/resource/screens/Count.res" once we create it.
- Also notice the pixelswide and pixelshigh members which describe the dimensions of our screen.
... ... "TestScreen" { "type" "TestScreen" // These describe the dimensions of the screen *in pixels* "pixelswide" 480 "pixelshigh" 240 // This is the name of the .res file to load up and apply to the vgui panel "resfile" "resource/screens/Count.res" } ... ...
Count.res
This file should be saved in "<your mod>/resource/screens/"
I simply took another screens res file and changed it up a bit; but you can use the in game vgui editor and cut the excess components (i.e the title bar, etc...), save it, and then plug it in to your screen.
"screen_basic.res" { "Background" { "ControlName" "MaterialImage" "fieldName" "Background" "xpos" "0" "ypos" "0" "zpos" "-2" "wide" "480" "tall" "240" "material" "vgui/screens/vgui_bg" } "lblCount" { "ControlName" "Label" "fieldName" "lblCount" "xpos" "120" "ypos" "110" "wide" "240" "tall" "34" "autoResize" "0" "pinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "labelText" "0" "textAlignment" "center" "dulltext" "0" "paintBackground" "0" } }
Creating the panel in Hammer
Finally, open Hammer, build yourself a simple map and place a vgui_screen entity. Set the "Panel Name" property to TestScreen, and you should have a working counter (with an annoying background image loaded in to your map. Beware that the opposite side to your screen does not render - so be sure to circle the entity before you figure that what you've done hasn't worked. | https://developer.valvesoftware.com/w/index.php?title=VGUI_Creating_A_Custom_Screen&oldid=166761 | CC-MAIN-2020-24 | refinedweb | 880 | 63.29 |
You are right; the replacement index I called 'j' is better buried as a C index or pointer within a slice replacement. In fact, a generator expression, if one has a keep expression, or a filter call, if one has filter function, work, without the intermediate list. Both also incorporate the keep scan index/pointer in C. I verified that this works by defining 3 functions.
def fc(n, keep):
mylist = list(range(n))
mylist[:] = [x for x in mylist if keep(x)]
return mylist
def fg(n, keep):
mylist = list(range(n))
mylist[:] = (x for x in mylist if keep(x))
return mylist
def fl(n, keep):
mylist = list(range(n))
mylist[:] = filter(keep, mylist)
return mylist
I added a second test expression.
print(fc(i, keep) == fg(i, keep) == fl(i, keep) == expect)
at the 3 obvious places in the test loop above.
---
In the existing question about removing duplicates, the existing all-hashable answer
mylist = list(set(mylist))
could be replaced by
mylist[:] = set(mylist) | https://bugs.python.org/msg377471 | CC-MAIN-2021-25 | refinedweb | 168 | 58.62 |
wraithdu 71 Posted July 1, 2010 (edited) Here is the rewritten version of this UDF. See my comments HERE. Please test the shit out of this thing. It was a major headache, and I want to make sure I didn't miss something. Thanks! Update 2013/05/28 - Fixed missing @error return in _Zip_ItemExists - Clarified a few @error return value meanings - Added an additional check and @error code to _Zip_DeleteItem - Clarified some of the header notes, esp regarding behavior on XPUpdate 2011/12/08 - Fixed recursion in ListAll functionUpdate 2011/12/07 - Fixed recursion error in CountAll function - updated objects to conform to new COM syntax (parenthesis req'd for methods)Update 2011/07/01 - Reverted change to AddItem function - **Adding an item directly to a sub folder on XP will FAILUpdate 2011/06/30 - Fixed traversing namespaces on Windows XP - Added note that overwrite fails on XPUpdate 2011/01/13 - Fixed bug adding items to a subfolder that doesn't exist yetUpdate 2010/08/27 - Fixed bug with trailing 'sUpdate 2010/07/16 - Better error reporting in _Zip_AddItem functionUpdate 2010/07/02 - Added credits. - Added trancexxx's suggestion to remove any left over temporary directories. - Replaced some StringTrim calls with cleaner StringRegExpReplace calls. - Moved a few repetitive lines of code into functions. - Moved a few repetitive lines of code into functions. - Moved a few repetitive lines of code into functions. =========================== _Zip.au3 Edited May 28, 2013 by wraithdu 4 Share this post Link to post Share on other sites | https://www.autoitscript.com/forum/topic/116565-zip-udf-zipfldrdll-library/ | CC-MAIN-2018-39 | refinedweb | 250 | 59.13 |
Yes:
The 2001 ANSI standard added the erfc function ( 1-erf(x) ), for float/double/long double.
Not 100% sure when that got built into most version of cmath and math.h. But by now almost every compiler should have it, and should have had it for nearly 8-9 years.
Certainly it is is gcc/g++.
Not the best example
#include <cmath> #include <iostream> int main() { for(int i=0;i<50;i++) { std::cout<<"x == "<<i*0.1<<" "<<-erfc(i*0.1)+1.0<<std::endl; } }
Please note : that erf has been added to a lot of cmath files, but I didn't know if that was in the standard
Edited 6 Years Ago by StuXYZ: n/a
Hi
I didn't found any error function when I was searching the compilers (gcc, visual c, watcom). Therefore, I took an approximation from Abramowitz/Stegun and wrote my own erf(x). It's approximation error is about 10^(-7). which was almost always sufficient for my apps. erf(x) = 1-erfc(x).
double erf(double x) { /* erf(z) = 2/sqrt(pi) * Integral(0..x) exp( -t^2) dt erf(0.01) = 0.0112834772 erf(3.7) = 0.9999998325 Abramowitz/Stegun: p299, |erf(z)-erf| <= 1.5*10^(-7) */ double y = 1.0 / ( 1.0 + 0.3275911 * x); return 1 - ((((( + 1.061405429 * y - 1.453152027) * y + 1.421413741) * y - 0.284496736) * y + 0.254829592) * y) * exp (-x * x); }
Maybe this small function is also useful for you.
--tesu
Edited 6 Years Ago by tesuji: n/a
Hi munur93,
I am glad that my little erf() saved your time.
Unfortunately, MS visual c++ and other poor compilers do not have any Gaussian erfxcz function implemented to date despite the C99 standard provides some error functions in math.h. (Then I cribbed from famous Irene Stegun's Handbook of Mathematical Functions, what sadly only contains an approximation of medium-range precision, possibly the old one from Goldstine.)
There are erf() and erfc() in gnu c and c++, header file is math.h, not cmath.h.
If you are interested in higher precision erf() (about 1e-14), you can send me a message. I have calculated some erf() with higher precision using rational functions in L1-approximation.
-- tesu
Edited 6 Years Ago by tesuji: | https://www.daniweb.com/programming/software-development/threads/294232/error-function-in-math-library | CC-MAIN-2016-50 | refinedweb | 381 | 68.16 |
function removed from LIS2HH12.py library module
I'm Marco Rainone, collaborator of the Wireless laboratory of the Institute of Theoretical Physics of Trieste.
In October I created a micropython program for a sensor project that uses the lopy with the pytrack board.
For the management of the accelerometer I used the LIS2HH12.py library module that I downloaded on September 29th.
Yesterday I made some changes to the software I had developed, and on the occasion from your site on github I downloaded the latest versions of pytrack library modules (including LIS2HH12.py) and updated the firmware on the lopy and on the pytrack.
I realized that my program crashed with an error generated by this situation:
comparing the version of the LIS2HH12.py module dated September 27th with the most recent version of February 20th, I verified that the yaw function (rotation calc)
was removed in the LIS2HH12 class
def yaw (self):
div = math.sqrt (math.pow (self.x [0], 2) + math.pow (self.z [0], 2))
if div == 0:
div = 0.01
return (180 / 3.14154) * math.atan (self.y [0] / div)
Why the jaw function has been removed from the latest versions of the LIS2HH12.py library module?
Can the version of LIS2HH12.py of September 27th (with the jaw function) still be used if the pytrack or pysense cards are updated with the latest firmware?
@mrainone said in function removed from LIS2HH12.py library module:
can you recommend a low cost magnetometer to connect to the lopy
I use simple GY-271 (HMC5883L)
It working fine for me and is cheap
In the past I have been successful in connecting a magnetometer () to a pytrack to get yaw measurements. I used this library: and connected the board to the the Pytrack via the external IO header (SDA='P8'=Pin 10 of the external header, 'SCL=P4'=Pin 9 of the external header).
thanks for the quick reply.
Fortunately, my application is limited to perform the yaw log, without further processing.
In case I had to update my sensor with lopy and pytrack to acquire a reliable value of the yaw parameter, I could process the data of the pytrack accelerometer together with those of a magnetometer connected externally to the lopy.
Is it a viable solution?
If the solution is correct, can you recommend a low cost magnetometer to connect to the lopy through the pytrack and where can I connect on the board by reducing the interface hw?
The reason the yaw function was removed is due to the fact that it is not possible to measure yaw with just an accelerometer. The accelerometer measures the force of gravity to determine orientation but when rotating the accelerometer in the yaw access, the force of gravity does not change because the direction of gravity is in the same axis as the yaw axis | https://forum.pycom.io/topic/2700/function-removed-from-lis2hh12-py-library-module/5 | CC-MAIN-2019-09 | refinedweb | 478 | 62.17 |
I am trying to use BlueJ to debug my java code for my homework. I am trying to pass arraylist to one of the methods and part of code (relevant) is posted under. Code compiles fine but when I try to create an object instance and input the string arraylist it is not working. I guess I need to know how to input data (parametric) into blueJ prompts when using an arraylist.
I wish I could attach the snapshots of the errors but this forum blocks them. I will try to attach them again anyway to see if that works somehow. I have tried to input in a few different ways but I always get one or the other error in BlueJ, sample of error messages as below:
BlueJ error:
a)
"Error: illegal initializer for java.util.ArrayList<java.lang.String>"
OR
b)
"Error: <identifier> Expected"
Code Snippet:
[highlight=java] import java.util.ArrayList; public class ArrayListMethods { ArrayList<String> list; //instance variable public ArrayListMethods(ArrayList<String> arrayList) { list = new ArrayList<String>(); } public boolean isSorted() { boolean sorted = false; for (int i = 0; i < list.size()-1; i++) { if (list.get(i).compareTo(list.get(i+1)) > 0) { sorted = true; } } return sorted; } } [/highlight] | http://www.javaprogrammingforums.com/whats-wrong-my-code/31781-bluej-question-error-illegal-initializer-java-util-arraylist-java-lang-string.html | CC-MAIN-2014-42 | refinedweb | 201 | 54.83 |
Databinding is a somewhat advanced topic, typically covered in the second or even the
final third of most Silverlight books. We’re going to tackle it in the next couple mini-tutorials because
- It isn’t difficult to understand
- It isn’t difficult to implement
- It is critical both to most applications and to the principal design pattern used with Windows Phone: MVVM
Create the Person class
To get started, create a new Windows Phone application in Visual Studio, and name it DataBinding. Right click on the project and select Add->New->Class and name the class Person.cs.
The class consists of an enumeration and a set of automatic properties,
public class Person { public enum Sex { Male, Female, } public string Name { get; set; } public bool Moustache { get; set; } public bool Goatee { get; set; } public bool Beard { get; set; } public Sex WhichSex { get; set; } public double Height { get; set; } public DateTime BirthDate { get; set; } public bool Favorite { get; set; } }
You can see pretty quickly how these properties will map to the various input controls shown in the illustration at the top. The booleans can be either CheckBoxes or RadioButtons (depending on whether they are mutually exclusive or not).
We are using a couple input controls you may not have seen yet, however. We’re using a DatePicker for the birth date and a slider (with a TextBlock) for the height. More on these in the next tutorial.
Before reading the next mini-tutorial you might want to try creating a first iteration of the UI yourself, based on what you already know, the illustration and the class definition.
I am finding these mini-tutorials just right for me (maybe this specific one was a bit short). I am fairly familiar with Silverlight and XAML and am just wanting to apply what I know to the WP7 framework.
@Bogdan
Bogdan and Dennis….
I have an on-going tutorial series (each entry is about 25 printed pages) on Windows Phone Programming. The request from the community was for another set of tutorials, from scratch, in bite-sized bites. Please bear with me for a few weeks and we’ll see if we can’t find a middle ground of something a bit longer but still in the mini-tutorial range.
Thanks for the feedback, it is very much appreciated.
I too feel that these mini-tutorials are too short. They get you super excited reading the title of the RSS feed but leave you hungry 2 minutes later.
Hi,
I’m developing an application and I use standard binding nothing fancy, but I’m facing a problem concerning how to handle validation.
I would be very happy if you can provide an example on how to handle/display an error when the user will enter “0.43$%6” for the Height in your example (if it is used in a TextBox.
Thank you
ArchieCoder
PS : I own the C# book from you, it is a really good book!!
Sorry for the negative feedback but this article is about nothing actually. When reading it I can’t stop thinking that it was intended just to be indexed within search engines with WP7 tag rather than provide any value for the community.
I would recommend posting the entire article instead of splitting it by passages. | http://jesseliberty.com/2010/11/09/windows-phone-from-scratch-5-data-binding/ | CC-MAIN-2021-10 | refinedweb | 551 | 58.42 |
I saw a sign at the gym yesterday that said, “Children are getting fatter every decade”. Below that sign stood a graph that basically showed that in five years the average English child will weigh as much as a tractor.
I found this claim slightly unbelievable, so I decided to investigate…
The Data
The data is taken from Data.gov.uk. We’ll be using the 2014 XLS file. Download it, and open it in your spreadsheet tool of choice.
Then navigate to sheet 7.2, as it contains the data we are looking for:
Now, before we jump into analyzing the data with Pandas, let’s take a step back and address the elephant in the room: If you can perform the analysis/plotting in Excel, why would you use Python?
Python vs Excel
Should I use Python or Excel?
This question is often asked by people just starting out in data analysis. While Python may be popular with the programming community, Excel is much more prevalent in the wider world. Most officer managers, sales people, marketers, etc. use Excel - and there’s nothing wrong with that. It’s a great tool if you know how to use it well, and it has turned many non-technical people into expert analysts.
The answer to whether you should use Python or Excel is not an easy one to answer. But in the end, there is no either/or: Instead, you can use them together.
Excel is great for viewing data, performing basic analysis, and drawing simple graphs, but it really isn’t suitable for cleaning up data (unless you are willing to dive into VBA). If you have a 500MB Excel file with missing data, dates in different formats, no headers, it will take you forever to clean it by hand. The same can be said if your data is spread across a dozen CSV files, which is fairly common.
Doing all that cleanup is trivial with Python and Pandas, a Python library for data analysis. Built on top of Numpy, Pandas makes high-level tasks easy, and you can write your results back to an Excel file, so you can continue to share the results of your analysis with non-programmers.
So while Excel isn’t going away, Python is a great tool if you want clean data and perform higher-level data analysis.
The Code
Right, let’s get started with the code - which you can grab from the project repo along with the spreadsheet I linked to above so you don’t have to download it again.
Start by creating a new script called obesity.py and import Pandas as well as matplotlib so that we can plot graphs later on:
import pandas as pd import matplotlib.pyplot as plt
Make sure you install both dependencies:
pip install pandas matplotlib
Next, let’s read in the Excel file:
data = pd.ExcelFile("Obes-phys-acti-diet-eng-2014-tab.xls")
And that’s it. In a single line we read in the entire Excel file.
Let’s print what we have:
print data.sheet_names
Run the script.
$ python obesity.py [u'Chapter 7', u'7.1', u'7.2', u'7.3', u'7.4', u'7.5', u'7.6', u'7.7', u'7.8', u'7.9', u'7.10']
Look familiar? These are the sheets we saw earlier. Remember, we will be focusing on sheet 7.2. Now if you look at 7.2 in Excel, you will see that the top 4 rows and bottom 14 rows contain useless info. Let me rephrase: It’s useful for humans, but not for our script. We only need rows 5-18.
Cleanup
So when we read the sheet, we need to make sure any unnecessary info is left out.
# Read 2nd section, by age data_age = data.parse(u'7.2', skiprows=4, skipfooter=14) print data_age
Run again.
Unnamed: 0 Total Under 16 16-24 25-34 35-44 45-54 55-64 65-74 \ 0 NaN NaN NaN NaN NaN NaN NaN NaN NaN 1 2002/03 1275 400 65 136 289 216 94 52 2 2003/04 1711 579 67 174 391 273 151 52 3 2004/05 2035 547 107 287 487 364 174 36 4 2005/06 2564 583 96 341 637 554 258 72 #...snip...#
We read the sheet, skipping the top 4 rows as well as the bottom 14 (as they contain data not useful to us). We then printed what we have. (For simplicity, I’m only showing the first few lines of the printout.)
The first line represents the column headers. Right off the bat you can see Pandas is quite smart since it picked up most of the headers correctly. Except for the first one, of course - e.g.,
Unnamed: 0. Why is that? Simple. Look at the file in Excel, and you see that it is missing a header for the year.
Another problem is that we have an empty line in the original file, and that is showing up as
NaN (Not a number).
So we now need to do two things:
- Rename the first header to
Year, and
- Get rid of any empty rows.
# Rename unamed to year data_age.rename(columns={u'Unnamed: 0': u'Year'}, inplace=True)
Here we told Pandas to rename the column Unnamed: 0 to Year. using the in-built function
rename().
inplace = Truemodifies the existing object. Without this, Pandas will create a new object and return that.
Next let’s drop the empty rows filled with
NaN:
# Drop empties data_age.dropna(inplace=True)
There is one more thing we need to do that will make our lives easier. If you look at the data_age table, the first value is a number. This is the index, and Pandas uses the default Excel practice of having a number as the index. However, we want to change the index to Year. This will make plotting much easier, since the index is usually plotted as the x axis.
data_age.set_index('Year', inplace=True)
We set the index to
Year.
Now print our cleaned up data:
print "After Clean up:" print data_age
And run:
Total Under 16 16-24 25-34 35-44 45-54 55-64 65-74 \ Year 2002/03 1275 400 65 136 289 216 94 52 2003/04 1711 579 67 174 391 273 151 52 2004/05 2035 547 107 287 487 364 174 36 2005/06 2564 583 96 341 637 554 258 72 #...snip...#
Much better. You can see the index is now the
Year, and all
NaNs are gone.
Charts
Now we can plot what we have.
# Plot data_age.plot() plt.show()
Oops. There is a problem: Our original data contains a total field that is overshadowing everything else. We need to get rid of it.
# Drop the total column and plot data_age_minus_total = data_age.drop('Total', axis=1)
axis =1 is slightly confusing, but all it really means is - drop the columns, as described from this Stack Overflow question.
Let’s plot what we have now.
data_age_minus_total.plot() plt.show()
Much better. We can actually see individual age groups now. Can you see which age group has the highest obesity?
Coming back to our original question: Are children getting fatter?
Let’s just plot a small section of the data: children under the age of 16 and grown ups in the age range of 35-44.
plt.close() # Plot children vs adults data_age['Under 16'].plot(label="Under 16") data_age['35-44'].plot(label="35-44") plt.legend(loc="upper right") plt.show()
So who is getting fatter?
Right. What do we see?
While children’s obesity has gone slightly down, their parents have ballooned. So it seems the parents need to worry about themselves rather than their children.
But what about the future?
The graph still doesn’t tell us what will happen to children’s obesity in the future. There are ways to extrapolate graphs like these into the future, but I must give a warning before we proceed: The obesity data has no underlying mathematical foundation. That is, we can’t find a formula that will predict how these values will change in the future. Everything is essentially guesswork. With this warning in mind, let’s see how we can try to extrapolate our graph.
First, Scipy does provide a function for extrapolation, but it only works for monotically increasing data (while our data goes up and down).
We can try curve fitting:
- Curve Fitting tries to fit a curve through points on a graph, by trying to generate a mathematical function for the data. The function may or may not be very accurate, depending on the data.
- Polynomial Interpolation Once you have an equation, you can use polynomial interpolation to try and interpolate any value on the graph.
We’ll use these two functions together to try and predict the future for England’s children:
kids_values = data_age['Under 16'].values x_axis = range(len(kids_values))
Here, we extract the values for children under 16. For the x axis, the original graph had dates. To simplify our graph, we’ll just be using the the numbers 0-10.
Output:
array([ 400., 579., 547., 583., 656., 747., 775., 632., 525., 495., 556.]) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
One more thing: Curve fitting uses different degrees of polynomials. In very simple terms,the higher the degree, the more accurate the curve fitting will be, but there is also the chance that the results will be garbage. Scipy will sometimes warn you if the degree is too high. Don’t worry, this will be more clear when we look at some examples.
poly_degree = 3 curve_fit = np.polyfit(x_axis, kids_values, poly_degree) poly_interp = np.poly1d(curve_fit)
We set the polynomial degree to 3. We then use the Numpy
polyfit() function to try to fit a graph through the data we have. The
poly1d() function is then called on the equation we generated to create a function that will be used to generate our values. This returns a function called
poly_interp that we will use below:
poly_fit_values = [] for i in range(len(x_axis)): poly_fit_values.append(poly_interp(i))
We loop from 0 to 10, and call the
poly_interp() function on each value. Remember, this is the function we generated when we ran the curve fitting algorithm.
Before moving on, let’s see what the different polynomial degrees mean.
We will plot both the original data, and our own data, to see how close our equation reached the ideal data:
plt.plot(x_axis, poly_fit_values, "-r", label = "Fitted") plt.plot(x_axis, kids_values, "-b", label = "Orig") plt.legend(loc="upper right")
The original data will be plotted in blue and labelled Orig, while the generated data will be red and labelled Fitted.
With a polynomial value of 3:
We see it isn’t that good a fit, so let’s try 5:
Much better. What about 7?
Now we get an almost perfect match. So, why wouldn’t we always use higher values?
Because the higher values have been so tightly coupled to this graph, they make prediction useless. If we try to extrapolate from the graph above, we get garbage values. Trying different values, I found that polynomial degrees of 3 and 4 were the only ones that give accurate results, so that’s what we’ll be using.
We are going to re-run our
poly_interp() function, this time for values from 0-15, to predict five years into the future.
x_axis2 = range(15) poly_fit_values = [] for i in range(len(x_axis2)): poly_fit_values.append(poly_interp(i))
This is the same code as before. Let’s again see the results with polynomial degrees of 3 and 4. The new extrapolated line is the green one and shows our prediction.
With 3:
Here, the obesity is going down. How about 4?
But here, it is shooting up, so kids will end up weighing like tractors!
Which of the two graphs is correct? It depends on whether you are working for the government or the opposition.
This is actually a feature, not bug. You must have heard these political debates where two sides draw the exact opposite conclusions from the same data? Now you see how it’s possible to draw radically different conclusions by tweaking small parameters.
And that is the reason we must be careful when accepting figures and graphs from lobbyists, especially if they are not willing to share the raw data. Sometimes, predictions are better left to astrologers.
Cheers! | https://realpython.com/analyzing-obesity-in-england-with-python/ | CC-MAIN-2021-17 | refinedweb | 2,094 | 74.19 |
\bin with this line:
mysqld --defaults-file=..\my.ini
Then create stop.bat in the same directory with that line:
mysqladmin -u root shutdown
Create admin.bat with this line:
mysql -h 127.0.0.1 -u root -p
In the C:\mysql directory, create a file named my.ini, and write:
[mysqld] # set basedir to your installation path basedir=C:\mysql # set datadir to the location of your data directory datadir=C:\mysql\data.
Using the Java MySQL driver!
Opening a connection to the database
Execute the file start.bat that you created earlier. Let the command window open to ensure MySQL is running. Create a class in your project and add the main method to it. You need to put a few instructions, i'll explain just after:
import java.sql.*;
public class SQLProject{ public static void main (String[] args){ try{ Class.forName("org.gjt.mm.mysql.Driver"); //Load the driver Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/data", "root", ""); //Connect } catch (Exception err){} } }.
How SQL syntax works
Every query (command sent to the server) has a syntax. SQL syntax is not the main purpose of this tutorial, however a few commands will be covered here. First of all, to create a database, the syntax is:
CREATE DATABASE `<database name>`;
This was the statement we used earlier to create our "data" database. Each database must have tables to store data. Each table can have its own fields, data types, values and so on. To create a table, the following will be used:
CREATE TABLE `<table name>`( `<column name>` <data type>([data modifier]) NOT NULL, `<another column name>` <data type>([data modifier]) NOT NULL, FULLTEXT(`<fulltext column name>`, `<another fulltext column>`));
To select some lines from a table, the following is used. However, the WHERE clause is optional if you wish to select the whole table:
SELECT `<column name>`, `<another field name>` FROM `<table name>` WHERE <conditions>;
To remove some lines from a table, we use this syntax, here again the WHERE clause is optional but be careful! Deleted data can't be brought back, so always use the WHERE clause:
DELETE FROM `<table name>` WHERE <conditions>;
If you really want to empty the table, you can use this shortcut (again, the lost data is lost forever so be careful):
TRUNCATE `<table name>`;
If we want to change a certain value in a table, we shall use:
UPDATE `<table name>` SET `<field>` = '<some value>' WHERE <conditions>;
Finally, to insert some data in a table, we'll use this code. Make sure the values are matching the data types:
INSERT INTO `<table name>` (`<field 1>`, `<field 2>`) VALUES ('<value 1>', '<value 2>');
Don't worry if it seems complicated for now, we'll practice them by giving examples of how it's done. Remember, SQL syntax is not case sensitive but it is recommended to use the same case as in the examples above. Let's create our first table.
Creating a table
In order to be able to store anything in our database, we need to have tables. We'll make a table that will look like that:
Table: people +------+-----------------------------+---------------------------+ | id | name | address | +------+-----------------------------+---------------------------+ | 1 | Bob | 123 Fake Street | | 2 | Roger | 666 Devil Street | | 3 | John | 325 Red Street | +------+-----------------------------+---------------------------+:`))"); } catch (Exception err){} } }
As you noticed, we sent this query to the database (the lines have been numbered):
1) CREATE TABLE `people` ( 2) `id` int(64) NOT NULL AUTO_INCREMENT, 3) `name` varchar(255) NOT NULL, 4) `address` varchar(255) NOT NULL, 5) UNIQUE (`id`), 6) FULLTEXT(`name`, `address`));.
Data types.
Inserting records in a table
Now, we're at the point where we are ready to insert our data in the table. We already know which data we want to insert (refer at the table drawn above). We will use the INSERT statement. Here's the full code to insert the rows:')"); } catch (Exception err){} } }.
Deleting a row in the table
Now, let's say we don't want John in the table. We have many ways to delete his row, here's the safest one:
conn.createStatement().execute("DELETE FROM `people` WHERE `id` = '3' LIMIT 1");!
The LIMIT clause.
Printing a table column's contents in the console
In this example, we'll "read" the table and print the results in the console:
ResultSet rs = conn.createStatement().executeQuery("SELECT `name` FROM `people` WHERE `id` < 4 ORDER BY `id`"); while (rs.next() == true){ System.out.println(rs.getString("name"); }:
Bob Roger
You can do anything you want with these results. I suggest you to explore the java.sql.ResultSet methods to find out how you can treat your results.
Security measures
Have you ever heard about SQL injections? Well when a SQL statement contains some input from the user, he might enter a part of SQL statement to screw up the table! You can prevent a lot of these by "escaping" a ' character by using the following:
String input = textfield.getText().replace("'", "\\'");
Now the "input" string is safe and can be added in a column. This is one thing that quite a lot of programmers forget to do.
Putting it all together
All right, we're near the end. To make sure you understood all, we're going to test the code. Start your server (remember: start.bat) then run the following code:')"); conn.createStatement().execute("DELETE FROM `people` WHERE `id` = '3' LIMIT 1"); //Delete John's row ResultSet rs = conn.createStatement().executeQuery("SELECT `name` FROM `people` WHERE `id` < 4 ORDER BY `id`"); //Select the rows while (rs.next() == true){ //Loop through results System.out.println(rs.getString("name")); //Print the result } rs.close(); //Close the result set conn.close(); //Close the connection } catch (Exception err){} } }
If everything is OK, the output will be:
Bob Roger! | http://www.dreamincode.net/forums/topic/32360-using-mysql-with-java/ | CC-MAIN-2017-13 | refinedweb | 955 | 64.41 |
Here is the assignmnent I need to complete:
"Write a program to calculate and print the result of the following two operations:
1/1 + 1/2 + 1/3 + 1/4 + 1/5 + ... + 1/99999999 + 1/100000000
and
1/100000000 + 1/99999999 + 1/99999998 + 1/99999997 + ... + 1/3 + 1/2 + 1/1
Results should be totaled and printed once using float variables for each calculation and once using double variables for each calculation. There should be a total of four answers printed. Make sure that the answers are adequately labeled. You may use any of the three loop mechanisms (while, do-while, or for)."
I've gotten the part of the program using the "double" variables to execute, but whenever I slip in the "float" variables part of the program, the window is blank when I try to run it. I know a float variable can only hold 7 digits, but I'm not sure how to resolve this. I appreciate any tips.
#include <iostream> using namespace std; void main () { float f; float fsum; double i; double Sum; for (f = 1, fsum = 0; f <= 100000000; f++) fsum = fsum + (1/f); cout << "The sum of all numbers 1/1 through 1/100000000 is " << fsum << endl; for (f = 100000000, fsum = 0; f >= 1; f--) fsum = fsum + (1/f); cout << "The sum of all numbers 1/100000000 through 1/1 is " << fsum << endl; for (i = 1, Sum = 0; i <= 100000000; i++) Sum = Sum + (1/i); cout << "The sum of all numbers 1/1 through 1/100000000 is " << Sum << endl; for (i = 100000000, Sum = 0; i >= 1; i--) Sum = Sum + (1/i); cout << "The sum of all numbers 1/100000000 through 1/1 is " << Sum << endl; | https://www.daniweb.com/programming/software-development/threads/382381/adding-a-sequence-of-numbers-using-a-for-loop | CC-MAIN-2021-17 | refinedweb | 281 | 71.28 |
z3c.recipe.tag 0.5
Generate ctags from eggs for development.
z3c.recipe.tag
Contents
Introduction
This recipe generates a TAGS database file that can be used with a number of different editors to quickly lookup class and function definitions in your package’s source files and egg dependencies.
Dependencies
Before running a tags enabled buildout, you must install the appropriate command line tag generation tools: exuberant-ctags and id-utils. In Ubuntu, you can install these with apt-get:
$ sudo apt-get install exuberant-ctags id-utils
On a Mac, download and install port from and then install ctags and idutils in this way:
$ sudo port install ctags idutils
How to use this recipe
With Buildout
Suppose you have an egg called MyApplication. To use this recipe with buildout, you would add the following to the buildout.cfg file:
[tags] recipe = z3c.recipe.tag:tags eggs = MyApplication
This produces a script file in the bin/ directory which you can then run like this:
$ ./bin/tags
By default, this script produces three files in the directory from which you ran the script:
- a ctags file called TAGS for use by emacs,
- a ctags file called tags for use by vi, and
- an idutils file called ID for use by either.
You can then use these file in your editor of choice.
Optionally, you can select which files to build. The following is the output of ./bin/tags --help:
usage: build_tags [options] options: -h, --help show this help message and exit -l LANGUAGES, --languages=LANGUAGES ctags comma-separated list of languages. defaults to ``-JavaScript`` -e, --ctags-emacs flag to build emacs ctags ``TAGS`` file -v, --ctags-vi flag to build vi ctags ``tags`` file -b, --ctags-bbedit flag to build bbedit ctags ``tags`` file -i, --idutils flag to build idutils ``ID`` file
If you’d like to set command line options by default (e.g. to limit building to ctags-vi by default) you can pass the default option in your buildout:
[tags] recipe = z3c.recipe.tag:tags eggs = MyApplication default = ['-v']
With Paver
If you are using Paver and already have z3c.recipe.tag installed, then all you have to do is add this line to your pavement.py file:
import z3c.recipe.tag
And then run the z3c.recipe.tag.tags task from the command line:
$ paver z3c.recipe.tag.tags
Additional Resources
For additional information on using tags tables with different editors see the following websites:
- Emacs:
- to jump to the location of a tag, type M-x find-tag and the name of the tag. Or use M-. to jump to the tag matching the token the cursor is currently on. The first time you do this, you will be prompted for the location of the TAGS file.
- VIM:
- BBEdit: Chapter 14, page 324
For more information on ctags, visit
(BBEdit is a Macintosh text editor.)
CHANGES
0.5 (2012-09-06)
- Exclude Python import statements by default from showing up as tags.
- Add ‘defaults’ option to allow adding default command line options (e.g. to set ‘-v’ by default)
0.4.1 (2012-01-11)
- Skip nonexistent sys.path directories to avoid ctags warnings.
0.4.0 (2010-08-29)
- Support new script features from zc.buildout 1.5 and higher. This version requires zc.buildout 1.5 or higher.
- Also index Mako and HTML files with id-utils.
0.3.0 (2009-08-16)
0.2.0 (2008-08-28)
- Allow command-line choices for what files to build, and what languages ctags should parse. (Note that the default behavior of running ./bin/tags is the same as previous releases.)
- Support the Mac OS X packaging system “macports” (exuberant ctags is ctags-exuberant in Ubuntu and ctags in macports).
- Support creating BBEdit-style ctags files.
- Small changes for development (use bootstrap external, set svn:ignore)
0.1.0 (2008-03-16)
- Initial release.
- buildout recipe for generating ctags of eggs used.
- Downloads (All Versions):
- 0 downloads in the last day
- 26 downloads in the last week
- 339 downloads in the last month
- Author: Paul Carduner
- License: ZPL 2.1
- Categories
- Development Status :: 5 - Production/Stable
- Framework :: Buildout
- Intended Audience :: Developers
- License :: OSI Approved :: Zope Public License
- Operating System :: OS Independent
- Programming Language :: Python
- Topic :: Software Development :: Build Tools
- Topic :: Text Editors :: Emacs
- Topic :: Utilities
- Package Index Owner: ctheune, mgedmin, gary, pcardune
- DOAP record: z3c.recipe.tag-0.5.xml | https://pypi.python.org/pypi/z3c.recipe.tag/0.5 | CC-MAIN-2016-18 | refinedweb | 734 | 65.32 |
Hello,
I am required to convert .ppt slides to jpeg except those slides that have audio or video embedded in it. Can anybody tell me how to do it?
Thanks
Hello,
I am required to convert .ppt slides to jpeg except those slides that have audio or video embedded in it. Can anybody tell me how to do it?
Thanks
Dear Appu_Achu,
If you want to check, if some slide has a VideoFrame or AudioFrame, you can do so by checking the type of shapes on a slide.
FYI : Videos are always linked not embedded. But audios can be linked or embedded. To check audio is embedded, check the AudioFrame.Embedded property returns true.
C#
//Check if any shape is audio or video frame
bool hasAudioVideo=false;
foreach(Shape shp in sld.Shapes)
{
if(shp is AudioFrame || shp is VideoFrame)
{
hasAudioVideo=true;
//break the loop
break;
}
}
VB.NET
'Check if any shape is audio or video frame
Dim hasAudioVideo As Boolean
For Each shp As Shape In sld.Shapes
If TypeOf shp Is AudioFrame Or TypeOf shp Is VideoFrame Then
hasAudioVideo = True
'Break the loop
Exit For
End If
Dear Faiz,
Thank you so much for the reply. It worked.
Thanks Again,Aparna
Hello,
I am using the serialize method as follows,
MemoryStream ms = new MemoryStream();
Background BG = slide.Background;
newBG.Serialize(ms);
I want to use this stream 'ms' in system.Drawing to draw a image.
Image image = Image.FromStream(ms, true, true);
but it gives a exception "Parameter is not valid.". Can you please tell me how to convert it to a valid stream.
Thanks..
If you want to get Background picture, you can get in this way.
Background BG = slide.Background;
Aspose.Slides.Picture pic = pres.Pictures.GetPictureById(BG.PictureId);
Image image = pic.Image;
Hi,
The above method you have mentioned works only when the background is of "Picture or Texture Fill", does not work for solid or gradient fill.
If possible, can you please let me know the stream returned when using Serialize method is of what type?
Thanks
It contains lot of other information like X, Y, width, height, alternative text etc.
<?xml:namespace prefix = o
If you want to get the image of slide background, then add an empty slide and then gets its thumbnail image via Presentation.GetThumbnail method and then delete the newly added slide via Presentation.Slides.Remove method.
Thanks a lot.
The requirement is that I want ot convert the slides to jpeg.but the quality is not very good when seen using large screens. So my idea is to write the text using system.drawing Graphics (using the anti-aliasing and the hinting property). So i thought I can serialize each and every items like background, shape etc and draw it using graphics.drawimage or some other way (not sure). But i guess it is not posssible now.
One more thing, I used the anti-alias property of font quality in aspose but there seems no difference in the font quality.
int fontIndex = por.FontIndex;
FontEntity fontEntity = textPres.Fonts[fontIndex];
fontEntity.Quality = FontQuality.ANTIALIASED_QUALITY;
I am doing the above thing for each and every slide and then saving the entire PPT. Then I am saving the slides as jpeg using GetThumbNail(). But there seems to be no difference. Is this the right way to do it.
Thanks
Dear Appu,
<?xml:namespace prefix = o
Are you getting blurry images? If so, please use Aspose.Slides 2.8.4.0 from this link.
In case, if you are still having problem, please attach your source ppt. Please also check thumbnail images taken from other ppts too.
Also, to get image with higher resolution, you need to give scaling factor to the Slide.GetThumbnail
For example, you can try
Slide.GetThumbnail(1.0, 1.0)
Or
Slide.GetThumbnail(2.0, 2.0)
Or
Slide.GetThumbnail(3.0, 3.0); // this will give you 2160 x 1620 image
Hi,
I am using the following piece of code for looping through the slides in a ppt.
IEnumerator slides = pres.Slides.GetEnumerator();
int j = 0;
while (slides.MoveNext()) {
j = j + 1;
Slide slide = (Slide)slides.Current;
image = slide.GetThumbnail(new Size(slideWidth, slideHeight));
image.Save("C:\\Slides\\Slide" + j + ".jpg",ImageFormat.Jpeg);
);
}
But sometimes what happens is that if there are say 16 slides, after converting to Jpeg there are 17 images. One of the slide is converted twice. But one of the them do not have all the contents of the slide and the other one does.
The same thing happens if I use foreach(Slide slide in slides) instead of while (slides.MoveNext()) {}
Please let me know what I can do regarding this.
Thanks
Dear Appu_Achu,
Presentation.Slides contains normal slides as well as master slides. So if you want to get the images of normal slides, you should use
Presentation.GetSlideByPosition and Presentation.Slides.LastSlidePosition
e.g
Presentation pres = new Presentation("c:\\source.ppt");
for (int i = 1; i <= pres.Slides.LastSlidePosition; i++)
{
Slide sld = pres.GetSlideByPosition(i);
System.Drawing.Image thumb = sld.GetThumbnail(1.0, 1.0);
thumb.Save("c:\\sld" + i + ".jpg");
}
Thank you so much. Now it works fine.
Hi,
I am using Aspose.Slides to process a ppt. I loop through all the slides and set the anti-aliasing property for the text and then writing the presentation again. But the bullets in the paragraph are not written properly. for example if i am using a diamond bullet it is converted to alphabet 'v'.. what do i do. kindly give me some suggestions.
foreach (Shape shape in textSlide.Shapes) {
if (shape is Aspose.Slides.Rectangle) {
if (shape.TextFrame != null) {
foreach (Paragraph para in shape.TextFrame.Paragraphs) {
if (para.Portions != null) {
foreach (Portion por in para.Portions) {
string text = por.Text;
int fontIndex = por.FontIndex;
FontEntity fontEntity = textPres.Fonts[fontIndex];
fontEntity.Quality = FontQuality.ANTIALIASED_QUALITY;
}
}
}
}
} else if (shape is Aspose.Slides.PictureFrame) {
PictureFrame pf = (PictureFrame)shape;
int b = pf.Brightness;
pf.Brightness = EAPConstants.BRIGHTNESS;
b = pf.Brightness;
}
}
}
tempPPTName = System.IO.Path.GetTempFileName();
textPres.Write(tempPPTName);
Please provide source presentation to check problem with bullets.
If I’m not mistaken the antialiasing property exists for fonts but actually do nothing in MS PowerPoint.
Also please always create new thread in the forum for new questions and requests.
I figured it out myself. Thanks. | https://forum.aspose.com/t/how-to-filter-out-slides-with-audio-video-files/102715 | CC-MAIN-2022-27 | refinedweb | 1,052 | 70.5 |
On Fri, 2003-10-03 at 07:23, Antonio Gallardo wrote:
> Carlos Chávez dijo:
> >
> > Hi to all,
> >
> > i'm try use the tag <wi:help> my template file is:
> >
> > <wt:form-template
> > <wt:widget-label
> > <wt:widget
> > <wi:help>Escriba el nombre del vendedor.</wi:help>
> > </wt:widget>
> > <br/><br/>
> > <input type="submit"/>
> > </wt:form-template>
> >
> > i'm use the stylesheet "woody-field-styling.xsl", but in the html
> > output put title="" in de "input" tag,
> >
> > what i'm doing wrong?
>
> Hi Carlos:
>
> You are not doing nothing wrong. The <wi:help> exists as part of the woody
> specification.
Huh? wi:help doesn't exist -- or at least not yet. It has been
discussed, but nothing concrete has come out of it yet.
> The idea behind the tag is to allow some help related to
> the widget. The samples does not render the tag, because the user decides
> to render it or not.
Yes and no.
yes, because indeed the contents of the wt:widget element in the
template will be copied into the wi:styling element after the
woodytransformer and can then be used in the XSL. BTW, this behaviour is
outdated and support for it will be dropped in the future. You now need
to explicitely use the wi:styling element in the template (the older way
is still supported for backwards compatibility, but that will be removed
once docs have been updated).
no, because inside wi:styling, you use whatever markup you want, but not
the wi namespace. The wi namespace is reserved for Woody itself,
inventing your own tags and putting them into that namespace is wrong.
Once wi:help will be implemented, it will be a sibling of wi:styling,
and it will also be definable inside the form definition, just as
wi:label.
In the meantime, you can use something like this inside wt:widget:
<wi:styling>
<help>abc</help>
</wi:styling>
and adjust the stylesheets to do something with the help tag.
-- | http://mail-archives.apache.org/mod_mbox/cocoon-users/200310.mbox/%3C1065183245.32767.226.camel@yum.ot%3E | CC-MAIN-2017-39 | refinedweb | 329 | 71.04 |
For many Internet of Things (IoT) projects a message queuing system like MQTT (Message Queue Telemetry Transport) is all that is needed to connect sensors, devices and graphic interfaces together. If however you require a database, with sorting, queuing and multi-media support then there are some great cloud storage platforms that are available. One that is definitely worth taking a look at is Google Firebase.
Like any IoT solution, Google Firebase can have inputs and sensors sending data directly into it, and a variety of client applications to view the data (Figure 1), but Google Firebase also offers other features such as: file storage, machine learning, messaging, and server side functions. In this article I will look at:
In this article I will look at:
- Setting up a sample Firebase IoT project
- Use Python to simulate I/O data
- Create a Web dashboard with Node-Red to view and write data
- Create an Android app using AppInventor to view and write data
- Look at a more complex data monitoring example in Python
Getting Started
Google Firebase [1] may not have the huge variety of options that Amazon Web Services (AWS) has, but I found as an IoT engineer Google Firebase had all the features that I needed to get up and running quickly, and I didn’t need a credit card for my free activation.
To begin log in with your Google account at, and select “Get Started”. I created a sample project called My-IoT. After the project is created Firebase will give it a unique identifier name, such as: my-iot-4ded7.
Firebase data can be stored in either a Realtime Database, or a Cloud Firestore. The Realtime Database is an unstructured NoSQL format that has been around for about 4 years, so there are lots of 3rd party components. The Cloud Firestore stores the data in structure collections and it’s fairly new so the 3rd party options are a little more limited.
For our test IoT project we will use the real-time database, and it can be created from the Database -> Data menu option.
The database structure can be built directly from the Firebase web console or imported from a JSON file. For this database 3 grouping are defined, one for Android, Node-Red and Raspberry Pi I/O values. The Firebase console allows for setting, changing and viewing the database values.
The security is configured in the Database -> Rules menu option. To keep things simple for testing read and write security is set to true for public access, (remember to change this for a production system).
The project’s remote access settings are shown in the Authentication section with the “Web setup” button.
Python and Firebase
There are a number of Python libraries to access Firebase. The pyrebase library has some added functionality such as: queries, sorting, file downloads and streaming support. The pyrebase library only support Python 3, and it is installed by:
sudo pip3 install pyrebase sudo pip3 install --upgrade google-auth-oauthlib
A Python 3 test program to set two values (pi/pi_value1 and pi/pi_value2) and read a single point and a group of point is shown below. Remember to change the configuration settings to match your project settings.
import pyrebase, random # define the Firebase as per your settings config = { "apiKey": "AIzaSyCq_WytLdmOy1AIzaSyCq_WytLdmOy1", "authDomain": "my-iot-4ded7.firebaseapp.com", "databaseURL": "", "storageBucket": "my-iot-4ded7.appspot.com" } firebase = pyrebase.initialize_app(config) db = firebase.database() # set 2 values with random numbers db.child("pi").child("pi_value1").set(random.randint(0,100)) db.child("pi").child("pi_value2").set(random.randint(0,100)) # readback a single value thevalue = db.child("pi").child("pi_value1").get().val() print ("Pi Value 1: ", thevalue) # get all android values all_users = db.child("android").get() for user in all_users.each(): print(user.key(), user.val())
The Firebase web console can be used to check the results from the test program.
Node-Red and Firebase
Node-Red is a visual programming environment that allows users to create applications by dragging and dropping nodes on the screen. Logic flows are then created by connecting the different nodes together.
Node-Red has been preinstalled on Raspbian Jesse since the November 2015. Node-Red can also be installed on Windows, Linux and OSX. To install and run Node-Red on your specific system see.
To install the Firebase components, select the Manage palette option from the right side of the menu bar. Then search for “firebase” and install node-red-contrib-firebase.
For our Node-Red example we will use web gauges to show the values of our two Python simulated test points. We will also send a text comment back to our Firebase database. The complete Node-Red logic for this is done in only 6 nodes!
To read the Pi values two firebase.on() nodes are used. The output from these nodes is connected to two dashboard gauge nodes. Double-clicking on firebase_on() node to configure Firebase database and the item to read from. Double-clicking on the gauge node allows you to edit gauge properties.
To send a text string to Firebase a text input node is wired to a firebase modify node. Edit the firebase modify node with the correct database address and value to set.
After the logic is complete, hit the Deploy button on the right side of the menu bar to run the logic. The Node-Red dashboard user interface is accessed by:, so for example 192.168.1.108:1880/ui.
AppInventor
AppInventor is a Web based Android app creation tool (), that uses a graphical programming environment.
AppInventor has two main screens. The Designer screen is used for the layout or presentation of the Android app and the Blocks screen is used to build the logic. On the right side of the top menu bar, the Designer and Blocks buttons allow you to toggle between these two screens.
On the Designer screen, an app layout is created by dragging a component from the Palette window onto the Viewer window.
We will use AppInventor to create an Android app that will read Pi values from our Firebase IoT database, and write a value back.
For the visuals on this application a Button, Label (2), ListView, Textbox and FirebaseDB component will be used. After a component is added to the application, the Components window is used to rename or delete that component. The Properties window is used to edit the features on a component. For the FirebaseDB component configure the Token and URL to match with your project settings.
Once the layout design is complete, logic can be added by clicking on the Blocks button on the top menu bar.
Logic is built by selecting an object in the Blocks window, and then click on the specific block that you would like to use.
AppInventor is pretty amazing when it comes to doing some very quick prototyping. Our entire app only uses two main blocks.
The when FirebaseDB1.DataChanged block is executed whenever new data arrives into the Firebase database. The DataChanged block returns a tag and a value variable. The tag variable is the top level item name, (“pi” or “nodered” for our example). The value will be a string of the items and their values, for example: “{pi_value2 = 34, pi_value1=77}”. We use a replace all text block to remove the “{” and “}” characters, then we pass the string to the ListView component. Note this same code will pass 2 or 200 tags in the pi tag section.
The when BT_PUT.click block will pass the text that we enter on the screen into the android/and_value1 item in our database.
After the screen layout and logic is complete, the menu item Build will compile the app. The app can be made available as an APK downloadable file or as a QR code link.
Below is picture of the final Android app synced with the Firebase data.
Python Data Monitoring Example
Our starting IoT Firebase realtime database was quite simple. Data monitoring or SCADA (Supervisory Control and Data Aquisition) projects usually require more information than a just a value. A more realistic sensor database would includes fields such as tag name, description, status, time and units.
By adding some indexing in the Firebase Security Rules it is possible to create some queries and sorts of the data. Some typical queries would be: “Points in alarm” or “Point values between 2:00 and 2:15”.
In the code listing below the syntax statement of .order_by_child(“status”).equal_to(“ALARM”).get() is used to show only records that have a status = ALARM. Some other filter options include: .start_at(time1).end_at(time2).get, .limit_to_first(n), and .order_by_value().
A good next step would be to pass important filtered information to Google Firebase’s messaging feature.
import pyrebase, random # define the Firebase as per your settings config = { "apiKey": "AIzaSyCq_AIzaSyCq_Wyt", "authDomain": "my-iot-7ded7.firebaseapp.com", "databaseURL": "", "storageBucket": "my-iot-7ded7.appspot.com" } firebase = pyrebase.initialize_app(config) db = firebase.database() tag_sum = db.child("pi").order_by_child("status").equal_to("ALARM").get() # print alarm points for tag in tag_sum.each(): info = tag.val() print (tag.key()," - ", info["description"],":", info["value"],info["units"], info["status"])
For more Python examples see the Pyrebase documentation.
Summary
Without a lot of configuration it is possible to configure a Google Firebase project and have Python, Node-Red and Android app read and write values. The level of programming complexity is on par with an MQTT implementation, however Google Firebase can offer a lot more future functionality that you wouldn’t have with MQTT, such as file storage, machine learning, messaging, and server side functions.
At the time of writing this article I found the Arduino Firebase library to be unreliable but Google offers some options like an MQTT bridge.
5 thoughts on “IoT with Google Firebase”
Hey great article! How did you authenticate firebase account in node-red? Was it JSON and from where the secret key was obtained?
In Node-Red when you add a Firebase node, click the ‘pencil’ button when you define the Firebase database. This will open a dialog to define your Firebase connect. From there you enter the connection details just like you would in Python. If you’re having any issues let me know and I could email some screenshots.
Thank you, It worked!
Hey, have you worked with firebase cloud messaging in node-red? Any good tutorials?
Hi, I’ve only used Python for Cloud messaging. But using Node-Red would be very useful. | https://funprojects.blog/2018/10/09/iot-with-google-firebase/comment-page-1/ | CC-MAIN-2020-10 | refinedweb | 1,749 | 64.81 |
This site uses strictly necessary cookies. More Information
I know this means public versus private in most cases however, I do not see the issue here. This is a script to determine the appropriate "Classification" depending on the time and connections made. There are 4 possible ranks. From high to low, Legendary, Epic, Excellent, and Good. Each of these have a "goal" time and connections made. For example, to achieve Legendary. You need to make 10 connections, in under 12 seconds. And to achieve Epic, you must make 8 connections in 15 seconds. However, if you make 10 connections, in 13 seconds.. that is no longer qualified for Legendary since it took you too long. So you will drop down a class, to Epic. The goal is to get the most connections in the least amount of time. If the connections made and time qualify lower than Excellent, it will give you Good by default. Here is the script that I have, It seems to be working but I can't test it until I fix this error. LevelExit.CombinedScore.scoreName' is inaccessible due to its protection level.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LevelExit : MonoBehaviour
{
public float padding;
public GUIStyle myStyle;
public string classification = "";
public int connections = 0;
public float time = 0.0f;
void Awake()
{
GameObject levelIntro = GameObject.Find("Level Introduction");
LevelIntroduction levelIntroScript = levelIntro.GetComponent<LevelIntroduction>();
int curConnections = GameLogic.getTotalConnections();
float curTime = GameLogic.getTotalTime();
CombinedScore playerScore = new CombinedScore("Player", curConnections, curTime);
/// Here we initialize all the score values.
CombinedScore legendaryScore = new CombinedScore("Legendary",
levelIntroScript.LegendConnect,
levelIntroScript.LegendTime);
CombinedScore epicScore = new CombinedScore("Epic",
levelIntroScript.EpicConnect,
levelIntroScript.EpicTime);
CombinedScore excellentScore = new CombinedScore("Excellent",
levelIntroScript.ExcellentConnect,
levelIntroScript.ExcellentTime);
CombinedScore goodScore = new CombinedScore("Good",
levelIntroScript.GoodConnect,
levelIntroScript.GoodTime);
/// Now put them all in a list, in order
List<CombinedScore> referenceScoresFromHighToLow = new List<CombinedScore>() { legendaryScore, epicScore, excellentScore, goodScore };
/// Then pass in the player's score along with the list, so it can compare them
classification = GetScoreClassification(playerScore, referenceScoresFromHighToLow);
}
public struct CombinedScore
{
int connections;
float time;
string scoreName;
public CombinedScore(string name, int conns, float t)
{
scoreName = name;
connections = conns;
time = t;
}
}
string GetScoreClassification(CombinedScore playerScore, List<CombinedScore> referenceScoresFromHighToLow)
{
foreach (CombinedScore score in referenceScoresFromHighToLow)
{
if (isBetterScore(playerScore, score))
{
/// If it is a better score it returns the value, breaking out of the loop early.
return score.scoreName;
}
}
/// The value if it doesn't beat any of the reference scores
return "Terrible";
}
bool isBetterScore(CombinedScore playerScore, CombinedScore referenceScore)
{
if (playerScore.connections >= referenceScore.connections && playerScore.time <= referenceScore.time)
{
return true;
}
return false;
}
void OnGUI()
{
//Get the number of the current level. Since the range from 0, 1, 2+
//Add 1.
int level = Application.loadedLevel + 1;
GUI.Label(new Rect((Screen.width / 2) - (125 / 2), (Screen.height / 2) - (125 / 2) + padding + 25, 125, 25), "Level " + level.ToString(), myStyle);
///If you want to update this in real time, you can call GetScoreClassification right here!
GUI.Label(new Rect((Screen.width / 2) - (125 / 2), (Screen.height / 2) - (125 / 2) + padding, 125, 25), "Classification: " + classification, myStyle);
GUI.Label(new Rect((Screen.width / 2) - (125 / 2), (Screen.height / 2) - (125 / 2) + padding - 25, 125, 25), "Connections: " + GameLogic.getTotalConnections(), myStyle);
GUI.Label(new Rect((Screen.width / 2) - (125 / 2), (Screen.height / 2) - (125 / 2) + padding - 50, 125, 25), "Time: " + (int)GameLogic.getTotalTime(), myStyle);
}
}
Answer by Bunny83
·
Nov 08, 2014 at 06:27 AM
Well, your 3 variables in your "CombinedScore" struct are all private ... The default visibility in C# is private. If you want them to be accessible from outside the struct, make them public.
Answer by Kiwasi
·
Nov 08, 2014 at 06:28 AM
You have declared scoreName as private. (C# defaults to private if you don't specify an access modifier).
CombinedScore is a struct that is separate object from LevelExit. Hence LevelExit cannot access private variables of CombinedScore. Neither can CombinedScore access private variables of LevelExit.
Fix by declaring scoreName as public.
Almost ;) It's true that the outer class has no access to private variables of the inner class, but the inner class has access to private variables of the outer class since the innerclass is part of the scope of the outer class. A simple example:
public class OuterClass
{
private string var1 = "$$anonymous$$y private string";
public void Print()
{
Debug.Log(var1);
}
public class InnerClass
{
public void Change(OuterClass t1)
{
t1.var1 = "Not anymore";
}
}
}
var outer = new OuterClass();
var inner = new OuterClass.InnerClass();
outer.Print(); // "$$anonymous$$y private string"
inner.Change(outer);
outer.Print(); // "Not anymore"
This does compile and works without any errors or warnings.
Yeah thanks its working.. but not actually working. $$anonymous$$y script is fixed since I made the variables public. However no clue why it is always saying i did terrible. I get to the end and it says i have 6 connections in 4 seconds, which I have on the level introduction set exactly and its saying terrible still.. wth...
@Josh$$anonymous$$Beyer: Well, we don't know the values you use since they seem to be defined in another script. You do your calculations in Awake. Are you sure that you don't "create" this script too early? Awake and Start are only called once in the lifetime of the script. You might want to store the time and connections in a local variable and display those in the
Getting the error "is inaccessible due to it's protection level" when I have the function set to public.
1
Answer
Distribute terrain in zones
3
Answers
Why do I get the alembic plugin error
1
Answer
I am getting a error CS0246:
1
Answer
EnterpriseSocial Q&A | https://answers.unity.com/questions/826635/cant-access-variable-due-to-its-protection-level.html | CC-MAIN-2021-31 | refinedweb | 931 | 50.84 |
Question: The following information applies to Questions 1a and 1b The
The following information applies to Questions 1a and 1b. The general equation for the weight of the first security to achieve minimum variance (in a two-stock portfolio) is given by
.png)
a. Show that w1 = 0.5 when σ1 = σ2.
b. What is the weight of Security 1 that gives minimum portfolio variance when r1,2 = 0.5, σ1 = 0.04, and σ2 =0.06?
.png)
a. Show that w1 = 0.5 when σ1 = σ2.
b. What is the weight of Security 1 that gives minimum portfolio variance when r1,2 = 0.5, σ1 = 0.04, and σ2 =0.06?
Answer to relevant QuestionsGiven two assets with the following characteristics:E(R1) = 0:12 σ1 = 0:04E(R2) = 0:16 σ2 = 0:06Assume that r1,2 = −1.00. What is the weight that would yield a zero variance for the portfolio?While the capital asset pricing model (CAPM) has been widely used to analyze securities and manage portfolios for the past 50 years, it has also been widely criticized as providing too simple a view of risk. Describe three ...a. You expect an RFR of 10 percent and the market return (RM) of 14 percent. Compute the expected return for the following stocks, and plot them on an SML graph.b. You ask a stockbroker what the firm’s research department ...Draw the security market line for each of the following conditions:a. (1) RFR = 0.08; RM(proxy) = 0.12(2) Rz = 0.06; RM(true) = 0.15b. Rader Tire has the following results for the last six periods. Calculate and compare the ...Consider the following questions related to empirical tests of the APT:a. Briefly discuss one study that does not support the APT. Briefly discuss a study that does support the APT. Which position seems more plausible?b. ...
Post your question | http://www.solutioninn.com/the-following-information-applies-to-questions-1a-and-1b-the | CC-MAIN-2017-17 | refinedweb | 316 | 70.39 |
Parse::Eyapp::debuggingtut - Solving ambiguities and fixing lexical, syntactic and semantic errors
The sources of error when programming with
eyapp are many and various.
Some of them are minor,
as having a nonterminal without production rules or a terminal that is never produced by the lexical analyzer.
These kind of errors can be caught with the help of the
%strict directive.
In the following sections we will discuss three main kind of errors that correspond to three development stages:
Conflicts with the grammar: the grammar is ambiguous or is not clear - perhaps due to the fact that
eyapp uses only a lookahead symbol - which sort of tree must be built for some inputs
There are no conflicts but the parser does not build the syntax tree as expected. May be it rejects correct sentences or accepts incorrect ones. Or may be it accepts correct ones but the syntax tree has not the shape we want (i.e. we have a precedence problem).
We have solved the conflicts and trees are satisfactory but we have errors inside the semantic actions.
Each time you discover an error write a test that covers that error. Section "TREE EQUALITY" deals with the problem of checking if the generated abstract syntax tree has the correct shape and attributes.
As Andreas Zeller points out in his article "Beautiful Debugging" finding the causes of a failing program must follow the scientific method:
eyapp
-voption,
yydebug, the Perl debugger, etc. to build the hypothesis). If you use continuous testing it is likely related with the recently written code.
eyapp
-voption,
yydebug, the Perl debugger, etc.) see if your predictions hold. Reject your hypothesis if they don't hold.
.
Token and production priorities are used to solve conflicts. Recall the main points of yacc-like parsers related to priorities:
%left %right %nonassoc
can be used in the head section to declare the priority of a token
.
The program
Precedencia.eyp illustrates the way priorities work in
eyapp:
pl@europa:~/LEyapp/examples/debuggingtut$ eyapp -c Precedencia.eyp %token NUM %left '@' %right '&' dummy %tree %% list: | list '\n' | list e ; e: %name NUM NUM | %name AMPERSAND e '&' e | %name AT e '@' e %prec dummy ; %%
See an execution:
pl@europa:~/LEyapp/examples/debuggingtut$ ./Precedencia.pm Expressions. Press CTRL-D (Unix) or CTRL-Z (Windows) to finish: 2@3@4 2@3&4 2&3@4 2&3&4 <CTRL-D> AT(AT(NUM(TERMINAL[2]),NUM(TERMINAL[3])),NUM(TERMINAL[4])) AT(NUM(TERMINAL[2]),AMPERSAND(NUM(TERMINAL[3]),NUM(TERMINAL[4]))) AT(AMPERSAND(NUM(TERMINAL[2]),NUM(TERMINAL[3])),NUM(TERMINAL[4])) AMPERSAND(NUM(TERMINAL[2]),AMPERSAND(NUM(TERMINAL[3]),NUM(TERMINAL[4])))
See if you are able to understand the output:
2@3@4: The phrase is interpreted as
(2@3)@4since the rule
e '@' ehas the precedence of the token
dummywhich is stronger that then priority of token
@. The conflict is solved in favor of the reduction
2@3&4: The rule
e '@' ehas the precedence of
dummywhich is the same than the token
&. The associativity decides. Since they were declared
%rightthe conflict is solved in favor of the shift. The phrase is interpreted as
2@(3&4)
2&3@4: The rule
e '&' ehas more precedence than the token
@. The phrase is interpreted as
(2&3)@4
2&3&4: Both the rule and the token have the same precedence. Since they were declared
%right, the conflict is solved in favor of the shift. The phrase is interpreted as
2&(3&4)
eyappProgram with Errors
The following simplified
eyapp program has some errors. The generated language is made of lists of declarations (
D stands for declaration) followed by lists of sentences (
S stands for statement) separated by semicolons:
pl@nereida:~/LEyapp/examples/debuggingtut$ cat -n Debug.eyp 1 %{ 2 =head1 SYNOPSIS 3 4 This grammar has an unsolved shift-reduce conflict. 5 6 Be sure C<DebugTail.pm> is reachable. 7 Compile it with 8 9 eyapp -b '' Debug.eyp 10 11 See the C<Debug.output> file generated. 12 Execute the generated modulino with: 13 14 ./Debug.pm -d # to activate debugging 15 ./Debug.pm -h # for help 16 17 The generated parser will not recognize any input, since its shifts forever. 18 Try input C<'D; D; S'>. 19 20 =head1 See also 21 22 23 24 Debug1.eyp Debug2.eyp DebugLookForward.eyp DebugDynamicResolution.eyp 25 26 =cut 27 28 our $VERSION = '0.01'; 29 use base q{DebugTail}; 30 31 %} 32 33 %token D S 34 35 %% 36 p: 37 ds ';' ss 38 | ss 39 ; 40 41 ds: 42 D ';' ds 43 | D /* this production is never used */ 44 ; 45 46 ss: 47 S ';' ss 48 | S 49 ; 50 51 %% 52 53 __PACKAGE__->main('Provide a statement like "D; D; S" and press <CR><CTRL-D>: ') unless caller;
Sometimes the presence of actions, attribute names and support code makes more difficult the readability of the grammar. You can use the
-c option of eyapp, to see only the syntactic parts:
$ eyapp -c examples/debuggingtut/Debug.eyp %token D S %% p: ds ';' ss | ss ; ds: D ';' ds | D ; ss: S ';' ss | S ; $
It is clear now that the language generated by this grammar is made of non empty sequences of
D followed by non empty sequences of <S> separated by semicolons.
When compiling this grammar,
eyapp produces a warning message announcing the existence of a conflict:
pl@nereida:~/LEyapp/examples$ eyapp Debug.eyp 1 shift/reduce conflict (see .output file) State 4: shifts: to state 8 with ';'
.outputfile
The existence of warnings triggers the creation of a file
Debug.output containing information about the grammar and the syntax analyzer.
Let us see the contents of the
Debug.output file:
pl@nereida:~/LEyapp/examples$ cat -n Debug.output 1 Warnings: 2 --------- 3 1 shift/reduce conflict (see .output file) 4 State 4: shifts: 5 to state 8 with ';' 6 7 Conflicts: 8 ---------- 9 State 4 contains 1 shift/reduce conflict 10 11 Rules: 12 ------ 13 0: $start -> p $end 14 1: p -> ds ';' ss 15 2: p -> ss 16 3: ds -> D ';' ds 17 4: ds -> D 18 5: ss -> S ';' ss 19 6: ss -> S 20 21 States: 22 ------- 23 State 0: 24 25 $start -> . p $end (Rule 0) 26 27 D shift, and go to state 4 28 S shift, and go to state 1 29 30 p go to state 2 31 ss go to state 3 32 ds go to state 5 33 .. ......................................... 55 State 4: 56 57 ds -> D . ';' ds (Rule 3) 58 ds -> D . (Rule 4) 59 60 ';' shift, and go to state 8 61 62 ';' [reduce using rule 4 (ds)] 63 .. ......................................... 84 State 8: 85 86 ds -> D ';' . ds (Rule 3) 87 88 D shift, and go to state 4 89 90 ds go to state 11 91 .. ......................................... 112 State 12: 113 114 p -> ds ';' ss . (Rule 1) 115 116 $default reduce using rule 1 (p) 117 118 119 Summary: 120 -------- 121 Number of rules : 7 122 Number of terminals : 4 123 Number of non-terminals : 4 124 Number of states : 13
The parser generated by
Parse::Eyapp is based on a deterministic finite automaton. Each state of the automaton remembers what production rules are candidates to apply and what have been seen from the right hand side of the production rule. The problem, according to the warning, occurs in state 4. State 4 contains:
55 State 4: 56 57 ds -> D . ';' ds (Rule 3) 58 ds -> D . (Rule 4) 59 60 ';' shift, and go to state 8 61 62 ';' [reduce using rule 4 (ds)] 63
An state is a set of production rules with a marker (the dot in rules 3 and 4) somewhere in its right hand side. If the parser is in state 4 is because the production rules
ds -> D ';' ds and
ds -> D are potential candidates to build the syntax tree. That they will win or not depends on what will happen next when more input is processed.
The dot that appears on the right hand side means position in our guessing. The fact that
ds -> D .';' ds is in state 4 means that if the parser is in state 4 we have already seen
D and we expect to see a semicolon followed by
ds (or something derivable from
ds). If such thing happens this production will be the right one (will be the handle in the jargon). The comment
60 ';' shift, and go to state 8
means that if the next token is a semicolon the next state will be state 8:
84 State 8: 85 86 ds -> D ';' . ds (Rule 3) 87 88 D shift, and go to state 4 89 90 ds go to state 11
As we see state 8 has the item
ds -> D ';' . ds which means that we have already seen a
D and a semicolon.
The fact that
ds -> D . is in state 4 means that we have already seen
D and since the dot is at the end of the rule, this production can be the right one, even if a semicolon is just waiting in the input. An example that it will be correct to "reduce" by the rule
ds -> D . in the presence of a semicolon is given by the input
D ; S. A rightmost derivation for such input is:
p => ds ; ss => ds ; S => D ; S
that is processed by the LALR(1) algorithm following this sequence of actions:
+----------+---------+---------+ | rule | read | input | | | | D ; S $ | | | D | ; S $ | | ds->d | ds | ; S $ | | | ds ; | S $ | | | ds ; S | $ | | ss->s | ds ; ss | $ | | p->ds;ss | p | | +----------+---------+---------+
Since it is correct to reduce in some cases by the production
ds -> D . and others in which is correct to shift the semicolon,
eyapp complains about a shift/reduce conflict with
';'. State 4 has two rules that compete to be the right one:
pl@nereida:~/LEyapp/examples$ eyapp Debug.eyp 1 shift/reduce conflict (see .output file)
We can guess that the right item (the rules with the dot, i.e. the states of the automaton are called LALR(0) items in the yacc jargon) is
ds -> D .';' ds and shift to state 8 consuming the semicolon, expecting to see something derivable from
ds later or guess that
ds -> D . is the right LR(0) item and reduce for such rule. This is the meaning of the comments in state 4:
60 ';' shift, and go to state 8 61 62 ';' [reduce using rule 4 (ds)]
To illustrate the problem let us consider the phrases
D;S and
D;D;S.
For both phrases, after consuming the
D the parser will go to state 4 and the current token will be the semicolon.
For the first phrase
D;S the correct decision is to use rule 4
ds -> D (to reduce in the jargon). For the second phrase
D;D;S the correct decision is to follow rule 3
ds -> D . ';' ds.
The parser generated by
eyapp would be able to know which rule is correct for each case if it were allowed to look at the token after the semicolon: if it is a
S is rule 4, if it is a
D is rule 3. But the parsers generated by
Eyapp do not lookahead more than the next token (this is what the "1" means when we say that
Parse::Eyapp parsers are LALR(1)) and therefore is not in condition to decide which production rule applies.
Unfortunately this is the sort of conflict that can't be solved by assigning priorities to the productions and tokens as it was done for the calculator example in Parse::Eyapp::eyappintro. If we run the analyzer it will refuse to accept correct entries like
D;D;S:
pl@europa:~/LEyapp/examples/debuggingtut$ eyapp -b '' -o debug.pl Debug.eyp 1 shift/reduce conflict (see .output file) State 4: shifts: to state 8 with ';' pl@europa:~/LEyapp/examples/debuggingtut$ ./debug.pl D;D;S ---------------------------------------- In state 0: Stack:[0] Need token. Got >D< Shift and go to state 4. ---------------------------------------- In state 4: Stack:[0,4] Need token. Got >;< Shift and go to state 8. ---------------------------------------- In state 8: Stack:[0,4,8] Need token. Got >D< Shift and go to state 4. ---------------------------------------- In state 4: Stack:[0,4,8,4] Need token. Got >;< Shift and go to state 8. ---------------------------------------- In state 8: Stack:[0,4,8,4,8] Need token. Got >S< Syntax error near input: 'S' line num 1
The default parsing action is to shift the token
; giving priority to the production
ds -> D . ';' ds
over the production
ds -> D .
Since no
ds production starts with
S, the presence of
S is (erroneously) interpreted as an error.
You may wonder why the productions
ss: S ';' ss | S ;
do not also produce a shift-reduce conflict with the semicolon. This is because the reduction by
ss -> S always corresponds to the last
S in a derivation:
ss => S ; ss => S ; S ; ss => S ; S; S
and thus, the reduction by
ss -> S only occurs in the presence of the
end of input token and never with the semicolon. The FOLLOW set of a syntactic variable is the set of tokens that may appear next to such variable in some derivation. While the semicolon
; is in the FOLLOW of
dd, it isn't in the FOLLOW of
ss.
To solve the former conflict the
Eyapp programmer has to reformulate the grammar modifying priorities and reorganizing the rules. Rewriting the recursive rule for
ds to be let recursive solves the conflict:
pl@nereida:~/LEyapp/examples/debuggingtut$ sed -ne '/^ds:/,/^;/p' Debug1.eyp | cat -n 1 ds: 2 %name D2 3 ds ';' D 4 | %name D1 5 D 6 ;
Now, for any phrase matching the pattern
D ; ... the action to build the tree is to reduce by
ds -> D.
The rightmost reverse derivation for
D;D;S is:
Derivation | Tree --------------------------------------+----------------------------- D;D;S <= ds;D;S <= ds;S <= ds;ss <= p | p(ds(ds(D),';',D),';',ss(S))
while the rightmost reverse derivation for
D;S is:
Derivation | Tree --------------------------------------+----------------------------- D;S <= ds;S <= ds;ss <= p | p(ds(D),';',ss(S))
When we recompile the modified grammar no warnings appear:
pl@nereida:~/LEyapp/examples$ eyapp Debug1.eyp pl@nereida:~/LEyapp/examples$
The problem here is that
Eyapp/Yapp/Yacc etc. produce LALR(1) parsers. They only look the next token. We can decide how to solve the conflict by rewriting the lexical analyzer to peer forward what token comes after the semicolon: it now returns
SEMICOLONS if it is an
S and
SEMICOLOND if it is an
D. Here is a solution based in this idea:
pl@nereida:~/LEyapp/examples/debuggingtut$ cat -n DebugLookForward.eyp 1 /*VIM: set ts=2 */ 2 %{ 3 =head1 SYNOPSIS 4 5 See 6 7 8 file DebugLookForward.eyp 9 10 This grammar fixes the conflicts an bugs in Debug.eyp and Debug1.eyp 11 12 Be sure C<DebugTail.pm> is reachable 13 compile it with 14 15 eyapp -b '' DebugLookForward.eyp 16 17 execute the generated modulino with: 18 19 ./DebugLookForward.pm -t 20 21 =head1 See also 22 23 Debug.eyp Debug1.eyp Debug2.eyp 24 25 =cut 26 27 our $VERSION = '0.01'; 28 use base q{DebugTail}; 29 30 %} 31 32 %token D S 33 %syntactic token SEMICOLONS SEMICOLOND 34 35 %tree 36 37 %% 38 p: 39 %name P 40 ds SEMICOLONS ss 41 | %name SS 42 ss 43 ; 44 45 ds: 46 %name D2 47 D SEMICOLOND ds 48 | %name D1 49 D 50 ; 51 52 ss: 53 %name S2 54 S SEMICOLONS ss 55 | %name S1 56 S 57 ; 58 59 %% 60 61 __PACKAGE__->lexer( 62 sub { 63 my $self = shift; 64 65 for (${$self->input()}) { 66 s{^(\s+)}{} and $self->tokenline($1 =~ tr{\n}{}); 67 return ('',undef) unless $_; 68 69 return ($1,$1) if s/^([sSDd])//; 70 return ('SEMICOLOND', 'SEMICOLOND') if s/^;\s*D/D/; 71 return ('SEMICOLONS', 'SEMICOLONS') if s/^;\s*S/S/; 72 die "Syntax error at line num ${$self->tokenline()}: ${substr($_,0,10)}\n"; 73 } 74 return ('',undef); 75 } 76 ); 77 78 __PACKAGE__->main unless caller();
Though
Debug1.pm seems to work:
pl@nereida:~/LEyapp/examples/debuggingtut$ ./Debug1.pm -t Try first "D;S" and then "D; D; S" (press <CR><CTRL-D> to finish): D;D;S P(D2(D1(TERMINAL[D]),TERMINAL[D]),S1(TERMINAL[S]))
There are occasions where we observe an abnormal behavior:
pl@nereida:~/LEyapp/examples/debuggingtut$ ./Debug1.pm -t Try first "D;S" and then "D; D; S" (press <CR><CTRL-D> to finish): D ; D ; S Syntax error near end of input line num 3. Expecting (;)
We can activate the option
yydebug => 0xF in the call to the parser method
YYParser. The integer parameter
yydebug of
new and
YYParse controls the level of debugging. Different levels of verbosity can be obtained by setting the bits of this argument. It works as follows:
/============================================================\ | Bit Value | Outputs | |------------+-----------------------------------------------| | 0x01 | Token reading (useful for Lexer debugging) | |------------+-----------------------------------------------| | 0x02 | States information | |------------+-----------------------------------------------| | 0x04 | Driver actions (shifts, reduces, accept...) | |------------+-----------------------------------------------| | 0x08 | Parse Stack dump | |------------+-----------------------------------------------| | 0x10 | Error Recovery tracing | \============================================================/
Let us see what happens when the input is
D;S. We have introduced some white spaces and carriage returns between the terminals:
pl@nereida:~/LEyapp/examples/debuggingtut$ ./Debug1.pm -d Try first "D;S" and then "D; D; S" (press <CR><CTRL-D> to finish): >< Syntax error near end of input line num 3. Expecting (;)
What's going on? After reading the carriage return
Need token. Got >D<
the parser receives an end of file. ¿Why?. Something is going wrong in the communications between lexical analyzer and parser. Let us review the lexical analyzer:
pl@nereida:~/LEyapp/examples/debuggingtut$ sed -ne '/lexer/,/^)/p' Debug1.eyp | cat -n 1 __PACKAGE__->lexer( 2 sub { 3 my $self = shift; 4 5 for (${$self->input()}) { # contextualize 6 s{^(\s)}{} and $self->tokenline($1 =~ tr{\n}{}); 7 8 return ('', undef) unless $_; 9 return ($1, $1) if s/^(.)//; 10 } 11 return ('', undef); 12 } 13 );
The error is at line 6. Only a single white space is eaten! The second carraige return in the input does not match lines 8 and 9 and the contextualizing
for finishes. Line 11 then unconditionally returns the
('',undef) signaling the end of input.
The grammar in file
Debug2.eyp fixes the problem: Now the analysis seems to work for this kind of input:
pl@nereida:~/LEyapp/examples/debuggingtut$ eyapp -b '' Debug2.eyp pl@nereida:~/LEyapp/examples/debuggingtut$ ./Debug2.pm -t -d Provide a statement like "D; D; S" and press <CR><CTRL-D>: >;< Shift and go to state 8. ---------------------------------------- In state 8: Stack:[0,5,8] Need token. Got >D< Shift and go to state 11. ---------------------------------------- In state 11: Stack:[0,5,8,11] Don't need token. Reduce using rule 3 (ds --> ds ; D): Back to state 0, then go to state 5. ---------------------------------------- In state 5: Stack:[0,5] Need token. Got >;< Shift and go to state 8. ---------------------------------------- In state 8: Stack:[0,5,8] Need token. Got >S< Shift and go to state 1. ---------------------------------------- In state 1: Stack:[0,5,8,1] Need token. Got >< Reduce using rule 6 (ss --> S): Back to state 8, then go to state 10. ---------------------------------------- In state 10: Stack:[0,5,8,10] Don't need token. Reduce using rule 1 (p --> ds ; ss): Back to state 0, then go to state 2. ---------------------------------------- In state 2: Stack:[0,2] Shift and go to state 7. ---------------------------------------- In state 7: Stack:[0,2,7] Don't need token. Accept. P(D2(D1(TERMINAL[D]),TERMINAL[D]),S1(TERMINAL[S]))
yydebug.
A third type of error occurs when the code inside a semantic action doesn't behave as expected.
The semantic actions are translated in anonymous methods of the parser object. Since they are anonymous we can't use breakpoints as
b subname # stop when arriving at sub ''name''
or
c subname # contine up to reach sub ''name''
Furthermore the file loaded by the client program is the generated
.pm. The code in the generated module
Debug.pm is alien to us - Was automatically generated by
Parse::Eyapp - and it can be difficult to find where our inserted semantic actions are.
To watch the execution of a semantic action is simple: We use the debugger
f file.eyp option to switch the viewing filename to our grammar file. The following session uses the example in the directory
examples/Calculator:
pl@nereida:~/LEyapp/examples/Calculator$ perl -wd scripts/calc.pl Loading DB routines from perl5db.pl version 1.3 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(scripts/calc.pl:8): Math::Calc->main(); DB<1> f lib/Math/Calc.eyp 1 2 3 4 5 6 7 #line 8 "lib/Math/Calc.eyp" 8 9: use base q{Math::Tail}; 10: my %s; # symbol table
Lines 37 to 41 contain the semantic action associated with the production
exp -> VAR (see file
examples/Calculator/lib/Math/Calc.eyp):
DB<2> l 37,41 37: my $id = $VAR->[0]; 38: my $val = $s{$id}; 39: $_[0]->semantic_error("Accesing undefined variable $id at line $VAR->[1].\n") 40 unless defined($val); 41: return $val;
now we set a break at line 37, to see what happens when a non initialized variable is used:
DB<3> b 37
We issue now the command
c (continue). The execution continues until line 37 of
lib/Math/Calc.eyp is reached:
DB<4> c Expressions. Press CTRL-D (Unix) or CTRL-Z (Windows) to finish: a = 2+b # user input Math::Calc::CODE(0x191da98)(lib/Math/Calc.eyp:37): 37: my $id = $VAR->[0];
Now we can issue any debugger commands (like
x,
p, etc.) to investigate the internal state of our program and determine what are the reasons of any abnormal behavior.
DB<4> n Math::Calc::CODE(0x191da98)(lib/Math/Calc.eyp:38): 38: my $val = $s{$id}; DB<4> x $id 0 'b' DB<5> x %s empty array
Most of the time reduce-reduce conflicts are due to some ambiguity in the grammar, as it is the case for this minimal example:
pl@nereida:~/LEyapp/examples/debuggingtut$ sed -ne '/%%/,/%%/p' minimalrr.eyp | cat -n 1 %% 2 s: 3 %name S_is_a 4 'a' 5 | A 6 ; 7 A: 8 %name A_is_a 9 'a' 10 ; 11 12 %%
In case of a reduce-reduce conflict, Parse::Eyapp reduces using the first production in the text:
pl@nereida:~/LEyapp/examples/debuggingtut$ eyapp -b '' minimalrr.eyp 1 reduce/reduce conflict pl@nereida:~/LEyapp/examples/debuggingtut$ ./minimalrr.pm -t Try "a" and press <CR><CTRL-D>: a S_is_a
If we change the order of the productions
pl@nereida:~/LEyapp/examples/debuggingtut$ sed -ne '/%start/,40p' minimalrr2.eyp | cat -n 1 %start s 2 3 %% 4 A: 5 %name A_is_a 6 'a' 7 ; 8 9 s: 10 %name S_is_a 11 'a' 12 | %name A 13 A 14 ; 15 %%
the selected production changes:
pl@nereida:~/LEyapp/examples/debuggingtut$ eyapp -b '' minimalrr2 1 reduce/reduce conflict pl@nereida:~/LEyapp/examples/debuggingtut$ ./minimalrr2.pm -t Try "a" and press <CR><CTRL-D>: a A(A_is_a)
In this example the programmer has attempted to define a language made of mixed lists
IDs and
NUMbers :
~/LEyapp/examples/debuggingtut$ eyapp -c typicalrr.eyp %token ID NUM %tree %% s: /* empty */ | s ws | s ns ; ns: /* empty */ | ns NUM ; ws: /* empty */ | ws ID ; %%
The grammar has several reduce-reduce conflicts:
~/LEyapp/examples/debuggingtut$ eyapp -b '' typicalrr.eyp 3 shift/reduce conflicts and 3 reduce/reduce conflicts
There are several sources of ambiguity in this grammar:
NUM NUM NUM
are ambiguous. The following two left-most derivations exists:
s =*=> ns ns =*=> NUM NUM ns => NUM NUM NUM and s =*=> ns ns =*=> NUM ns =*=> NUM NUM NUM
the same with phrases like
ID ID ID
s => empty
or
s => s ns => s empty => empty
etc.
The generated parser loops forever if feed with a list of identifiers:
~/LEyapp/examples/debuggingtut$ ./typicalrr.pm -d Try inputs "4 5", "a b" and "4 5 a b"(press <CR><CTRL-D> to finish): ab ---------------------------------------- In state 0: Stack:[0] Don't need token. Reduce using rule 1 (s --> /* empty */): Back to state 0, then go to state 1. ---------------------------------------- In state 1: Stack:[0,1] Need token. Got >ID< Reduce using rule 4 (ns --> /* empty */): Back to state 1, then go to state 2. ---------------------------------------- In state 2: Stack:[0,1,2] Reduce using rule 3 (s --> s ns): Back to state 0, then go to state 1. ---------------------------------------- In state 1: Stack:[0,1] Reduce using rule 4 (ns --> /* empty */): Back to state 1, then go to state 2. ---------------------------------------- In state 2: Stack:[0,1,2] Reduce using rule 3 (s --> s ns): Back to state 0, then go to state 1. ---------------------------------------- ^C
The problem is easily solved designing an equivalent non ambiguous grammar:
pl@europa:~/LEyapp/examples/debuggingtut$ cat -n correcttypicalrr.eyp 1 %token ID NUM 2 3 %% 4 s: 5 /* empty */ 6 | s ID 7 | s NUM 8 ; 9 10 %%
See also these files in the
examples/debuggintut/ directory:
typicalrr2.eypis equivalent to
typicalrr.eypbut has
%namedirectives, to have a nicer tree
typicalrr_fixed.eypeliminates the ambiguity using a combination of priorities and elimination of the redundant empty productions. Explicit precedence via
%precdirectives are given to produce right recursive lists
typicalrr_fixed_rightrecursive.eypis almost equal to
typicalrr_fixed.eypbut eliminates the of
%precdirectives by making the list production right recursive
We can also try to disambiguate the former example using priorities. For that we need to give an explicit priority to the end-of-input token. To refer to the end-of-input token in the header section, use the empty string
''. In the file
examples/debuggingtut/typicalrrwithprec.eyp there is a priority based solution:
~/LEyapp/examples/debuggingtut$ eyapp -c typicalrrwithprec.eyp %right LNUM %right NUM %right ID %right '' # The string '' refers to the 'End of Input' token %tree bypass %% s: %name EMPTY /* empty */%prec '' | %name LIST s ws | %name LIST s ns ; ns: %name EMPTYNUM /* empty */%prec NUM | %name NUMS NUM ns ; ws: %name EMPTYID /* empty */%prec LNUM | %name IDS ID ws ; %%
Observe the use of
%right '' in the header section: it gives a priority to the end-of-input token.
~/LEyapp/examples/debuggingtut$ ./typicalrrwithprec.pm -t Try "4 5 a b 2 3" (press <CR><CTRL-D> to finish): 4 5 a b 2 3 ^D LIST( LIST( LIST( EMPTY, NUMS( TERMINAL[4], NUMS( TERMINAL[5], EMPTYNUM ) ) ), IDS( TERMINAL[a], IDS( TERMINAL[b], EMPTYID ) ) ), NUMS( TERMINAL[2], NUMS( TERMINAL[3], EMPTYNUM ) ) )
The grammar in file
examples/debuggintut/pascalenumeratedvsrange.eyp:
~/LEyapp/examples/debuggingtut$ eyapp -c pascalenumeratedvsrange.eyp %token TYPE DOTDOT ID %left '+' '-' %left '*' '/' %% type_decl: TYPE ID '=' type ';' ; type: '(' id_list ')' | expr DOTDOT expr ; id_list: ID | id_list ',' ID ; expr: '(' expr ')' | expr '+' expr | expr '-' expr | expr '*' expr | expr '/' expr | ID ; %%
introduces a problem that arises in the declaration of enumerated and subrange types in Pascal:
type subrange = lo .. hi; type enum = (a, b, c);
The original language standard allows only numeric literals and constant identifiers for the subrange bounds (`lo' and `hi'), but Extended Pascal and many other Pascal implementations allow arbitrary expressions there. This gives rise to the following situation, containing a superfluous pair of parentheses:
type subrange = (a) .. b;
Compare this to the following declaration of an enumerated type with only one value:
type enum = (a);
These two declarations look identical until the
.. token. With normal LALR(1) one-token look-ahead.
The consequence is a reduce-reduce conflict, which is summarized in this state of the LALR automata:
State 10: id_list -> ID . (Rule 4) expr -> ID . (Rule 11) ')' [reduce using rule 11 (expr)] ')' reduce using rule 4 (id_list) ',' reduce using rule 4 (id_list) $default reduce using rule 11 (expr)
The grammar in file
pascalenumeratedvsrangesolvedvialex.eyp solves this particular problem by looking ahead in the lexical analyzer: if the parenthesis is followed by a sequence of comma separated identifiers finished by the closing parenthesis and a semicolon we can conclude that is a enumerated type declaration. For more details, have a look at the file. Another solution using the postponed conflict resolution strategy can be found in file
pascalenumeratedvsrangesolvedviadyn.eyp.
Though not so common, it may occur that a reduce-reduce conflict is not due to ambiguity but to the limitations of the LALR(1) algorithm. The following example illustrates the point:
pl@europa:~/LEyapp/examples/debuggingtut$ cat -n rrconflictnamefirst.eyp 1 %token VAR ',' ':' 2 3 %{ 4 use base q{Tail}; 5 %} 6 7 %% 8 def: param_spec return_spec ',' 9 ; 10 param_spec: 11 type 12 | name_list ':' type 13 ; 14 return_spec: 15 type 16 | name ':' type 17 ; 18 name: VAR 19 ; 20 type: VAR 21 ; 22 name_list: 23 name 24 | name ',' name_list 25 ; 26 %% 27 28 __PACKAGE__->main unless caller();
This non ambiguous grammar generates a language of sequences like
a, b : e f : e,
The conflict is due to the final comma in:
def: param_spec return_spec ','
If you suppress such comma there is no conflict (try it). When compiling with eyapp we get the warning:
pl@europa:~/LEyapp/examples/debuggingtut$ eyapp rrconflictnamefirst.eyp 1 reduce/reduce conflict
Editing the
.output file we can see the conflict is in state 2:
46 State 2: 47 48 name -> VAR . (Rule 6) 49 type -> VAR . (Rule 7) 50 51 ',' [reduce using rule 7 (type)] 52 VAR reduce using rule 7 (type) 53 $default reduce using rule 6 (name)
If we look at the grammar we can see that a reduction by
type -> VAR .
may occur with a comma as incoming token but only after the reduction by
param_spec has taken place. The problem is that the automaton forgets about it. Look the automaton transitions in the
.outputfile. By making explicit the difference between the first and second
type we solve the conflict:
pl@europa:~/LEyapp/examples/debuggingtut$ cat -n rrconflictnamefirst_fix1.eyp 1 %token VAR ',' ':' 2 3 %{ 4 use base q{Tail}; 5 %} 6 7 %% 8 def: param_spec return_spec ',' 9 ; 10 param_spec: 11 type 12 | name_list ':' type 13 ; 14 return_spec: 15 typeafter 16 | name ':' typeafter 17 ; 18 name: VAR 19 ; 20 type: VAR 21 ; 22 typeafter: VAR 23 ; 24 name_list: 25 name 26 | name ',' name_list 27 ; 28 %% 29 30 __PACKAGE__->main unless caller();
A reduce-reduce conflict is solved in favor of the first production found in the text. If we execute the grammar with the conflict
./rrconflictnamefirst.pm, we get the correct behavior:
pl@europa:~/LEyapp/examples/debuggingtut$ eyapp -b '' rrconflictnamefirst.eyp 1 reduce/reduce conflict pl@europa:~/LEyapp/examples/debuggingtut$ ./rrconflictnamefirst.pm Expressions. Press CTRL-D (Unix) or CTRL-Z (Windows) to finish: a,b:c d:e, <CTRL-D> $
The program accepts the correct language - in spite of the conflict - due to the fact that the production
name: VAR
is listed first.
The parser rejects the correct phrases if we swap the order of the productions writing the
type: VAR production first,
pl@europa:~/LEyapp/examples/debuggingtut$ ./reducereduceconflict.pm Expressions. Press CTRL-D (Unix) or CTRL-Z (Windows) to finish: a,b:c d:e, <CTRL-D> Syntax error near input: ',' (lin num 1). Incoming text: === b:c d === Expected one of these terminals: VAR
Files
reducereduceconflict_fix1.eyp and
reducereduceconflict_fix2.eyp offer other solutions to the problem.
Usually there is a one-to-one relation between a token and a regexp. Problems arise, however when a token's type depends upon contextual information. An example of this problem comes from PL/I, where statements like this are legal:
if then=if then if=then
In PL/I this problem arises because keywords like
if are not reserved and can be used in other contexts. This simplified grammar illustrates the problem:
examples/debuggingtut$ eyapp -c PL_I_conflict.eyp # This grammar deals with the famous ambiguous PL/I phrase: # if then=if then if=then # The (partial) solution uses YYExpect in the lexical analyzer to predict the token # that fulfills the parser expectatives. # Compile it with: # eyapp -b '' PL_I_conflict.eyp # Run it with; # ./PL_I_conflict.pm -debug %strict %token ID %tree bypass %% stmt: ifstmt | assignstmt ; # Exercise: change this production # for 'if' expr 'then' stmt # and check with input 'if then=if then if=then'. The problem arises again ifstmt: %name IF 'if' expr 'then' expr ; assignstmt: id '=' expr ; expr: %name EQ id '=' id | id ; id: %name ID ID ; %%
If the token ambiguity depends only in the syntactic context, the problem can be alleviated using the
YYExpect method. In case of doubt, the lexical analyzer calls the
YYExpect method to know which of the several feasible tokens is expected by the parser:
examples/debuggingtut$ sed -ne '/sub lex/,/^}/p' PL_I_conflict.eyp sub lexer { my $parser = shift; for ($parser->{input}) { # contextualize m{\G\s*(\#.*)?}gc; m{\G([a-zA-Z_]\w*)}gc and do { my $id = $1; return ('if', 'if') if ($id eq 'if') && is_in('if', $parser->YYExpect); return ('then', 'then') if ($id eq 'then') && is_in('then', $parser->YYExpect); return ('ID', $id); }; m{\G(.)}gc and return ($1, $1); return('',undef); } }
Here follows an example of execution:
examples/debuggingtut$ eyapp -b '' PL_I_conflict.eyp examples/debuggingtut$ ./PL_I_conflict.pm Expressions. Press CTRL-D (Unix) or CTRL-Z (Windows) to finish: if then=if then if=then IF(EQ(ID,ID),EQ(ID,ID))
A lexical tie-in is a flag which is set to alter the behavior of the lexical analyzer. It is a way to handle context-dependency.
C
The C language has a context dependency: the way an identifier is used depends on what its current meaning is. For example, consider this:
T(x);
This looks like a function call statement, but if
T is a typedef name, then this is actually a declaration of
x. How can a parser for C decide how to parse this input?
Here is another example:
{ T * x; ... }
What is this, a declaration of
x as a pointer to
T, or a void multiplication of the variables
T and
x?
The usual method to solve this problem is to have two different token types,
ID and
TYPENAME. When the lexical analyzer finds an identifier, it looks up in the symbol table the current declaration of the identifier in order to decide which token type to return:
TYPENAME if the identifier is declared as a typedef,
ID otherwise. See the ANSI C parser example in the directory
examples/languages/C/ansic.eyp
In the "Calc"-like example in
examples/debuggintut/SemanticInfoInTokens.eyp we have a language with a special construct
hex (hex-expr). After the keyword
hex comes an
expression in parentheses in which all integers are hexadecimal. In particular, strings in
/[A-F0-9]+/ like
A1B must be treated as an hex integer unless they were previously declared as variables. Let us see an example of execution:
$ eyapp -b '' SemanticInfoInTokens.eyp $ cat inputforsemanticinfo2.txt int A2 A2 = HEX(A23); A2 = HEX(A2) $ ./SemanticInfoInTokens.pm -f inputforsemanticinfo2.txt -t EXPS(ASSIGN(TERMINAL[A2],NUM[2595]),ASSIGN(TERMINAL[A2],ID[A2]))
The first hex expression
HEX(A23) is interpreted as the number
2595 while the second
HEX(A2) refers to previously declared variable
A2.
An alternative solution to this problem that does not make use of lexical tie-ins - but still uses an attribute
HEXFLAG for communication between different semantic actions - can be found in the file
examples/debuggintut/Tieins.eyp.
pl@nereida:~/LEyapp/examples/debuggingtut$ sed -ne '5,91p' SemanticInfoInTokens.eyp | cat -n 1 %strict 2 3 %token ID INT INTEGER 4 %syntactic token HEX 5 6 %right '=' 7 %left '+' 8 9 %{ 10 use base q{DebugTail}; 11 my %st; 12 %} 13 14 %tree bypass alias 15 16 %% 17 stmt: 18 decl <* ';'> expr <%name EXPS + ';'> 19 { 20 # make the symbol table an attribute 21 # of the root node 22 $_[2]->{st} = { %st }; 23 $_[2]; 24 } 25 ; 26 27 decl: 28 INT ID <+ ','> 29 { 30 # insert identifiers in the symbol table 31 $st{$_->{attr}} = 1 for $_[2]->children(); 32 } 33 ; 34 35 expr: 36 %name ID 37 ID 38 | %name NUM 39 INTEGER 40 | %name HEX 41 HEX '(' { $_[0]->{HEXFLAG} = 1; } $expr ')' 42 { 43 $_[0]->{HEXFLAG} = 0; 44 $expr; 45 } 46 | %name ASSIGN 47 id '=' expr 48 | %name PLUS 49 expr '+' expr 50 ; 51 52 id : ID 53 ; 54 55 %% 56 57 # Context-dependant lexer 58 __PACKAGE__->lexer( sub { 59 my $parser = shift; 60 my $hexflag = $parser->{HEXFLAG}; 61 62 for (${$parser->input}) { # contextualize 63 m{\G\s*(\#.*)?}gc; 64 65 m{\G(HEX\b|INT\b)}igc and return (uc($1), $1); 66 67 m{(\G\d+)}gc and return ('INTEGER', $hexflag? hex($1) : $1); 68 69 70 m{\G([a-zA-Z_]\w*)}gc and do { 71 my $match = $1; 72 $hexflag and !exists($st{$match}) and $match =~ m{^([A-F0-9]+$)}gc and return ('INTEGER', hex($match)); 73 return ('ID', $1); 74 }; 75 76 m{\G(.)}gc and return ($1, $1); 77 78 return('',undef); 79 } 80 } 81 ); 82 83 *TERMINAL::info = *NUM::info = *ID::info = sub { 84 $_[0]->{attr} 85 }; 86 87 __PACKAGE__->main() unless caller();
Here the lexical analyzer looks at the value of the attribute
HEXFLAG; when it is nonzero, all integers are parsed in hexadecimal, and tokens starting with letters are parsed as integers if possible.
For more about lexical tie-ins see also strategy presented here can be used whenever there is a shift-reduce or reduce-reduce conflict that can not be solved using static precedences.;
The more the time invested writing tests the less the time spent debugging. This section deals with the Parse::Eyapp::Node method
equal which can be used to test that the trees have the shape we expect.
A call
$tree1->equal($tree2) compare the two trees
$tree1 and
$tree2. Two trees are considered equal if their root nodes belong to the same class, they have the same number of children and the children are (recursively) equal.
In Addition to the two trees the programmer can specify pairs
attribute_key => equality_handler:
$tree1->equal($tree2, attr1 => \&handler1, attr2 => \&handler2, ...)
In such case the definition of equality is more restrictive: Two trees are considered equal if
An attribute handler receives as arguments the values of the attributes of the two nodes being compared and must return true if, and only if, these two attributes are considered equal. Follows an example:
examples/Node$ cat -n equal.pl 1 #!/usr/bin/perl -w 2 use strict; 3 use Parse::Eyapp::Node; 4 5 my $string1 = shift || 'ASSIGN(VAR(TERMINAL))'; 6 my $string2 = shift || 'ASSIGN(VAR(TERMINAL))'; 7 my $t1 = Parse::Eyapp::Node->new($string1, sub { my $i = 0; $_->{n} = $i++ for @_ }); 8 my $t2 = Parse::Eyapp::Node->new($string2); 9 10 # Without attributes 11 if ($t1->equal($t2)) { 12 print "\nNot considering attributes: Equal\n"; 13 } 14 else { 15 print "\nNot considering attributes: Not Equal\n"; 16 } 17 18 # Equality with attributes 19 if ($t1->equal($t2, n => sub { return $_[0] == $_[1] })) { 20 print "\nConsidering attributes: Equal\n"; 21 } 22 else { 23 print "\nConsidering attributes: Not Equal\n"; 24 }
When the former program is run without arguments produces the following output:
examples/Node$ equal.pl Not considering attributes: Equal Considering attributes: Not Equal
equalDuring Testing
During the development of your compiler you add new stages to the existing ones. The consequence is that the AST is decorated with new attributes. Unfortunately, this implies that tests you wrote using
is_deeply and comparisons against formerly correct abstract syntax trees are no longer valid. This is due to the fact that
is_deeply requires both tree structures to be equivalent in every detail and that our new code produces a tree with new attributes.
Instead of
is_deeply use the
equal method to check for partial equivalence between abstract syntax trees. You can follow these steps:
Data::Dumperstatements
Data::Dumper
equal.
Tests using this methodology will not fail even if later code decorating the AST with new attributes is introduced.
See an example that checks an abstract syntax tree produced by the simple compiler (see
examples/typechecking/Simple-Types-XXX.tar.gz) for a really simple source:
Simple-Types/script$ cat prueba27.c int f() { }
The first thing is to obtain a description of the tree, that can be done executing the compiler under the control of the Perl debugger, stopping just after the tree has been built and dumping the tree with Data::Dumper:
pl@nereida:~/Lbook/code/Simple-Types/script$ perl -wd usetypes.pl prueba27.c main::(usetypes.pl:5): my $filename = shift || die "Usage:\n$0 file.c\n"; DB<1> c 12 main::(usetypes.pl:12): Simple::Types::show_trees($t, $debug); DB<2> use Data::Dumper DB<3> $Data::Dumper::Purity = 1 DB<4> p Dumper($t) $VAR1 = bless( { .............................................. }, 'PROGRAM' ); ...............................................................
Once we have the shape of a correct tree we can write our tests:
examples/Node$ cat -n testequal.pl 1 #!/usr/bin/perl -w 2 use strict; 3 use Parse::Eyapp::Node; 4 use Data::Dumper; 5 use Data::Compare; 6 7 my $debugging = 0; 8 9 my $handler = sub { 10 print Dumper($_[0], $_[1]) if $debugging; 11 Compare($_[0], $_[1]) 12 }; 13 14 my $t1 = bless( { 15 'types' => { 16 'CHAR' => bless( { 'children' => [] }, 'CHAR' ), 17 'VOID' => bless( { 'children' => [] }, 'VOID' ), 18 'INT' => bless( { 'children' => [] }, 'INT' ), 19 'F(X_0(),INT)' => bless( { 20 'children' => [ 21 bless( { 'children' => [] }, 'X_0' ), 22 bless( { 'children' => [] }, 'INT' ) ] 23 }, 'F' ) 24 }, 25 'symboltable' => { 'f' => { 'type' => 'F(X_0(),INT)', 'line' => 1 } }, 26 'lines' => 2, 27 'children' => [ 28 bless( { 29 'symboltable' => {}, 30 'fatherblock' => {}, 31 'children' => [], 32 'depth' => 1, 33 'parameters' => [], 34 'function_name' => [ 'f', 1 ], 35 'symboltableLabel' => {}, 36 'line' => 1 37 }, 'FUNCTION' ) 38 ], 39 'depth' => 0, 40 'line' => 1 41 }, 'PROGRAM' ); 42 $t1->{'children'}[0]{'fatherblock'} = $t1; 43 44 # Tree similar to $t1 but without some attributes (line, depth, etc.) 45 my $t2 = bless( { 46 'types' => { 47 'CHAR' => bless( { 'children' => [] }, 'CHAR' ), 48 'VOID' => bless( { 'children' => [] }, 'VOID' ), 49 'INT' => bless( { 'children' => [] }, 'INT' ), 50 'F(X_0(),INT)' => bless( { 51 'children' => [ 52 bless( { 'children' => [] }, 'X_0' ), 53 bless( { 'children' => [] }, 'INT' ) ] 54 }, 'F' ) 55 }, 56 'symboltable' => { 'f' => { 'type' => 'F(X_0(),INT)', 'line' => 1 } }, 57 'children' => [ 58 bless( { 59 'symboltable' => {}, 60 'fatherblock' => {}, 61 'children' => [], 62 'parameters' => [], 63 'function_name' => [ 'f', 1 ], 64 }, 'FUNCTION' ) 65 ], 66 }, 'PROGRAM' ); 67 $t2->{'children'}[0]{'fatherblock'} = $t2; 68 69 # Tree similar to $t1 but without some attributes (line, depth, etc.) 70 # and without the symboltable and types attributes used in the comparison 71 my $t3 = bless( { 72 'types' => { 73 'CHAR' => bless( { 'children' => [] }, 'CHAR' ), 74 'VOID' => bless( { 'children' => [] }, 'VOID' ), 75 'INT' => bless( { 'children' => [] }, 'INT' ), 76 'F(X_0(),INT)' => bless( { 77 'children' => [ 78 bless( { 'children' => [] }, 'X_0' ), 79 bless( { 'children' => [] }, 'INT' ) ] 80 }, 'F' ) 81 }, 82 'children' => [ 83 bless( { 84 'symboltable' => {}, 85 'fatherblock' => {}, 86 'children' => [], 87 'parameters' => [], 88 'function_name' => [ 'f', 1 ], 89 }, 'FUNCTION' ) 90 ], 91 }, 'PROGRAM' ); 92 93 $t3->{'children'}[0]{'fatherblock'} = $t2; 94 95 # Without attributes 96 if (Parse::Eyapp::Node::equal($t1, $t2)) { 97 print "\nNot considering attributes: Equal\n"; 98 } 99 else { 100 print "\nNot considering attributes: Not Equal\n"; 101 } 102 103 # Equality with attributes 104 if (Parse::Eyapp::Node::equal( 105 $t1, $t2, 106 symboltable => $handler, 107 types => $handler, 108 ) 109 ) { 110 print "\nConsidering attributes: Equal\n"; 111 } 112 else { 113 print "\nConsidering attributes: Not Equal\n"; 114 } 115 116 # Equality with attributes 117 if (Parse::Eyapp::Node::equal( 118 $t1, $t3, 119 symboltable => $handler, 120 types => $handler, 121 ) 122 ) { 123 print "\nConsidering attributes: Equal\n"; 124 } 125 else { 126 print "\nConsidering attributes: Not Equal\n"; 127 }
The code defining tree
$t1 was obtained from an output using
Data::Dumper. The code for trees
$t2 and
$t3 was written using cut-and-paste from
$t1. They have the same shape than
$t1 but differ in their attributes. Tree
$t2 shares with
$t1 the attributes
symboltable and
types used in the comparison and so
equal returns
true when compared. Since
$t3 differs from
$t1 in the attributes
symboltable and
types the call to
equal returns
false.
I use these rules for indenting Parse::Eyapp programs:
synvar: 'a' othervar 'c' | 'b' anothervar SOMETOKEN ;
The separation bar
| goes indented relative to the left side of the rule. Each production starts two spaces from the bar. The first right hand side is aligned with the rest.
;must also be in its own line at column 0
syntacvar: /* empty */ | 'a' othervar 'c' | 'b' anothervar ;
exp: $NUM { $NUM->[0] } | $VAR { my $id = $VAR->[0]; my $val = $s{$id}; $_[0]->semantic_error("Accessing undefined variable $id at line $VAR->[1].\n") unless defined($val); return $val; } | $VAR '=' $exp { $s{$VAR->[0]} = $exp } | exp.x '+' exp.y { $x + $y } | exp.x '-' exp.y { $x - $y } | exp.x '*' exp.y { $x * $y } | exp.x '/'.barr exp.y { return($x/$y) if $y; $_[0]->semantic_error("Illegal division by zero at line $barr->[1].\n"); undef } | '-' $exp %prec NEG { -$exp } | exp.x '^' exp.y { $x ** $y } | '(' $exp ')' { $exp } ;. | http://search.cpan.org/dist/Parse-Eyapp/lib/Parse/Eyapp/debuggingtut.pod | CC-MAIN-2016-07 | refinedweb | 7,441 | 60.35 |
Riftsaw configuration as ODE (wsa headers and failure policy)rdelaporte Apr 13, 2010 12:18 PM
Hi,
I'm using Riftsaw 2.0.0 final version.
I would like to know if Riftsaw supports the ODE configurations as there :
-
-
1. In fact, i'd like to set custom HTTP header on a SOAP request to a partnerlink.
I also want to set WS-Addressing headers automaticly on one-way invoke on a partnerlink. Is it possible ?
2. I want to set some kind of redelivery policy if an invoke activity fails for example. Is it possible ?
Thanks a lot.
Regards,
Raphaël.
1. Re: Riftsaw configuration as ODE (wsa headers and failure policy)jeff.yuchang Apr 13, 2010 10:52 PM (in response to rdelaporte)
Hi Raphael,
For the endpoint configuration, yes, we support them. For the supported properties, please refer to for the detail information. With regard to the ws-addressing, afaik, I don't think we have this functionality. Could you try it and file a jira if it doesn't work.
For the ActivityFailureandRecoery, as RiftSaw is based on ODE, yes, it supports.
Regards
Jeff
2. Re: Riftsaw configuration as ODE (wsa headers and failure policy)rdelaporte Apr 14, 2010 4:41 AM (in response to jeff.yuchang)
Hi Jeff,
1. For the endpoint configuration, I've tried into the riftsaw.sar/bpel.properties, I didn't saw the global congifuration remarks...
But still, even in the bpelContent dir, it's not working, I'll raise a JIRA about that.
2. For the WSA headers, i've already tested it, and Riftsaw does not add the standard WSA headers for one-way invoke. It should be nice. I'll raise a JIRA about that as well.
3. For the failure recovery, I cannot manage to use it.
I've tried the sample on ODE guide
>
I stopped my SoapUI partnerlink, but it does not do the retry logic at all...
Maybe I can help, i'd like to contribute !
Regards,
Raphaël.
3. Re: Riftsaw configuration as ODE (wsa headers and failure policy)jeff.yuchang Apr 14, 2010 9:18 PM (in response to rdelaporte)
Hi Raphaël,
Thanks very much for your jiras and test cases, we definitely like your contribution.
For the endpoint configuration, we don't support the global configuration for now, only supports the properties from bpel bundle. we have had a jira, which you could find useful for your contribution.
Additionaly, you can go to wiki pages () for more information about Riftsaw, it has some documents that should help you get familiar with RiftSaw codebase, like Building RiftSaw code etc.
Regards
Jeff
4. Re: Riftsaw configuration as ODE (wsa headers and failure policy)jeff.yuchang Apr 22, 2010 10:41 PM (in response to rdelaporte)
For the activity failure recovery feature, we have issues for it now, I've created a jira for this:
-Jeff
5. Re: Riftsaw configuration as ODE (wsa headers and failure policy)jeff.yuchang Jun 18, 2010 7:25 AM (in response to jeff.yuchang)
For your information, I've verified the activity failure recover working on the current code base, which will be released on the CR2.
6. Re: Riftsaw configuration as ODE (wsa headers and failure policy)clsimone Mar 3, 2011 7:25 AM (in response to jeff.yuchang)
Hello everyone,
I have the following issue with the activity failure and recovery from ODE. I have a process that uses this activity for each invoke (if a service is not available) and runs perfect on my local machine which is a Windows, but if I deploy it on a Linux machine it doesn't work. It doesn't complain about anything, it simply ignores this activity and the process fails with a request timeout.
<bpel:invoke
<ext:failureHandling xmlns:
<ext:faultOnFailure>true</ext:faultOnFailure>
</ext:failureHandling>
</bpel:invoke>
My question is: could it be that on the other machine the namespace cannot find the dependency?
xmlns:ext=""
I do the build with maven and I have in my local repository on both machines the library that should provide the activity definition.
I have the same version of JBoss and Riftsaw on both machines
Do you have any idea what could be the problem?
Thank you,
Laura
7. Re: Riftsaw configuration as ODE (wsa headers and failure policy)clsimone Mar 3, 2011 12:00 PM (in response to clsimone)
Never mind, the Riftsaw versions were different . On the Linux machine I have the Riftsaw-2.0.0 and on Windows I have Riftsaw-2.2.0. So, for everyone that wants to use activity failure and recovery, do not use it with version 2.0.0.
Regards,
Laura | https://developer.jboss.org/message/537316 | CC-MAIN-2021-04 | refinedweb | 778 | 65.52 |
Recently I have tried to connect to SQL Database server which is in my local network machine. I can connect and access SQL server from my Android app. I did it in the following way….
1. First of all you need a JDBC driver library for SQL Server. As we know android library has only SQLite database driver. So first download an open source JDBC driver from this site (I downloaded the Linux version).
2. Then import the jar file into your Android app.(jtds-1.2.5.jar).
3. Now just try this code by modifying according to your context
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import net.sourceforge.jtds.jdbc.*; public void query2() { Log.i("Android"," MySQL Connect Example."); Connection conn = null; try { String driver = "net.sourceforge.jtds.jdbc.Driver"; Class.forName(driver).newInstance(); //test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class; String connString = "jdbc:jtds:sqlserver://server_ip_address :1433/DBNAME;encrypt=fasle;user=xxxxxxxxx;password=xxxxxxxx;instance=SQLEXPRESS;"; String username = "xxxxxx"; String password = "xxxxxxxxxx"; conn = DriverManager.getConnection(connString,username,password); Log.w("Connection","open"); Statement stmt = conn.createStatement(); ResultSet reset = stmt.executeQuery("select * from TableName"); //Print the data to the console while(reset.next()){ Log.w("Data:",reset.getString(3)); // Log.w("Data",reset.getString(2)); } conn.close(); } catch (Exception e) { Log.w("Error connection","" + e.getMessage()); } }
4. You will find more about parameter passing here in connection string .
August 9, 2011 at 12:13 am
A big thank you for your article post.Much thanks again. Keep writing.
August 19, 2011 at 6:17
February 2, 2012 at 8:40 am
Oh sorry in this connection, which network that you connect to each other?
wireless or something else…
February 2, 2012 at 8:58 am
I think wireless/other-connection will not vary. My database server machine was on the private network(Intranet) and my android device and emulator was connected on that network.
February 2, 2012 at 4:13 pm
Yes thank you!
Excuse me sir ! When i follow from your code on Eclipse and run with Android Emulator in the same machine, why it show the message in log that : Error connection Unable to get information from SQL Server : 169.254.91.62.
About the server_ip_address i try to get from (TCP/IP in SQL Server configuration manager), (Local Area Connection)…. What the problem?
SQL Server 2008 (MSSQLSERVER)
Database Name : MyDB
User : sa
Password : 123
Best regard.
Jerry
February 3, 2012 at 5:44 am
I feel glad to help you! Please try to access any site from Android Emulator that is hosted in your local machine. If this can be accessed then SQL Server can be accessed (in your case there may be SQL Server authentication/configuration problem, hints: SQLEXPRESS instead of MSSQLSERVER, // or \\, I know little about Database Server), otherwise I guess SQL Server in same machine can’t be accessed from Emulator.
You are most welcome.
February 3, 2012 at 4:25 pm
Yes sir ! Thank you so much for your help. I’m really admire of you… and I think u are my guide.
Next time if I have some problem again, Can I ask you?
Sorry that I bother you a lot…
Best regard.
Jerry
February 6, 2012 at 9:05 am
You are so welcome. Please feel free to ask any question.
February 3, 2012 at 6:59 pm
Amitku, how’re you?
I’m development a software will access MSSQL by TCP/IP. Is your java code enough to do that? I ask it because I tried to run in the Android emulator and I didn’t get it to work. It show the same message from Jerry.
PS: sorry for my bad english. If you don’t understand me, please talk to me, ok?
Thank you so much.
February 6, 2012 at 9:12 am
As I tested this code with SQL Server 2008 running in a different machine on the Intranet, I think this code will work. Follow “Ricardo Gallwas” comment.
Thanks for following this post.
February 6, 2012 at 9:21 am
But for what kind of scenario you want to access Database server? My thinking is that if you need to access Database server for grabbing data from your phone/tablet application it will be better to create web-service(php,ruby on rails, asp.net, J2EE) to access database and query the data or save the data by web service into your database by URL/http request from your Android application and then do whatever you want in your application with that data.
I do that for an Android application which is also a live web application.
I apology for any misleading suggestion. Thanks
February 9, 2012 at 5:41 am
am developing a android mobile app and in that i want to access and insert the text values into the MS sql sever database.can u give me the code for that.Thanks in advance…
For DB Connection :
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con=DriverManager.getConnection(“Jdbc:Odbc:Driver={SQL Server};Database=”+db_database+”;Server=”+db_server+”,”+db_port+”;”,db_username,db_password);
Database : CRLocator
Port : 49162
Username : crlocator
pwd : crlocator
February 10, 2012 at 2:01 pm
Hi there. first of all i gotta say congrats for your article, it came in handy. However, i found a problem when running it. It throws the follwing exception:
Charset 0x0904D0002A/Cp850 is not supported by the JVM.
I googled it and found that charsets.jar is missing in my Android’s JVM. now the question is how do i install this jar in my android? I tried adding this jar to my android project and compiling it but i still get the same exception when running it in my android phone.
Thanks in advance :)
February 29, 2012 at 4:29 am
I have done the Steps 1 & 2
Can you explain at which location i need to call this step:3. Actually this code is not invoked by the project.
regards
Sham
March 9, 2012 at 9:53 am
From the above link, I just can find JDBC driver in Wondow version. Where can i find the linux version? Thanks anyway.
March 14, 2012 at 9:39 am
hi amitku:
Can u help me for the MYSQL database calling in an android application?
Please tell me there is any way to call database table into the android device, and i don’t want use any middle ware
for that, direct connection with a database.
if it is possible then tell me, it will help me for my project.
April 26, 2012 at 8:09 am
sir i am having one doubt i am using your coding to connect sql sever but i am getting an error while running application in log i am getting unable to get information from sql server
April 27, 2012 at 11:18 am
thank you so much for this tutorials
May 9, 2012 at 10:37 pm
Hello I am getting an error Classnotfoundexception. can you plz tell me how to resolve this issue
May 21, 2012 at 11:50 am
Hey Amitku.
Thanks for the wonderful article but dude Im stuck.
can just provide a zip file of your project
so I can go through.
Becz for me my Logcat
all is saying ERROR CONNECTION
“05-21 12:47:07.462: E/Error connection(403): net.sourceforge.jtds.jdbc.Driver”
Don’t have any idea.
Cheers man
June 9, 2012 at 8:09 am
Thank you for give this connectivity code.
thank you very much | http://amitku.wordpress.com/2011/08/03/how-to-connect-and-access-sql-database-server-from-android-app/ | CC-MAIN-2014-15 | refinedweb | 1,263 | 67.04 |
)
SYNOPSIS
#include <stdlib.h> void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); int heapsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); int mergesort(void *base, size_t nmemb, size_t size, int (*compar). mergesort() functions qsort() and heapsort() are not stable, that is, if two mem- bers compare as equal, their order in the sorted array is undefined. The function mergesort() is stable. The qsort() function is an implementation of C.A.R. Hoare's ``quicksort'' algorithm, a variant of partition-exchange sorting; in particular, see D.E. Knuth's Algorithm Q. qsort() takes O N lg N average time. This implementation uses median selection to avoid its O N**2 worst-case behavior. The heapsort() function is an implementation of J.W.J. William's ``heap-- sion. The function mergesort() requires additional memory of size nmemb * size bytes; it should be used only when space is not at a premium. mergesort() is optimized for data with pre-existing order; its worst case time is O N lg N; its best case is O N. Normally, qsort() is faster than mergesort() is faster than heapsort(). Memory availability and pre-existing order in the data can make this untrue.
RETURN VALUES
The qsort()- ory.
COMPATIBILITY
Previous versions of qsort() did not permit the comparison routine itself to call qsort(). This is no longer true.", 7.1.2 June 4, 1993 NetBSD 7.1.2 | https://man.netbsd.org/NetBSD-7.1.2/i386/qsort.3 | CC-MAIN-2022-05 | refinedweb | 242 | 68.26 |
Author: tim.peters Date: Thu Jul 27 03:14:53 2006 New Revision: 50855 Modified: python/trunk/Misc/NEWS python/trunk/Python/mystrtoul.c Log: Bug #1521947: possible bug in mystrtol.c with recent gcc. In general, C doesn't define anything about what happens when an operation on a signed integral type overflows, and PyOS_strtol() did several formally undefined things of that nature on signed longs. Some version of gcc apparently tries to exploit that now, and PyOS_strtol() could fail to detect overflow then. Tried to repair all that, although it seems at least as likely to me that we'll get screwed by bad platform definitions for LONG_MIN and/or LONG_MAX now. For that reason, I don't recommend backporting this. Note that I have no box on which this makes a lick of difference -- can't really test it, except to note that it didn't break anything on my boxes. Silent change: PyOS_strtol() used to return the hard-coded 0x7fffffff in case of overflow. Now it returns LONG_MAX. They're the same only on 32-bit boxes (although C doesn't guarantee that either ...). Modified: python/trunk/Misc/NEWS ============================================================================== --- python/trunk/Misc/NEWS (original) +++ python/trunk/Misc/NEWS Thu Jul 27 03:14:53 2006 @@ -12,6 +12,11 @@ Core and builtins ----------------- +- Bug #1521947: When checking for overflow, ``PyOS_strtol()`` used some + operations on signed longs that are formally undefined by C. + Unfortunately, at least one compiler now cares about that, so complicated + the code to make that compiler happy again. + - Bug #1524310: Properly report errors from FindNextFile in os.listdir. - Patch #1232023: Stop including current directory in search @@ -37,7 +42,7 @@ mapping the faux "thread id" 0 to the current frame. - Bug #1525447: build on MacOS X on a case-sensitive filesystem. - + Library ------- @@ -88,7 +93,7 @@ Extension Modules ----------------- -- Bug #1471938: Fix curses module build problem on Solaris 8; patch by +- Bug #1471938: Fix curses module build problem on Solaris 8; patch by Paul Eggert. - Patch #1448199: Release interpreter lock in _winreg.ConnectRegistry. Modified: python/trunk/Python/mystrtoul.c ============================================================================== --- python/trunk/Python/mystrtoul.c (original) +++ python/trunk/Python/mystrtoul.c Thu Jul 27 03:14:53 2006 @@ -195,10 +195,19 @@ return (unsigned long)-1; } +/* Checking for overflow in PyOS_strtol is a PITA since C doesn't define + * anything about what happens when a signed integer operation overflows, + * and some compilers think they're doing you a favor by being "clever" + * then. Python assumes a 2's-complement representation, so that the bit + * pattern for the largest postive signed long is LONG_MAX, and for + * the smallest negative signed long is LONG_MAX + 1. + */ + long PyOS_strtol(char *str, char **ptr, int base) { long result; + unsigned long uresult; char sign; while (*str && isspace(Py_CHARMASK(*str))) @@ -208,17 +217,20 @@ if (sign == '+' || sign == '-') str++; - result = (long) PyOS_strtoul(str, ptr, base); + uresult = PyOS_strtoul(str, ptr, base); - /* Signal overflow if the result appears negative, - except for the largest negative integer */ - if (result < 0 && !(sign == '-' && result == -result)) { + if (uresult <= (unsigned long)LONG_MAX) { + result = (long)uresult; + if (sign == '-') + result = -result; + } + else if (sign == '-' && uresult == (unsigned long)LONG_MAX + 1) { + assert(LONG_MIN == -LONG_MAX-1); + result = LONG_MIN; + } + else { errno = ERANGE; - result = 0x7fffffff; + result = LONG_MAX; } - - if (sign == '-') - result = -result; - return result; } | https://mail.python.org/pipermail/python-checkins/2006-July/054977.html | CC-MAIN-2017-17 | refinedweb | 534 | 51.18 |
Your message dated Fri, 22 Feb 2002 17:28:16 +0100 with message-id <20020222162816.GA1218@zombie.inka.de> and subject line Bug#135211: boot-floppies: bf2.4 has 2.4.17 kernel but 2.2.20 Feb 2002 15:15:33 +0000 >From claus_h@image.dk Fri Feb 22 09:15:33 2002 Return-path: <claus_h@image.dk> Received: from fepe.post.tele.dk [195.41.46.137] by master.debian.org with esmtp (Exim 3.12 1 (Debian)) id 16eHQ5-0005RE-00; Fri, 22 Feb 2002 09:15:33 -0600 Received: from localhost.localdomain ([62.243.131.45]) by fepE.post.tele.dk (InterMail vM.4.01.03.23 201-229-121-123-20010418) with ESMTP id <20020222151530.LLFF24918.fepE.post.tele.dk@localhost.localdomain> for <submit@bugs.debian.org>; Fri, 22 Feb 2002 16:15:30 +0100 Subject: boot-floppies: bf2.4 has 2.4.17 kernel but 2.2.20 modules From: Claus Hindsgaul <claus_h@image.dk> To: Debian Bug Tracking System <submit@bugs.debian.org> Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable X-Mailer: Evolution/1.0.2 Date: 22 Feb 2002 16:16:39 +0100 Message-Id: <[🔎] 1014390999.1176.10.camel@reber> Mime-Version: 1.0 Delivered-To: submit@bugs.debian.org Package: boot-floppies Version: CVS 2.22.2002 Severity: important In the current (2-21-2002) CVS, the bf24 flavor include modules for kernel 2.2.20 instead of the version matching the kernel (currently 2.4.17). So no modules can be loaded. The build process include the following messages: $ make resc1440bf2.4.bin [...] I: creating module contents file, 'modcontbf2.4' I: creating 'modulesbf2.4.tgz' I: creating 'linuxbf2.4' I: creating 'sys_mapbf2.4.gz' I: creating 'configbf2.4.gz' I: cleaning up extract area make -C utilities KVER=3D2.2.20 KERNEL_VERSION_CODE=3D144179 writemaps make[1]: Entering directory `/data/debian/boot-floppies/utilities' make -C writemaps KVER=3D2.2.20 KERNEL_VERSION_CODE=3D144179 make[2]: Entering directory `/data/debian/boot-floppies/utilities/writemaps' [...] The following "fix" makes it possible to build a usable bf24 flavor, but of course invalidates all others. It seems that the $kver variable is used somewhere in the bf24 build where it should not have been. ifeq "$(architecture)" "i386" - kver :=3D 2.2.20 + kver :=3D 2.4.17-bf2.4 kver_24 :=3D 2.4.17 endif -- System Information Debian Release: 3.0 Architecture: i386 Kernel: Linux reber 2.4.18-pre9 #19 SMP s=F8n feb 17 15:38:42 CET 2002 i686 Locale: LANG=3Dda, LC_CTYPE=3Dda_DK --------------------------------------- Received: (at 135211-done) by bugs.debian.org; 22 Feb 2002 16:28:19 +0000 >From inet@zombie.inka.de Fri Feb 22 10:28:19 2002 Return-path: <inet@zombie.inka.de> Received: from mail.uni-kl.de (uni-kl.de) [131.246.137.52] by master.debian.org with esmtp (Exim 3.12 1 (Debian)) id 16eIYU-0001Qd-00; Fri, 22 Feb 2002 10:28:18 -0600 Received: from mailinf.rhrk.uni-kl.de (mailinf.rhrk.uni-kl.de [131.246.137.54]) by uni-kl.de (8.10.2+Sun/8.11.5) with ESMTP id g1MGSFg22017; Fri, 22 Feb 2002 17:28:15 +0100 (MET) Received: from domino.informatik.uni-kl.de (domino.informatik.uni-kl.de [131.246.161.19]) by mailinf.rhrk.uni-kl.de (8.10.2+Sun/8.11.5) with ESMTP id g1MGSG924620; Fri, 22 Feb 2002 17:28:16 +0100 (MET) Received: from zombie (rotes255.wohnheim.uni-kl.de [131.246.178.65]) by domino.informatik.uni-kl.de (8.11.6/8.11.6) with ESMTP id g1MGSGv21260; Fri, 22 Feb 2002 17:28:16 +0100 (MET) Received: from inet by zombie with local (Exim 3.34 #1 (Debian)) id 16eIYS-0000R4-00; Fri, 22 Feb 2002 17:28:16 +0100 Date: Fri, 22 Feb 2002 17:28:16 +0100 From: Eduard Bloch <edi@gmx.de> To: Claus Hindsgaul <claus_h@image.dk>, 135211-done@bugs.debian.org Subject: Re: Bug#135211: boot-floppies: bf2.4 has 2.4.17 kernel but 2.2.20 modules Message-ID: <20020222162816.GA1218@zombie.inka.de> References: <[🔎] 1014390999.1176.10.camel@reber> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <[🔎] 1014390999.1176.10.camel@reber> User-Agent: Mutt/1.3.27i Sender: Eduard Bloch <inet@zombie.inka.de> Delivered-To: 135211-done@bugs.debian.org First: ask before reporting important bugs. > In the current (2-21-2002) CVS, the bf24 flavor include modules for > kernel 2.2.20 instead of the version matching the kernel (currently He? What does make you think so? > 2.4.17). So no modules can be loaded. It does not include ANY modules - so which do you expect to be loaded? > The build process include the following messages: ... > make -C utilities KVER=2.2.20 KERNEL_VERSION_CODE=144179 writemaps > make[1]: Entering directory `/data/debian/boot-floppies/utilities' It does not need other utilities than 2.2.20. > make -C writemaps KVER=2.2.20 KERNEL_VERSION_CODE=144179 It does not need other keymaps than 2.2.20. So what did you want to report? Gruss/Regards, Eduard. -- <Zomb>.oO(Die 3 F's fon Debian: Find the bug, Fix the bug, Forward to maintainer) -- Zomb in #debian.de | https://lists.debian.org/debian-boot/2002/02/msg00730.html | CC-MAIN-2017-04 | refinedweb | 886 | 56.01 |
General task and protocol management class. More...
#include <manager.hpp>
General task and protocol management class.
Handles all task and protocol management, creation/destruction of requests and passing of messages to requests. The template argument should be a class type derived from the Request class with at least the response() function defined. To operate this class all that needs to be done is creating an object and calling handler() on it.
Definition at line 185 of file manager.hpp.
Construct from a file descriptor.
The only piece of data required to construct a Manager object is a file descriptor to listen on for incoming connections. By default mod_fastcgi sets up file descriptor 0 to do this so it is the value passed by default to the constructor. The only time it would be another value is if an external FastCGI server was defined.
Definition at line 199 of file manager.hpp.
Tells you the size of the message queue.
Definition at line 109 of file manager.hpp.
References Fastcgipp::ManagerPar::messages.
Return the amount of pending requests.
Definition at line 230 of file manager.hpp.
References Fastcgipp::Manager< T >::requests.
General handling function to be called after construction.
This function will loop continuously manager tasks and FastCGI requests until either the stop() function is called (obviously from another thread) or the appropriate signals are caught.
Definition at line 293 of file manager.hpp.
Handles management messages.
This function is called by handler() in the case that a management message is recieved. Although the request id of a management record is always 0, the Protocol::FullId associated with the message is passed to this function to keep track of it's associated file descriptor.
Definition at line 65 of file manager.cpp.
References Fastcgipp::Message::data, Fastcgipp::Block::data, Fastcgipp::Protocol::GET_VALUES, Fastcgipp::Protocol::maxConnsReply, Fastcgipp::Protocol::maxReqsReply, Fastcgipp::Protocol::mpxsConnsReply, Fastcgipp::Protocol::processParamHeader(), Fastcgipp::Protocol::UNKNOWN_TYPE, and Fastcgipp::Protocol::version.
Passes messages to requests.
Whenever a message needs to be passed to a request, it must be done through this function. Requests are associated with their Protocol::FullId value so that and the message itself is all that is needed. Calling this function from another thread is safe. Although this function can be called from outside the fastcgi++ library, the Request class contains a callback function based on this that is more usable. An id with a Protocol::RequestId of 0 means the message is destined for the Manager itself. Should a message by passed with an id that doesn't exist, it will be discarded.
Definition at line 247 of file manager.hpp.
References Fastcgipp::Protocol::BEGIN_REQUEST, Fastcgipp::Message::data, and Fastcgipp::Message::type.
Configure the handlers for POSIX signals.
By calling this function appropriate handlers will be set up for SIGPIPE, SIGUSR1 and SIGTERM. It is called by default upon construction of a Manager object. Should the user want to override these handlers, it should be done post-construction.
Definition at line 53 of file manager.cpp.
References Fastcgipp::ManagerPar::signalHandler().
Referenced by Fastcgipp::ManagerPar::ManagerPar().
Halter for the handler() function.
This function is intended to be called from a thread separate from the handler() in order to halt it. It should also be called by a signal handler in the case of of a SIGTERM. Once handler() has been halted it may be re-called to pick up exactly where it left off without any data loss.
Definition at line 24 of file manager.cpp.
Terminator for the handler() function.
This function is intended to be called from a signal handler in the case of of a SIGUSR1. It is similar to stop() except that handler() will wait until all requests are complete before halting.
Definition at line 12 of file manager.cpp.
Indicated whether or not the manager is currently in sleep mode.
Definition at line 142 of file manager.hpp.
A queue of messages for the manager itself.
Definition at line 128 of file manager.hpp.
Referenced by Fastcgipp::ManagerPar::getMessagesSize().
Associative container type for active requests.
This container associated the Protocol::FullId of each active request with a pointer to the actual Request object.
Definition at line 243 of file manager.hpp.
Referenced by Fastcgipp::Manager< T >::getRequestsSize().
Mutex to make accessing asleep thread safe.
Definition at line 144 of file manager.hpp.
Boolean value indicating that handler() should halt.
Definition at line 156 of file manager.hpp.
Mutex to make stopBool thread safe.
Definition at line 158 of file manager.hpp.
Queue for pending tasks.
This contains a queue of Protocol::FullId that need their handlers called.
Definition at line 125 of file manager.hpp.
Boolean value indication that handler() should terminate.
Definition at line 163 of file manager.hpp.
Mutex to make terminateMutex thread safe.
Definition at line 165 of file manager.hpp.
The pthread id of the thread the handler() function is operating in.
Although this library is intended to be used with boost::thread and not pthread, the underlying pthread id of the handler() function is needed to call pthread_kill() when sleep is to be interrupted.
Definition at line 150 of file manager.hpp.
Handles low level communication with the other side.
Definition at line 113 of file manager.hpp. | http://www.nongnu.org/fastcgipp/doc/2.1/a00039.html | CC-MAIN-2021-10 | refinedweb | 870 | 52.15 |
Asked by:
#r "...."
Question
I am trying to use Freebase.
I create a new peoject ->library and then...
// Learn more about F# at. See the 'F# Tutorial' project
// for more guidance on F# programming.
#load "Library1.fs"
#r "Samples.DataStore.Freebase.dll"
but, F# interactive shows the msg:
Script.fsx(7,1): error FS0082: Could not resolve this reference. Could not locate the assembly "Samples.DataStore.Freebase.dll". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. (Code=MSB3245)
Script.fsx(7,1): error FS0084: Assembly reference 'Samples.DataStore.Freebase.dll' was not found or is invalid
1-What should I do to do in order to use freebase (with intelisense)?
2-I ve been having a hard time to understand and use references, ....fsx, etc... What would be a good video to understand how to use @ load, #r etc,etc???
DaFonseca
All replies
@load and #r are for use in interactive scripting when there is no project file to orchestrate these details; and in that sort of situation, you may also need to use #i to add the directory path to the reference search list.
However, you are using a project that emits an assembly, to to set up references, you use the right-click context menu on the project in the solution view to add the reference (as you would in C#), browsing to the assembly location.
Do you mean in case I am working directly on F# interctive I can command:
#r "Samples.DataStore.Freebase.dll"
type Webdata = Samples.DataStore.Freebase.FreebaseDat
It is not working.. Any clue?
Another question would be. When using a project how can use Freebase or Worldbank data (with intelisense)? Do I have to add theses as references?? As a solution? an assembly??
what if i want to use show.fs.. Should I save it on project directory and add a reference using browse?
DaFonseca
A worked example using some of my own private projects as a source, as I've not done anything that would make use of freebase
If you try to open a namespace that isn't in any referenced assembly, you get an error at the first unknown facet in that namespace name
> open Tinesware.Infrastructure;; open Tinesware.Infrastructure;; -----^^^^^^^^^ stdin(1,6): error FS0039: The namespace or module 'Tinesware' is not defined
If you try to reference a non-GAC assembly that's not in the standard search path you get resolution failure
> #r "Tinesware.Infrastructure.dll";; #r "Tinesware.Infrastructure.dll" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ stdin(2,1): error FS0082: Could not resolve this reference. Could not locate the assembly "Tinesware.Infrastructure.dll" . Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation er rors. (Code=MSB3245) #r "Tinesware.Infrastructure.dll" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ stdin(2,1): error FS0084: Assembly reference 'Tinesware.Infrastructure.dll' was not found or is invalidSo what you have to do to get at the types you're after is add the folder containing the assembly to the search path, then reference it, then open the namespace:
> #I "E:\\hg\\tinesware-tools\\Infrastructure\\_Output\\Debug+AnyCPU\\lib\\net40";; --> Added 'E:\hg\tinesware-tools\Infrastructure\_Output\Debug+AnyCPU\lib\net40' to library include path > #r "Tinesware.Infrastructure.dll";; --> Referenced 'E:\hg\tinesware-tools\Infrastructure\_Output\Debug+AnyCPU\lib\net40\Tinesware.Infrastructure.dll' > open Tinesware.Infrastructure;; >The MSDN page F# Interactive (fsi.exe) Reference section Differences Between the Interactive, Scripting and Compiled Environments gives some more context. | https://social.msdn.microsoft.com/Forums/en-US/97427dec-b8ca-429a-939b-99482f00555a/r-?forum=fsharpgeneral | CC-MAIN-2020-16 | refinedweb | 588 | 59.09 |
[+] Download Related Source code
Frankly, intrusion in to the private space of others is not so great. Mostly, you’ll get a kick in your ass, but at times, if you are lucky and if you are really smart, you’ll end up finding something really cool (Bond, James Bond).
For me, at times, when doing some hacks/exploration of compiled or third party assemblies, I end up wanting to initialize a private class or a class with a private or internal constructor. Or, at times, when dealing with pre-compiled legacy libraries that I can’t change - I want to write a couple of tests against a private method to understand how it works. I remember going through the source code of TFS power toys or so some time back - and I found that those guys are bringing up a lot of goodness by unearthing some private classes in the TFS library.
Still, I should warn you.
Warning (assume that this is in red): Private types, internals and private members are so because of some reason, and often you don’t want to mess with them directly. And if you do, chances are that you’ll break later, because there is no guarantee that the guys who created those assemblies will keep the private/internal implementations as such.
If you still don’t mind breaking the rules so that you can un earth some hidden potential against all the danger warnings - here is a quick wrapper class that’ll make the job easy using C# 4.0 dynamic features and reflection. And more than that, this is a good learning point to see how you can use reflection to initialize private types, invoke private/internal constructors, get/set private properties, invoke private methods etc.
1 – What we are talking about
To explain further what we’ll achieve, consider this simple example.
class Program { static void Main(string[] args) { //Note that the type of 'wrapper' is dynamic dynamic wrapper = new AccessPrivateWrapper(new ClassWithPrivateMembers()) ; //Let us access the private members wrapper.somePrivateField = "Field Val"; wrapper.SomePrivateProperty = "Property Val"; wrapper.DumpValues(); Console.ReadLine(); } class ClassWithPrivateMembers { private string somePrivateField; private string SomePrivateProperty { get; set; } private void DumpValues() { Console.WriteLine("Look ma, I'm accessing private members. Prop = " + SomePrivateProperty + ", Fld=" + somePrivateField); } } }
And if you run that, you’ll find that the dynamic wrapper is correctly setting the the private field and property values, and then invoking a private method in the class (DumpValues method), to print the result.
//Note that the wrapper is dynamic dynamic wrapper = AccessPrivateWrapper.FromType (typeof(SomeKnownClass).Assembly,"ClassWithPrivateConstructor"); //Access the private members wrapper.PrivateMethodInPrivateClass();
2 – What the heck is AccessPrivateWrapper
If you are wondering what exactly is AccessPrivateWrapper – it is a simple class we inherited from the System.Dynamic.DynamicObject class.
But before that If the keyword ‘dynamic’s not not familiar to you, I really suggest you to read this article I wrote earlier - C# 4.0 dynamic keyword – Under the hood
Coming back to DynamicObject -. The DynamicObject class has a few cool methods for you to override. For now, we are only interested in these members:
- TryInvokeMember - Provides the implementation of calling a member.
- TrySetMember - Provides the implementation of setting a member.
- TryGetMember - Provides the implementation of getting a member.
So, we are inheriting our AccessPrivateWrapper from the DynamicObject class, and overriding these methods to access private and public methods, properties and fields via reflection (I hope you know the fact that via reflection, you can invoke, set and get the values of even private and internal members).
Have a look at the implementation of AccessPrivateWrapper
/// <summary> /// A 10 minute wrapper to access private members, havn't tested in detail. /// Use under your own risk - amazedsaint@gmail.com /// </summary> public class AccessPrivateWrapper : DynamicObject { /// <summary> /// The object we are going to wrap /// </summary> object _wrapped; /// <summary> /// Specify the flags for accessing members /// </summary> static BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; /// <summary> /// Create a simple private wrapper /// </summary> public AccessPrivateWrapper(object o) { _wrapped = o; } /// <summary> /// Create an instance via the constructor matching the args /// </summary> public static dynamic FromType(Assembly asm,string type,params object[] args) { var allt = asm.GetTypes(); var t=allt.First(item=>item.Name==type); var types=from a in args select a.GetType(); //Gets the constructor matching the specified set of args var ctor = t.GetConstructor(flags, null, types.ToArray(), null); if (ctor != null) { var instance = ctor.Invoke(args); return new AccessPrivateWrapper(instance); } return null; } /// <summary> /// Try invoking a method /// </summary> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var types=from a in args select a.GetType(); var method = _wrapped.GetType().GetMethod (binder.Name,flags, null, types.ToArray(), null); if (method == null) return base.TryInvokeMember(binder, args, out result); else { result=method.Invoke(_wrapped, args); return true; } } /// <summary> /// Tries to get a property or field with the given name /// </summary> public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) { //Try getting a property of that name var prop = _wrapped.GetType().GetProperty(binder.Name,flags); if (prop == null) { //Try getting a field of that name var fld = _wrapped.Get.GetType().GetProperty(binder.Name, flags); if (prop == null) { var fld = _wrapped.GetType().GetField(binder.Name, flags); if (fld != null) { fld.SetValue(_wrapped,value); return true; } else return base.TrySetMember(binder, value); } else { prop.SetValue(_wrapped, value, null); return true; } } }
That looks simple, isn’t it? To detail that a bit, when ever user sets or gets a property or field on our dynamic object, the TrySetMember or TryGetMember will get called - and from there onwards, we use reflection to do the job of setting or getting the property or field value, regardless whether it is private or public. If a property of the given name doesn’t exist we’ll try to find a field of the given name to do the get or set operation.
Similarly, TryInvokeMethod will get fired when the user tries to invoke a method via our dynamic wrapper. We fetch the method matching the type of arguments, to obtain the correct overload, and then do the job via reflection. Make sure you download the code from the above link, and debug through a bit.
Also, pay some special attention to the FromType method that we used earlier. Basically, it’ll find the type to create an instance of, and then will find the constructor to invoke, based on the given arguments.
More Thoughts
Now, what about Unit testing your private members? Ever wanted to do that? That is not a common scenario, but at times, as I mentioned earlier, you might be dealing with a legacy system and you want to write a couple of tests against some of the private methods. Oh yes, you can use the AccessPrivateWrapper to do that.
Note that the above implementation don’t work with libraries that are obfuscated, because we are relying on reflection.
Also, the above implementation won’t access inherited private or internal members. That is pretty simple to implement, but that is an exercise for you ;)
Conclusion
A related tip: You can use InternalsVisibleTo attribute to grant access to the internal members of the target assembly to your caller assembly, if you’ve access to both the assemblies. This is useful, especially when you do unit testing.
Also, check out my other C# 4.0 dynamic tricks
Happy Coding!! | http://www.amazedsaint.com/2010/05/accessprivatewrapper-c-40-dynamic.html | CC-MAIN-2014-15 | refinedweb | 1,226 | 54.73 |
Hello Friends!
Today I am going to share very important code for ListView into ScrollView.
Many Android developers says: “You should not put a ListView in a ScrollView because a ListView already a scrollview.
But some times its really needed in project “ how can place a ListView into a ScrollView without it collapsing to its minimum height?”
And finally I got it on stack over flow-
I waste a lot of time in goggling so I don’t want some one do same so you can follow my blog
step by step-
UPDATE: Please check my this post for in case any of issue-
step by step-
UPDATE: Please check my this post for in case any of issue-
PrintScren:
Step1- Create an Activity name-MainActivity.java and create a listview.
package com.example.scrollviewlistviewdemo;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private String listview_array[] = { "ONE", "TWO", "THREE", "FOUR", "FIVE",
"SIX", "SEVEN", "EIGHT", "NINE", "TEN" };
ListView myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.listView);
myList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listview_array));
Helper.getListViewSize(myList);
}
}
Step2- Create main.xml-
<ScrollView xmlns:android=""
xmlns:tools=""
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="19dp"
android:
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:
</LinearLayout>
</ScrollView>
Step3- Finally and important thing create another class Helper.java and put below given code-
package com.example.scrollviewlistviewdemo;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
public class Helper {
public static void getListViewSize(ListView myListView) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
//setting listview item in adapter
ViewGroup.LayoutParams params = myListView.getLayoutParams();
params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
Log.i("height of listItem:", String.valueOf(totalHeight));
}
}
Hope it will help you thanks!
HI Manish, nice blog could you please let me know your contact info.
Hi Abhay, Thanks for your comment you can find me on my blog "About Me" page..
Thanks,
thanks work great!
your welcome!
*you're
Hi ,
Plz give me sample how to get gridview insode scroll view. It is one of my modulus.
Thanx Manish Srivastava !!! It works properly !! Thanx again..
Parwinder
your welcome..
*you're
I'm getting this error in my application:
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:493)
at android.view.View.measure(View.java:15513)
(...)
Can you help me? Thanks a lot
Hi!
Its seems you are trying to add a view into your Relative Layout? If yes please don't add it in xml file just create a view in xml and add it in your activity.
Or some thing else? let me know in detail? what are you doing in your code? only Log cat is not enough to find out bug..
Thanks,
Hi, your Helper's classe is awsome.
But for some phone, i have a FATAL EXCEPTION :
FATAL EXCEPTION: main
java.lang.NullPointerException at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:465)
at android.view.View.measure(View.java:15172)
at net.coopcom.citegreenui.adapters.Helper.getListViewSize(Helper.java:23).
What can i do ?
My XLM File :
I am getting nullpointer exception in below line:
listItem.measure(0, 0);
@Sarojini can you share your log cat?
Hi Manish, in my listview I have rows with different height and the method getMeasuredHeight in for loop returns same height for every row. Do you have any idea why it returns wrong height? Thanks a lot
Hi Tomas, I think you are working on custom list-view using custom adapter - BaseAdapter or ArrayAdapter.
So also in this case my demo is working fine. Because I am getting size of adapter not a list-view..
So if you have demo app please mail me I will try to short out your problem.
Thanks,
Manish
Thank you, but I found almost the same solution here .
Then what you want from me? do you want promote above link here? Jamal thanks for your nice suggestion, I appreciate your R&D but my code is working Okay for every case , I mean simple list view and custom list view both..
Infect my one reader getting some other type of issue but I have no time for R&D. If you really want to help me try one thing just change array item size like-
private String listview_array[] = { "ONEkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkkk", "TWO", "THREE", "FOUR", "FIVE","SIX", "SEVEN", "EIGHT","NINEhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh", "TEN" };
Now you will see you are not getting all list-view item correctly. Problem is measurement of Adapter If you can see on it please check it..
Thanks,
Hi Manish,
Thanx for such a wonderful tutorial, actually i was facing a problem for custom listView while calculating measure.
But....
Hi Jamal,
Thanx for such a good point while using custom adapter like viewgroup.
I used both of yours code, it working nice to me for custom adapter.
Thank you once again :)
Hello Sudhir!
Thanks for your comment...
Have you got any solution? Please post here..
Thanks a lot..
Hi Srivastava how are u ?
that's true i had the same problem using BaseAdapter, i didn't get the real size of the list beacuse the size of textview change on the layout row of the list, and i'm always looking for solution.
Please try at your end and when I will got any solution I will inform you..
Well we can try simple View instead of List-view into scroll-view in this case :)
Wow, It works properly !! Thanks Manish and nice blog,
Your welcome!
Hello manish,
Nice blog, but i have a Question that, if i use Your class then it automatically scrolls down to listview, eventhough i am having some component on top, the view gets automatically scrolled at listview first index.
I wanted to know if i can keep the view at top position only.
I am not sure but try something like that-
scrollViewEventDetails.fullScroll(View.FOCUS_UP);//if you move at the end of the scroll
scrollViewEventDetails.pageScroll(View.FOCUS_UP);//if you move at the middle of the scroll
Well i have tried this, but not yet successfull...
Please search on google and stack overflow...and please put your answer here also so other can get help from your comment..
Thanks..
nice work very useful info thanks
One thing is if you Use Runnable Method and inside it use your function. Keep sleep for 1 second, then the problem gets solved, the top view is always displayed, but it is not correct.
Will definitely post here if i get a proper solution.
Thank You.
your most welcome I am waiting for your solution..
Thanks,
I'm got error like this
06-06 18:15:17.709: E/AndroidRuntime(9685): FATAL EXCEPTION: main
06-06 18:15:17.709: E/AndroidRuntime(9685): java.lang.NullPointerException
06-06 18:15:17.709: E/AndroidRuntime(9685): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:470)
06-06 18:15:17.709: E/AndroidRuntime(9685): at android.view.View.measure(View.java:15367)
06-06 18:15:17.709: E/AndroidRuntime(9685): at com.truelife.tvtalk.TopicDetailHelper.getListViewSize(TopicDetailHelper.java:20)
I use listview that set getview in myadapter class
my code in Activity
mAdapter = new TopicDetailCommentAdapter(this, MyArrList);
listView1.setAdapter(mAdapter);
TopicDetailHelper.getListViewSize(listView1);
and my adapter class
public class TopicDetailCommentAdapter extends BaseAdapter {
private Context context;
private ArrayList> data;
private static LayoutInflater inflater = null;
public TopicDetailCommentAdapter(Context ct,
ArrayList> d) {
data = d;
context = ct;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View rowView = convertView;
HashMap dataValue = new HashMap();
dataValue = data.get(position);
if(rowView == null) {
rowView = inflater.inflate(R.layout.topic_detail_item, null);
}
try {
ImageView imgViewAvatar = (ImageView) rowView.findViewById(R.id.ColAvatarComment);
TextView txtComment = (TextView) rowView.findViewById(R.id.CommentDetail);
TextView txtDateCreate = (TextView) rowView.findViewById(R.id.CommentCreated);
final String userId = dataValue.get("user_id");
String is_edit = dataValue.get("is_edit");
final String boardId = dataValue.get("board_id");
final String topicId = dataValue.get("topic_id");
txtComment.setText(dataValue.get("CommentDetail"));
txtDateCreate.setText(dataValue.get("CommentCreated"));
String filename = dataValue.get("ColUserAvatar");
if (filename != "") {
ImageLoader.getInstance()
.load(imgViewAvatar, filename, true);
}
} catch (Exception e) {
e.printStackTrace();
}
return rowView;
}
}
Your code is looking okay only one doubt here-
1)where you have set your row layout? I can't see in you activity class nor CustomAdapter class..
Please do one thing first remove scrollview and without measure it run your app.. is it working fine or not let me know please?
Hello this solution is not working for my code..please help.I am inserting items in list view dynamically..for dynamic insertion of items it is not working..It is working for static insertion of items
Please try this article, it will work 100%-
the man like you are rare thank you so much manish this code really very much help for me
thanks
Thanks Rajesh!
this method works but the last item of list is not completely visible.
yes some cases this not work fine..
Thank you. A very good example.
Thanks!
Hi Manish,
How can you access the non visible items of listview??
> I have a list view which contains some 20 odd items along with a check
> box. I am trying to set all the checkboxes when the first checkbox is clicked or checked,
> iam getting NullPointerException at below written code, present inside the OnCheckedChange listener:
>
> CheckBox cbox= (CheckBox) view.getChildAt(j).findViewById (R.id.alarmCheck);
>
> here view.getChildAt(j) comes null, which is valid since the views are not visible and hence are not instantiated...
> > Now if I have six elements in this ViewList, which are visible on the
> > emulator, then the same code just works fine.
> > Problem arises when the list is long and it starts scrolling and some
> > element are not visible.
> > I am working on this problem for some days, any help will be highly
> > apperciated.
I am not sure why this issue happening and what you trying to do actually..
But in case of ListView, listview load only that part which part is visible and on scroll when top portion or bottom portion are invisible that will not load by listview. I think that make issue in your case.
So my idea is that assign a value to all checkbox at the time of declaration time don't leave it null. Hope that will work for you or try to do something like that-
if(chkBox1!=null){
//add into listview
}
Thanks,
Manish
Great job...
Thanks Dear!
Hi manish, could you answer please how i can do same thing for ExpandableListView
Sorry Dear I have no idea, You can try by yourself..
If you got any thing positive please let me know, I will thankful to you..
Thanks!
This comment has been removed by the author.
This comment has been removed by the author.
This is not working in my case can u please help me My layout is......
Scrollview
linearlayout
framelayout
viewpager
viewpagerindicator
framelayout
listview
progressbar
linearlayout
Scrollview
Very complex layout, i am not sure it will work or not.. Please test it at your end.
Thanks,
I have tested it at my end...it is not scrolling...full container.
again it is scrolling listview only...
tengo la siguiente estructura
ScrollView
LinearLayout
TextView
ListView
TextView
/ScrollView
/LinearLayout
/TextView
/ListView
/TextView
Pero me deja mucho espacio debajo del Listview, quizas unos 10 cms antes de mostrar el TextView, alguna solución.
Acá el xml completo
this is the corrected structure
ScrollView
LinearLayout
TextView
/TextView
ListView
/ListView
TextView
/TextView
/LinearLayout
/ScrollView
It is looking okay and it should scroll.
This is a bad solution guy. That Helper class loads all the views, therefore the ListView is not recycling its views. You will run into performance issues if you've got a large dataset and then throw in if each row view dowloads images via a webservice. The app will crash miserable. There's always repercussions using hack methods of doing stuff. The folks at Google know why they categorically stated that wrapping a ListView in a ScrollView is not a suitable design pattern. Guys be careful copying and pasting code!
Yes you are right. It is not right solution. But some time if needed you can use this method, measure list-view adapter. Best way is linear layout instead of list-view inside scroll-view.
Thanks!
Thanks Dear Manish..Good thoughts ...
Thanks dear and your Welcome!
This is working but since I am using a GridView, I can't seem to get the right totalHeight of my GridView. How do I calculate it properly?
Sorry dear its have issue with custom views. Its give us wrong measurement. Please try another logic don't use listview inside scrollview.
Please try @Jamal Comment hope it will help you. last guys commented that its work for him- mani
your code is nice its working fine.but my prblm is when i am scrollling down its keep on coming even if no content.i am not getting y its behaving like this.
which type of listview do you have simple or custom?
Thanks Jamal your answers really helps me to come out of this problem.
Sajad, thanks for response back it will help to others.. Really Thanks!
Welcome dear Manish,Nice job from you as well.......thanks
Hey Dude Thanksssss it workssss!!!
Your welcome dear!
Manish i got a problem here that the last item does't display compleatly .what is the problem ?
I have already told that this is not good way to do thing listview inside scrollview. In case of custom views it does not work perfectly. well you have tried Jamal answer that did not help you?
it just total height problem..some how not able to get total height to draw all view...I added
2* (listItem.getMeasuredHeight()) and it working fine for me...tested it on emulator.
@Shubham he he he its totally "Indain Jugadh" not a developer logic. You did a great job, I appreciate your logic but in every case it will not work.. Anyway thanks for posting your answer..
thanks so much :) it works
Your welcome..
Hiii
Thanks Manish ....
This article helped me to solve my problem .............
Thanks and your welcome dear!
Nice post, helped me a lot, just one thing. When you are using your own adapter you have to use that adapter in the helper to get the correct size
any issue with that?
Hi Manish.
You resolved me a big thing... I'm very pleased... cheers, and keep going, you're fantastic!
Thanks and your welcome dear..
your blog is nice .. i m working on android appliacation i designed screen having radio buttons search edittext and buttons but when i m testing the application in mobile then keybord appear....and i cant see what i m selecting and typing in the edittext... so is there any way to scroll whole layout automatically when i m typing on keybord?? i have used many linearlayout in one root linearlayout....
It should automatic scroll. Is your page have custom view like custum gridview etc? If your page is big please use scrollbar as parent of all views.
Hi ,
Plz give me sample how to get gridview insode scroll view. It is one of my modulus.
Read more:
if you put gridview inside scroll-view any problem here?
The problem I am getting is when I mention layout_height attribute as wrap_content,fill_parent and match_parent it is showing only one row of the grid and it is giving a warning like "GridView and ListView should not be mentioned in ScrollView"
You are right we can't put any touch view inside other view like listview or gridview inside the scrollview. But try above logic may be it will help you. I have did it for listview just try above code for gridview may be it will work..
the above code works for me for GridView but the issue is I have a BaseAdapter class. I am getting problem in getting height of that adapter class. Please give me an idea on this.
BaseAdapter means? your CustomAdapter class which one is extend from BaseAdapter right? so you are not getting correct view?
Yes
I am giving code which I tried
public class NoteAdapter extends BaseAdapter {
private Activity activity;
private ArrayList> data;
private static LayoutInflater inflater=null;
int totalHeight = 0;
public NoteAdapter(Result result,
ArrayList> mylist) {
// TODO Auto-generated constructor stub
activity = result;
data=mylist;
//data2=mylist2;
//data3=mylist3;
System.out.println("Reminders is : "+data.size());
//System.out.println("Expense is : "+data2.size());
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView == null)
vi = inflater.inflate(R.layout.note_item, null);
TextView title = (TextView)vi.findViewById(R.id.name);// title
//TextView title1 = (TextView)vi.findViewById(R.id.name1);
HashMap event = new HashMap();
event = data.get(position);
//ListAdapter myListAdapter = myListView.getAdapter();
totalHeight += vi.getMeasuredHeight();
//totalHeight += data.size();
ViewGroup.LayoutParams params = title.getLayoutParams();
params.height = totalHeight + (title.getHeight()); /** (myListAdapter.getCount() - 1));*/
title.setLayoutParams(params);
System.out.println("Note data is : "+event);
title.setText(event.get(Result.KEY_NOTENAME));
//title1.setText(event.get(Result.KEY_NOTENAME));
return vi;
}
}
Please check
Well this is pretty good blog where I found some useful information especially about android app development that most important in now a days. I'd like to say thank for this stuff keep it up dear..!
Thanks Mike!
Thank you very much. it's good tutorial.
Your welcome!
How I can do to make the focus of this app up and not on the first result of the listview?
i think you should use android:focusable="false" or "true" in you scrollview.
very thank resolve my problems
Hi , This article is good. But i used ExpandableListView in the place of ListView. Then it is only scrolling expandable view, it not scrolling entire view. I have another LinearLayout contains two Buttons under Expandablelistview, those buttons are not scrolling. Could you help in out to fix it. My parent layout is ScrollView.
Thanks in advance.
Venkat K
thanks bro..........u made my day
hi Manish
i'm using a custom listview and height of that is fixed.. i.e. only one item should be visible, if we scroll then we can see the other elements.
Prob: I'm having a edit text, pick contact and add more contacts.
so if i click add more contacts then it will add to the listview and will display, this works fine with pick contacts but problem is with edit text if i enter the phone number.. it won't scroll.
Can you please suggest me a solution.
Thanks in adavance. :)
Try this link-
Hi Manish,
I have tried the your listview sample with GridView (through CustomAdapter extends with BaseAdapter). But it the height of the gridview is growing as too large while scrolling. Please give some suggestion For me.
Try to add your gridview into Linear some thing like this-
Thank!!!!! this solved my problem! omg, I had long been looking for a solution, thank again!
Your welcome and in case of any issue you can follow this article-
The code which you posted has flaw...you are saying that ListView and ScrollView works but in this code only ScrollView is working and not the ListVIew. Check to it......
Thank You
works like a charm! thank you ! :) :)
Dear Manish Srivastava,Thank you so so much. It is really working. You are so smart.
Super it's works..... but i have doubt. if i have 1,00,000 records in that list means it may cause stack overflow issues.
This comment has been removed by the author.
I am getting this error :
Caused by: java.lang.NullPointerException
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:493)
at android.view.View.measure(View.java:15609)
at app.plusconnect.com.plusconnect.helper.Helper.getListViewSize(Helper.java:21)
at com.plusconnect.app.profile.viewprofile.Profile_Details.onCreate(Profile_Details.java:75)
Helper class same as it is given in your code.
Profile_Details.java //my Activity Page
public class Profile_Details
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile__details);
ListView listSkills= (ListView) findViewById(R.id.listSkillDetails);
Helper.getListViewSize(listSkills); // Getting Error on this Line
}
Helper.Java
{ listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight(); //(Helper.java:21)
}
Please try this-
Good work man... Thumbs up for U
This comment has been removed by the author.
Dear Manish Srivastava,Thank you so so much. It is really working..... But i have some doubt.
I need a solution when list-items are of variable sizes, i.e. some textview that expand over multiple lines. Any suggestion?
Although the suggested getListViewSize(ListView myListView) methods work in most of the cases, in some cases, specially with a lot of items, I noticed that the last elements are not displayed.
Hi,
This will not work in case of the text's length vary, like 3 or 4 line text. The problem lied at the measure() method. You could check it by watch the value of getMeasuredWidth() and getMeasuredHeight(). When the items 's width are expected to match each other, it doesn't. In fact it will vary alot. So I think it's better to fix the width with the parent view's width.
Try Custom Listview using Linear Layout-
hello,
i have a listview inside a scroll view
i need to access that listview.
i am not able to get the position in the onitemclicklistner
how to get access of listview elemets in the scroll view
listview.OnItemClickListner is now working for you?
HI,
I am creating a custom listview using baseadapter with Pager.
I am adding the search edit text on the adapter in the same way as you defined but that edittext is not visible.
Could you tell me?
thanks
No Idea dear! Can you try on another device?
hi, the code works fine but when the listview is larger than the screen height, the app focus in the listview automatically and dont show the views above the list, i have to scroll up to see this, what can i do? thanks
Thanks Dude
Thank you very much! :)
please how to show app in (endless) infinite scroll view to show image and text.
Hi friends Please help me :: When i scroll down my checked items get unchecked in that activity where i access my phone contacts
Im sorry, but I´m very excited.. As say in Mexico: "Eres la pinche mera neta del planeta"
Amazing! work like a charm! thank you very much.
Your welcome :)
This comment has been removed by the author.
Manish bro Super solution i struggle for 2 days with this listview and scrollview finally this solution helps me thanks a lot ......
Thanks brother!
hello please tell me any one this code work with custom listview????
Yes it should work and if does not follow below link-
Thank you so much sir, Yes It works properly.Mad about your logic.
Manish, Can you please provide Helper Class code for RecylerView?
It really works... Thanx for the Post
working great !!! thanks for this post....
Great man !! Like a charm | http://www.androidhub4you.com/2012/12/listview-into-scrollview-in-android.html | CC-MAIN-2017-47 | refinedweb | 3,997 | 60.51 |
Important: Please read the Qt Code of Conduct -
C1083: Cannot open include file: 'QWebView': No such file or directory
I have included webkitwidgets and webkit in my .pro file.
But still I get the error mentioned in the title when I use:
#include <QWebView>
How can I fix this?
(Qt Creator 2.7.0 based on Qt 5.0.2 32bit, Win xp)
- Chris Kawa Moderators last edited by Chris Kawa
After you modify .pro file re-run qmake (menu Build-> Run qmake).
Oh, and make sure you're using Qt version that still has QWebView. It was deprecated and then removed in later versions.
Btw. QtCreator 2.7.0 is pretty old. Current version is 4.2.2. Have you thought about upgrading?
- mrjj Lifetime Qt Champion last edited by
@Panoss
If you want to use a newer of Qt, you should check out
Note. You can use a newer Creator even if you stay older Qt.
The version used for building Creator is not related to any version of Qt you have installed and
use to build your apps.
I did: menu Build-> Run qmake and it was fixed!
Thank you guys you were grate help!
(I have my reasons I wanna keep this version of Qt)
- mrjj Lifetime Qt Champion last edited by | https://forum.qt.io/topic/79248/c1083-cannot-open-include-file-qwebview-no-such-file-or-directory/4 | CC-MAIN-2021-04 | refinedweb | 216 | 84.57 |
Hi,
I’m concerned about the missing functions in HTML to word import.
There is no way to include css styles, most style tags at the tags are not imported ans so on.
Are you are developing here or is this a topic you are ignoring.
That’s not amazing.
Please give me an answer about these topics.
Greetings Christian
Hi,
Hi Christian,
<?xml:namespace prefix = o
Thanks for your inquiry. Could you please attach your HTML here for testing? I will check it and provide you more information.
We are planning completely rework our HTML import module to support more HTML features. But you should note that Aspose.Words was originally designed to work with MS Word documents. HTML format very differs from MS Word documents format. That is why some things in HTML are difficult to map to the corresponding things in MS Word documents.
Best regards, | https://forum.aspose.com/t/inserthtml-missing-functions/57596 | CC-MAIN-2022-21 | refinedweb | 149 | 77.84 |
/README.md
Demonstrates how to use the stripe_payment plugin.
For help getting started with Flutter, view our online documentation.
Add this to your package's pubspec.yaml file:
dependencies: stripe_payment: ^0.1.0
You can install packages from the command line:
with Flutter:
$ flutter packages get
Alternatively, your editor might support
flutter packages get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:stripe_payment/stripe_payment.dart';
We analyzed this package on May 17, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
Detected platforms: Flutter
References Flutter, and has no conflicting libraries. | https://pub.dev/packages/stripe_payment/versions/0.1.0 | CC-MAIN-2019-22 | refinedweb | 109 | 51.65 |
Compiler Error with Q_DECLARE_METATYPE
Hi fellow Qters,
I have a small class to describe a dataset, which I would like to use in the context of the model/view system and thus my class needs to act like a QVariant. I have read the Qt documentation of the respective classes and my code looks like this (simplified to the basic parts):
class Dataset { public: enum DatasetType { TypeA = 0, TypeB = 1, TypeC = 2, TypeD = 3, }; Dataset(); Dataset(const Dataset& _data); ~Dataset(); ... private: ... DatysetType m_type; ... } Q_DECLARE_METATYPE(Dataset)
After declaring Dataset a Metatype, I'm using it in my code like this:
... QVariant var; Dataset data; var.setValue(data); ...
When I'm trying to compile the code, I get this compile error, however:
/usr/include/QtCore/qmetatype.h(169): error: class "QMetaTypeId<Dataset *>" has no member "qt_metatype_id" static inline int qt_metatype_id() { return QMetaTypeId<T>::qt_metatype_id(); } ^ detected during: instantiation of "int QMetaTypeId2<T>::qt_metatype_id() [with T=Dataset *]" at line 230 instantiation of "int qMetaTypeId(T *) [with T=Dataset *]" at line 463 of "/usr/include/QtCore/qvariant.h" instantiation of "void qVariantSetValue(QVariant &, const T &) [with T=Dataset *]" at line 528 of "/usr/include/QtCore/qvariant.h" instantiation of "void QVariant::setValue(const T &) [with T=Dataset *]" at line 18 of "/home/goetz/Projects/playground/source/Shared/GUI/DatasetTreeModel.cpp" compilation aborted for /home/goetz/Projects/playground/source/Shared/GUI/DatasetTreeModel.cpp (code 2)
Has anyone seen this before and knows how to get around? I haven't found anything on google, that would help me out.
- mrjj Qt Champions 2016
Hi
@wieland suggested
he has this:
Q_DECLARE_METATYPE(Dataset)
but uses this:
QMetaTypeId<Dataset *> ( the :setValue(const T &) [with T=Dataset *] )
he needs a Q_DECLARE_METATYPE(Dataset*) too
Can you try that ?
Hi,
good idea, but adding Q_DECLARE_METATYPE(Dataset*) didn't help either. The same compiler error persits.
I have
#ifndef DATASET_H #define DATASET_H #include <QMetaType> class Dataset { public: enum DatasetType { TypeA = 0, TypeB = 1, TypeC = 2, TypeD = 3, }; Dataset(); Dataset(const Dataset& _data); ~Dataset(); private: DatasetType m_type; }; Q_DECLARE_METATYPE(Dataset) #endif // DATASET_H
and
#include "dataset.h" Dataset::Dataset() { } Dataset::Dataset(const Dataset &_data) { Q_UNUSED(_data) } Dataset::~Dataset() { }
and use it with this:
void MainWindow::on_pushButton_clicked() { QVariant var; Dataset data; var.setValue(data); qDebug() << var.canConvert(QMetaType::Bool); }
Can't reproduce the problem so far.
If I do this:
void MainWindow::on_pushButton_clicked() { QVariant var; Dataset * data = new Dataset; var.setValue(data); qDebug() << var.canConvert(QMetaType::Bool); }
I get a similar compile error, but that can be fixed by adding:
Q_DECLARE_METATYPE(Dataset*)
- mrjj Qt Champions 2016
Thank you @Wieland
Also tried it in Qt 5.7. mingw and it compiled and ran.
Just to be sure. Please delete the build folder completely and rebuild.
Just to be sure it's not just a typo, because I've noticed you made the same typo in your cross-posting on qtcentre: there needs to be a semicolon after your class definition (before the QT_DECLARE_METATYPE).
It's just a typo in the post. I do have a a semicolon after the class declaration and before the Q_DECLARE_METATYPE macro.
I've also tried to add Q_DECLARE_METATYPE(Dataset) and Q_DECLARE_METATYPE(Dataset*) without success. I still get the same compiler error.
- mrjj Qt Champions 2016
@tobiSF
There must be something more we dont see.
Can you try this test project that compiles for me
@mrjj, I downloaded the project and I could compile it. But only after I have removed the trailing coma from the enum and after putting a comment around this line
qDebug() << var.canConvert(QMetaType::Bool);
Otherwise the compiler would show the following error message:
mainwindow.cpp(12): error: no instance of overloaded function "QVariant::canConvert" matches the argument list argument types are: (QMetaType::Type) object type is: QVariant qDebug() << var.canConvert(QMetaType::Bool); ^ compilation aborted for mainwindow.cpp (code 2) Makefile:209: recipe for target 'mainwindow.o' failed make: *** [mainwindow.o] Error 2
But I guess the part that counts - the metatype declaration - seems to work.
Quick update, I have changed the following line
Dataset* data; QVariant child; child.setValue(data);
to this
Dataset* data; QVariant child = QVariant::fromValue(data);
and now it's compiling fine. Any idea what might cause this?
- kshegunov Qt Champions 2016
@tobiSF said in Compiler Error with Q_DECLARE_METATYPE:
You have:
Q_DECLARE_METATYPE(Dataset)
but then use a pointer to that type:
Dataset* data; QVariant child = QVariant::fromValue(data);
those are not interchangeable. It's evident even from your original post (as @Wieland noted):
instantiation of "void QVariant::setValue(const T &) [with T=Dataset *]" at line 18 of "/home/goetz/Projects/playground/source/Shared/GUI/DatasetTreeModel.cpp"
The instantiation is with a pointer to
Datasetnot with a
Datasetobject.
@kshegunov thanks, as you said, @Wieland pointed it out and I fixed that right away (without updating the code in the initial post, however. The compiler error persisted and only went away after switching from setValue(data) to QVariant::fromValue(data). Is still can't compile the code when I use the setValue method, but with the QVariant::fromValue I can do what I wanted to.
- kshegunov Qt Champions 2016
@tobiSF said in Compiler Error with Q_DECLARE_METATYPE:
I fixed that right away (without updating the code in the initial post, however
Sorry if I seem thick, but I don't see it. I saw you attempted to declare the pointer as a metatype, but not that you tried calling the function with an actual object. There seems to be some confusion, so I'll try to expand. I'm referring to this error:
instantiation of "void QVariant::setValue(const T &) [with T=Dataset *]" at line 18 of "/home/goetz/Projects/playground/source/Shared/GUI/DatasetTreeModel.cpp"
which suggests you instantiate
QVariant::setValuewith a pointer to the type, not with the actual type you intend to use. Do you mind providing line18 and the few preceding lines of
DatasetTreeModel.cpp(where the argument passed to the function is declared) exactly as it appears when you get the compile error? Because this error somehow doesn't correspond to the source sample you provided in the OP.
PS.
QVariant::setValueand
QVariant::fromValuedo exactly the same thing for non-qt types (i.e. the ones you declare).
@kshegunov to be more precise, I fixed the metatype declaration:
... Q_DECLARE_METATYPE(Dataset) Q_DECLARE_METATYPE(Dataset*) ...
I was and still am instantiating the QVariant with a pointer to the type and not an actual type, which is why the initial declaration of the type as metatype didn't work. Now that I have both declared as metatype, it works with pointers.
- kshegunov Qt Champions 2016
Ah, okay, so it's just me being dense. | https://forum.qt.io/topic/79741/compiler-error-with-q_declare_metatype | CC-MAIN-2017-51 | refinedweb | 1,096 | 55.74 |
.
Scala.meta
Setup
Getting started with scalameta is quite straightforward. You only need to add a dependency in your
build.sbt:
libraryDependencies += "org.scalameta" %% "scalameta" % "1.7.0"
Then in your code all you have to do is
import scala.meta._
Macro setup
The setup to write a macro is slightly more involved. First you need to separate repos as it’s not possible to use the macros annotations in the same project where they are defined. The reason is that the macros annotations must be compiled before they can be used.
Once compiled you don’t even need a dependency to scalameta to use your macros annotations, you only need a dependency to the project that declares the annotations.
The setup for the macros definition project is slightly more complex as you need to enable the macroparadise plugin but it’s just a single line to add to your
build.sbt.
addCompilerPlugin("org.scalameta" % "paradise" % "3.0.0-M8" cross CrossVersion.full)
Of course you can use sbt subprojects to create one subproject for the macro definition and one subproject for the application that uses the macros annotations.
lazy val metaMacroSettings: Seq[Def.Setting[_]] = Seq( addCompilerPlugin("org.scalameta" % "paradise" % "3.0.0-M8" cross CrossVersion.full), scalacOptions += "-Xplugin-require:macroparadise", scalacOptions in (Compile, console) := Seq(), // macroparadise plugin doesn't work in repl yet. sources in (Compile, doc) := Nil // macroparadise doesn't work with scaladoc yet. ) lazy val macros = project.settings( metaMacroSettings, name := "pbmeta", libraryDependencies += "org.scalameta" %% "scalameta" % "1.7.0" ) lazy val app = project.settings( metaMacroSettings, libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % Test ).dependsOn(macros)
Parsing
At the heart of scalameta is a high-fidelity parser. The scalameta parser is able to parse scala code capturing all the context (comments, word position, …) hence the high-fidelity.
It’s easy to try out:
scala> import scala.meta._ scala> "val number = 3".parse[Stat] res1: scala.meta.parsers.Parsed[scala.meta.Stat] = val number = 3 scala> "Map[String, Int]".parse[Type] res2: scala.meta.parsers.Parsed[scala.meta.Type] = Map[String, Int] scala> "number + 2".parse[Term] res3: scala.meta.parsers.Parsed[scala.meta.Term] = number + 2 scala> "case class MyInt(i: Int /* it's an Int */)".parse[Stat] res4: scala.meta.parsers.Parsed[scala.meta.Stat] = case class MyInt(i: Int /* it's an Int */)
Tokens
As you can see the parser captures all the details (including the comments). It’s easy to get the captured tokens:
scala> res4.get.tokens res5: scala.meta.tokens.Tokens = Tokens(, case, , class, , MyInt, (, i, :, , Int, , /* it's an Int */, ), )
Scalameta also captures the position of each token.
Trees
The structure is captured as a tree.
scala> res4.get.children res6: scala.collection.immutable.Seq[scala.meta.Tree] = List(case, MyInt, def this(i: Int /* it's an Int */), ) scala> res6(2).children res7: scala.collection.immutable.Seq[scala.meta.Tree] = List(, i: Int)
Transform
This is nice but it’s not getting us anywhere. It’s great to capture all these details but we need to transform the tokens in order to generate some code. This is where the
transform method comes in.
scala> "val number = 3".parse[Stat].get.transform { | case q"val $name = $expr" => | val newName = Term.Name(name.syntax + "Renamed") | q"val ${Pat.Var.Term(newName)} = $expr" | } res8: scala.meta.Tree = val numberRenamed = 3
Quasiquotes
Here we have transformed a
Tree into another
Tree but instead of manipulating the
Tree directly (which is possible as well) we have use quasiquotes to both deconstruct the existing
Tree in the pattern match and construct a new
Tree as a result.
Quasiquote makes it much more convenient to manipulate
Trees. The difficulty (especially at the beginning) is too get familiar with all the scalameta ASTs. Fortunately there is a very useful cheat sheet that summarises them all.
Macros
With all this knowledge we’re now ready to enter the world of metaprogramming and write our first macro. Writing a macros is quite similar to the transformation we did above.
In fact only the declaration changes but the principle remains: we pattern match on the parsed tree using quasiquotes, apply some transformation and return a modified tree.
import scala.collection.immutable.Seq import scala.meta._ class Hello extends scala.annotation.StaticAnnotation { inline def apply(defn: Any): Any = meta { defn match { case cls@Defn.Class(_, _, _, ctor, template) => val hello = q"""def hello: Unit = println("Hello")""" val stats = hello +: template.stats.getOrElse(Nil) cls.copy(templ = template.copy(stats = Some(stats))) } } }
Here we just create an
@Hello annotation to add a method
hello (that prints
"Hello" to the standard output) to a case class.
We can use it like this:
@Hello case class Greetings() val greet = Greetings greet.hello // prints "Hello"
Congratulations! If you understand this, you understand scalameta macros. You can head over to the scalameta tutorial for additional examples.
PBMeta
Now that you understand scalameta macros we are reading to discuss the PBMeta implementation as it is built on these concepts.
It defines an annotation
@PBSerializable to add implicit
PBReads and
PBWrites into the companion object of the case class.
The pattern match is used to detect if the companion objects already exists or if we have to create it. The third case is for handling Scala enums.
defn match { case Term.Block(Seq(cls@Defn.Class(_, name, _, ctor, _), companion: Defn.Object)) => // companion object exists ... case cls@Defn.Class(_, name, _, ctor, _) => // companion object doesn't exist ... case obj@Defn.Object(_, name, template) if template.parents.map(_.syntax).contains("Enumeration()") => // Scala enumeration ... }
Note how we check that the object extends
Enumeration. We don’t have all the type information available at compile time (there is no
typer phase run as part of the macro generation – that’s why scalameta is quite fast). As we don’t have the whole type hierarchy available the only check we can do is if the object extends
Enumeration directly. (If it does indirectly we’re not going to catch it! – probably something we can do with the semantic API).
All the remaining code is here to generate the
PBReads and
PBWrites instances.
PBWrites
PBWrites trait defines 2 methods:
write(a: A, to: CodedOutputStream, at: Option[Int]): Unitwrites the given object
ato the specified output stream
toat index
at. The index is optional and is used to compute the tag (if any).
sizeOf(a: A, at: Option[Int]): Intcomputes the size (number of bytes) needed to encode the object
a. If an index
atis specified the associated tag size is also added into the result.
Quasiquotes are used to generate these methods:
q""" implicit val pbWrites: pbmeta.PBWrites[$name] = new pbmeta.PBWrites[$name] { override def write(a: $name, to: com.google.protobuf.CodedOutputStream, at: Option[Int]): Unit = { at.foreach { i => to.writeTag(i, com.google.protobuf.WireFormat.WIRETYPE_LENGTH_DELIMITED) to.writeUInt32NoTag(sizeOf(a)) } ..${params.zipWithIndex.map(writeField)} } override def sizeOf(a: $name, at: Option[Int]): Int = { val sizes: Seq[Int] = Seq(..${params.zipWithIndex.map(sizeField)}) sizes.reduceOption(_+_).getOrElse(0) + at.map(com.google.protobuf.CodedOutputStream.computeTagSize).getOrElse(0) } } """
In case you’re wondering what the
..$ syntax is, it’s just how to deal with sequences in quasiquotes.
Here a create a collection of
Term.Apply to write each field into the
CodedOutputStream. The
..$ syntax allows us to directly insert the whole sequence into the quasiquote.
(Similarly there is a
...$ syntax to deal with sequences of sequences).
PBReads
PBReads instances are generated in a similar way. The idea is to generate code that will extract field values from the
CodedInputStream and create a new instance of the object with the extracted field at the end.
val fields: Seq[Defn.Var] = ctor.paramss.head.map(declareField) val cases: Seq[Case] = ctor.paramss.head.zipWithIndex.map(readField) val args = ctor.paramss.head.map(extractField) val constructor = Ctor.Ref.Name(name.value) q""" implicit val pbReads: pbmeta.PBReads[$name] = new pbmeta.PBReads[$name] { override def read(from: com.google.protobuf.CodedInputStream): $name = { var done = false ..$fields while (!done) { from.readTag match { case 0 => done = true ..case $cases case tag => from.skipField(tag) } } new $constructor(..$args) } } """
IDE Support and debugging
In theory macros extension are supported in IntelliJ Idea. From what I experienced while developing PBMeta it works great with simple cases (e.g. adding a method to an existing case class) and it’s great as it allows you to expand to annotated class and see the generated code. Of course it’s great to debug and see what code is actually executed.
However it fails in more complex situations (e.g. creating a companion object):
In this case you’re left with inserting debug statements (i.e.
println) in the generated code. It’s simple and powerful but don’t forget to clean them up when debugging is over.
Conclusion
Scalameta is an amazing tool, it makes meta-programming easy and enjoyable. However there are some shortcomings you need to be aware of:
- You need to get familiar with all the quasi quote paraphernalia. There are many different terms but once you start to know them things got much easier. Plus you can try things out in the console.
- IDE support is great … when it works. When it doesn’t debugging isn’t easy and you’re left with generating
printlnstatement in your code. Not ideal!
- Scalameta doesn’t provide all the type analysis performed by the compiler. Yet we can do amazing things with the available information. Plus it’s fast (no heavy type inference needed)!
I used PBMeta as an introduction to Scalameta and without any knowledge I managed to build all the functionality I wanted. I even managed to add custom field position with the
@Pos annotation. The only thing I missed is the support for
sealed trait mapping to protobuf
oneOf structure.
For more details you can head over to PBMeta, try it out and let me know what you think in the comments below. | http://www.beyondthelines.net/computing/generating-protobuf-formats-with-scala-meta-macros/ | CC-MAIN-2017-26 | refinedweb | 1,663 | 60.92 |
We've drawn shapes so far using data internal to the program. In our Sketcher program we want to be able to draw a shape using the mouse in the view, and then store the finished shape in the model. We want the process to be as natural as possible, so we'll implement a mechanism that allows you to draw by pressing the left mouse button (more accurately, button 1) and dragging the cursor to draw the selected type of shape. So for a line, the point where you depress the mouse button will be the start point for the line, and the point where you release the button will be the end point.
As you drag the mouse with the button down, we'll display the line as it looks at that point. Thus the line will be displayed dynamically all the time the mouse cursor is being dragged and the left button remains pressed. This process is called rubber-banding.
We can use essentially the same process of pressing the mouse button and dragging the cursor for all four of our shapes. Thus two points will define each shape – the cursor position where the mouse button is pressed, and the cursor position where the mouse button is released, (plus the color for the shape, of course). This implies that our shape constructors will all have three parameters, the two points and the color. Let's look at how we handle mouse events to make this work.
Because all the drawing operations for a sketch will be accomplished using the mouse, we must implement the process for creating elements within the methods that will handle the mouse events. The mouse events we're interested in will originate in the SketchView object because that's where we'll be drawing shapes. We will make the view responsible for handling all its own events, which will include events that occur in the drawing process as well as interactions with existing shapes.
Drawing a shape, such as a line, interactively will involve us in handling three different kinds of mouse event. Let's summarize what they are, and what we need to do when they occur:
You'll remember from the previous chapter that there are two mouse listener interfaces: MouseListener which has methods for handling events that occur when the mouse buttons are pressed or released and MouseMotionListener which has methods for handling events that arise when the mouse is moved. You will also recall that the MouseInputAdapter class implements both, and since we need to implement methods from both interfaces, we'll add an inner class to the SketchView class that extends the MouseInputAdapter class.
Since there's quite a lot of code involved in this, we will first define the bare bones of the class to handle mouse events, and then build in the detail until it does what we want.
Add the following class outline as an inner class to SketchView:
import javax.swing.JComponent; import java.util.*; // For Observable, Observer, Iterator import java.awt.*; // For Graphics, Graphics2D, Point import java.awt.event.MouseEvent; import javax.swing.event.MouseInputAdapter; class SketchView extends JComponent implements Observer { // Rest of the class as before class MouseHandler extends MouseInputAdapter { public void mousePressed(MouseEvent e) { // Code to handle mouse button press... } public void mouseDragged(MouseEvent e) { // Code to handle the mouse being dragged... } public void mouseReleased(MouseEvent e) { // Code to handle the mouse button being release... } private Point start; // Stores cursor position on press private Point last; // Stores cursor position on drag private Element tempElement; // Stores a temporary element } }
We have implemented the three methods that we will need to create an element. The mousePressed() method will store the position of the cursor in the start member of the MouseHandler class, so it will be available to the mouseDragged() method that will be called repeatedly when you drag the mouse cursor with the button pressed. The mouseDragged() method will create an element using the current cursor position and the position saved in start, and store a reference to it in the tempElement member of the class. The last member will be used to store the cursor position when mouseDragged() is called. Both start and last are of type Point since this is the type that we will get for the cursor position, but remember that Point is a subclass of Point2D, so you can always cast a Point reference to Point2D when necessary. The process ends when you release the mouse button, causing the mouseReleased() method to be called.
An object of type MouseHandler will be the listener for mouse events for the view object, so we should put this in place in the SketchView constructor. Add the following code at the end of the existing code:
public SketchView(Sketcher theApp) { this.theApp = theApp; MouseHandler handler = new MouseHandler(); // create the mouse listener addMouseListener(handler); // Listen for button events addMouseMotionListener(handler); // Listen for motion events }
We call the addMouseListener()and addMotionListener() methods and pass the same listener object because our listener class deals with both. Both these methods are inherited from the Component class that also defines an addMouseWheelListener() method for when you want to handle mouse wheel events.
Let's go for the detail of the MouseHandler class now, starting with the mousePressed() method.
The first thing we will need to do is find out which button is pressed. It is generally a good idea to make mouse button operations specific to a particular button. That way you avoid potential confusion when you extend the code to support more functionality. This is very easy to do. The getButton() method for the MouseEvent object that is passed to a handler method returns a value of type int that indicates which of the three supported buttons changed state. It can return one of four constant values that are defined in the MouseEvent class, BUTTON1, BUTTON2, BUTTON3, or NOBUTTON, the last constant being the return value when no button has changed state in the current mouse event. On a two-button mouse or a wheel mouse, button 1 for a right-handed user is the left button and button 2 is the right button. Of course, these are reversed if you have a left-handed mouse setup. Button 3 is the middle button when there is one. We can detect when button1 is pressed by using the following code in the mousePressed() method:
public void mousePressed(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) // Code to handle button 1 press... }
A MouseEvent object records the current cursor position, and you can get a Point reference to it by calling the getPoint()method. For example:
public void mousePressed(MouseEvent e) { start = e.getPoint(); // Save the cursor position in start if(e.getButton() == MouseEvent.BUTTON1) { // Rest of the code to handle button 1 press... } }
This saves the current cursor position in the start field of our MouseHandler object. We save it before the if statement as we are likely to want the current cursor position available whichever button was pressed.
As well as saving the cursor position, our implementation of mousePressed() must set things up to enable the mouseDragged()method to create an element and display it. One thing the mouseDragged() method needs to know is whether button 1 is down or not. The getButton() method won't do this in this case since it records which button changed state in the event, not which button is down, and the button state won't change as a consequence of a mouse dragged event. We can store the state of button one when the mousePressed() method is called, though. Then it will be available to the mouseDragged() method. First, we need to add a suitable field to the MouseHandler class:
private boolean button1Down = false; // Flag for button 1 state
Now we can store the state when the mousePressed() method executes:
public void mousePressed(MouseEvent e) { start = e.getPoint(); // Save the cursor position in start if(button1Down = (e.getButton() == MouseEvent.BUTTON1)) { // Rest of the code to handle button 1 press... } }
The mouseDragged() method is going to be called very frequently, and to implement rubber-banding of the element each time, the redrawing of the element needs to be very fast. We don't want to have the whole view redrawn each time, as this will carry a lot of overhead. We need a different approach.
One way to do this is to draw in XOR mode. You set XOR mode by calling the setXORMode() method for a graphics context, and passing a color to it – usually the background color. In this mode the pixels are not written directly to the screen. The color in which you are drawing is combined with the color of the pixel currently displayed together with a third color that you specify, by exclusive ORing them together, and the resultant pixel color is written to the screen. The third color is usually set to be the background color, so the color of the pixel that is written is the result of the following operation:
resultant_Color = foreground_color^background_color^current_color
The effect of this is to flip between the drawing color and the background color. The first time you draw a shape, the result will be in the color you are drawing with, except for overlaps with other shapes, since they won't be in the background color. When you draw the same shape a second time the result will be the background color so the shape will disappear. Drawing a third time will make it reappear. We saw how this works back in Chapter 2 when we were discussing the bitwise exclusive OR operation.
Based on what we have said, we can implement the mousePressed() method for the MouseHander class like this:
public void mousePressed(MouseEvent e) { start = e.getPoint(); // Save the cursor position in start if(button1Down = (e.getButton() == MouseEvent.BUTTON1)) { g2D = (Graphics2D)getGraphics(); // Get graphics context g2D.setXORMode(getBackground()); // Set XOR mode g2D.setPaint(theApp.getWindow().getElementColor()); // Set color } }
If button 1 was pressed, we obtain a graphics context for the view, so we must add another member to the MouseHandler class to store this:
We use the object, g2D, to set XOR mode, as we will use this mode in the mouseDragged() method to erase a previously drawn shape without reconstructing the whole sketch. The last thing that is done here is to retrieve the current drawing color that is recorded in the SketchFrame object. You will remember that this is set when you select a menu item or a toolbar button. We use theApp object stored in the view to get the SketchFrame object, and then call its getElementColor() member to retrieve the color. This method doesn't exist in SketchFrame, but it's not difficult. Add the following method to the SketchFrame class definition:
public Color getElementColor() { return elementColor; }
With the button press code in place, we can have a go at implementing mouseDragged().
We can obtain the cursor position in the mouseDragged() method in the same way as for the mousePressed()method, which is by calling getPoint() for the event object, so we could write:
last = e.getPoint(); // Get cursor position
But then we only want to handle drag events for button 1, so we will make this conditional upon the button1Down field having the value true. When mouseDragged() is called for the first time, we won't have created an element, so we can just create one from the points stored in start and last, and then draw it using the graphics context saved by the mousePressed() method. The mouseDragged() method will be called lots of times while you drag the mouse though, and for every occasion other than the first, we must take care to redraw the old element before creating the new one. Since we are in XOR mode, drawing the element a second time will draw it in the background color, so it will disappear. Here's how we can do all that:
public void mouseDragged(MouseEvent e) { last = e.getPoint(); // Save cursor position if(button1Down) { if(tempElement == null) { // Is there an element? tempElement = createElement(start, last); // No, so create one } else { g2D.draw(tempElement.getShape()); // Yes – draw to erase it tempElement.modify(start, last); // Now modify it } g2D.draw(tempElement.getShape()); // and draw it } }
If button 1 is pressed, button1Down will be true so we are interested. We first check for an existing element by comparing the reference in tempElement with null. If there isn't one we create an element of the current type by calling a method, createElement(), that we will add to the SketchView class in a moment. We save a reference to the element that is created in the tempElement member of the listener object.
If tempElement is not null then an element already exists so we modify the existing element to incorporate the latest cursor position by calling a method modify() for the element object. We will need to add an implementation of this method for each element type. Finally we draw the latest version of the element referenced by tempElement. Since we expect to call the modify() method for an element polymorphically, we should add it to the base class, Element. It will be abstract in the Element class so add the following declaration to the class definition:
public abstract void modify(Point start, Point last);
Since we reference the Point class here we need an import statement for it in the Element.java file:
import java.awt.Point;
We can implement createElement() as a private member of the MouseHandler class, since it's not needed anywhere else. The parameters for the method are just two points that will be used to define each element. Here's the code:
private Element createElement(Point start, Point end) { switch(theApp.getWindow().getElementType()) { case LINE: return new Element.Line(start, end, theApp.getWindow().getElementColor()); case RECTANGLE: return new Element.Rectangle(start, end, theApp.getWindow().getElementColor()); case CIRCLE: return new Element.Circle(start, end, theApp.getWindow().getElementColor()); case CURVE: return new Element.Curve(start, end, theApp.getWindow().getElementColor()); default: assert false; // We should never get to here } return null; }
Since we refer to the constants identifying element types here, we must make the SketchView class implement the Constants interface, so modify the class to do that now. The first line of the definition will be:
class SketchView extends JComponent implements Observer, Constants
The createElement() method returns a reference to a shape as type Element. We determine the type of shape to create by retrieving the element type ID stored in the SketchFrame class by the menu item listeners that we put together in the previous chapter. The getElementType()method isn't there in the SketchFrame class yet, but you can add it now as:
public int getElementType() { return elementType; }
The switch statement in createElement() selects the constructor to be called, and as you see, they are all essentially of the same form. If we fall through the switch with an ID that we haven't provided for, we return null. Of course, none of these shape class constructors exists in Sketcher yet. So if you want to try compiling the code we have so far, you will need to comment out each of the return statements. The constructor calls imply that all our shape classes are inner classes to the Element class. We will see how to implement these very soon. But first, let's add the next piece of mouse event handling we need – handling button release events.
When the mouse button is released, we will have created an element. In this case all we need to do is to add the element referred to by the tempElement member of the MouseHandler class to the SketchModel object that represents the sketch. One thing we need to consider though. Someone might click the mouse button without dragging it. In this case there won't be an element to store, so we just clean up the data members of the MouseHandler object.
public void mouseReleased(MouseEvent e) { if(button1Down = (e.getButton()==MouseEvent.BUTTON1)) { button1Down = false; // Reset the button 1 flag if(tempElement != null) { theApp.getModel().add(tempElement); // Add element to the model tempElement = null; // No temporary now stored } if(g2D != null) { // If there's a graphics context g2D.dispose(); // ...release the resource g2D = null; // Set field to null } start = last = null; // Remove the points } }
When the button1 is released it will change state so we can use the getButton() method here. Of course, once button 1 is released we need to reset our flag, button1Down. If there is a reference stored in tempElement we add it to the model by calling the add() method that we defined for it and set tempElement back to null. It is important to set tempElement back to null here. Failing to do that would result in the old element reference being added to the model when you click the mouse button.
When we add the new element to the model, the view will be notified as an observer, so the update() method in the view will be called. We can implement the update() method in the SketchView class like this:
public void update(Observable o, Object rectangle) { if(rectangle == null) repaint(); else repaint((Rectangle)rectangle); }
If rectangle is not null, then we have a reference to a Rectangle object that was provided by the notifyObservers() method call in the add() method for the SketchModel object. This rectangle is the area occupied by the new element, so we pass this to the repaint() method for the view to add just this area to the area to be redrawn on the next call of the paint() method. If rectangle is null, we call the version of repaint() that has no parameter to redraw the whole view. Another important operation here is calling the dispose() method for the g2D object. Every graphics context makes use of finite system resources. If you use a lot of graphics context objects and you don't release the resources they use, your program will consume more and more resources. Under Windows for instance you may eventually run out, your computer will stop working, and you'll have to reboot. When you call dispose() for a graphics context object it can merely no longer be used, so we set g2D back to null to be on the safe side.
We have implemented all three methods that we need to draw shapes. We could try it out if only we had a shape to draw. | http://www.yaldex.com/java_tutorial/0411123598.htm | CC-MAIN-2017-30 | refinedweb | 3,087 | 59.94 |
A feature of the Sic interpreter is that it will use the `unknown'
built-in to handle any command line which is not handled by any of the
other registered built-in callback functions. This mechanism is very
powerful, and allows me to lookup unhandled built-ins in the user's
`PATH', for instance.
Before adding any modules to the project, I have created a separate
subdirectory, `modules', to put the module source code into. Not
forgetting to list this new subdirectory in the AC_OUTPUT macro
in `configure.in', and the SUBDIRS macro in the top level
`Makefile.am', a new `Makefile.am' is needed to build the
loadable modules:
AC_OUTPUT
SUBDIRS
## Makefile.am -- Process this file with automake to produce Makefile.in
INCLUDES = -I$(top_builddir) -I$(top_srcdir) \
-I$(top_builddir)/sic -I$(top_srcdir)/sic \
-I$(top_builddir)/src -I$(top_srcdir)/src
pkglib_LTLIBRARIES = unknown.la
pkglibdir is a Sic specific directory where modules will be
installed, See section Installing and Uninstalling Configured Packages.
pkglibdir
For a library to be maximally portable, it should be written so that it
does not require back-linking(47) to
resolve its own symbols. That is, if at all possible you should design
all of your libraries (not just dynamic modules) so that all of their
symbols can be resolved at linktime. Sometimes, it is impossible or
undesirable to architect your libraries and modules in this way. In
that case you sacrifice the portability of your project to platforms
such as AIX and Windows.
The key to building modules with libtool is in the options that are
specified when the module is linked. This is doubly true when the
module must work with libltdl's dlpreopening mechanism.
unknown_la_SOURCES = unknown.c
unknown_la_LDFLAGS = -no-undefined -module -avoid-version
unknown_la_LIBADD = $(top_builddir)/sic/libsic.la
Sic modules are built without a `lib' prefix (`-module'),
and without version suffixes (`-avoid-version'). All of the
undefined symbols are resolved at linktime by `libsic.la', hence
`-no-undefined'.
Having added `ltdl.c' to the `sic' subdirectory, and called
the AC_LIB_LTDL macro in `configure.in', `libsic.la'
cannot build correctly on those architectures which do not support
back-linking. This is because `ltdl.c' simply abstracts the native
dlopen API with a common interface, and that local interface
often requires that a special library be linked -- `-ldl' on linux,
for example. AC_LIB_LTDL probes the system to determine the name
of any such dlopen library, and allows you to depend on it in a portable
way by using the configure substitution macro, `@LIBADD_DL@'. If
I were linking a libtool compiled libltdl at this
juncture, the system library details would have already been taken care
of. In this project, I have bypassed that mechanism by compiling and
linking `ltdl.c' myself, so I have altered `sic/Makefile.am'
to use `@LIBADD_DL@':
AC_LIB_LTDL
dlopen
libtool
lib_LTLIBRARIES = libcommon.la libsic.la
libsic_la_LIBADD = $(top_builddir)/replace/libreplace.la \
libcommon.la @LIBADD_DL@
libsic_la_SOURCES = builtin.c error.c eval.c list.c ltdl.c \
module.c sic.c syntax.c
Having put all this infrastructure in place, the code for the
`unknown' module is a breeze (helper functions omitted for
brevity):
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <sys/types.h>
#include <sys/wait.h>
#include <sic/module.h>
#define builtin_table unknown_LTX_builtin_table
static char *path_find (const char *command);
static int path_execute (Sic *sic, const char *path, char *const argv[]);
/* Generate prototype. */
SIC_BUILTIN (builtin_unknown);
Builtin builtin_table[] = {
{ "unknown", builtin_unknown, 0, -1 },
{ 0, 0, -1, -1 }
};
BUILTIN_DECLARATION(unknown)
{
char *path = path_find (argv[0]);
int status = SIC_ERROR;
if (!path)
sic_result_append (sic, "command \"", argv[0], "\" not found",
NULL);
else if (path_execute (sic, path, argv) != SIC_OKAY)
sic_result_append (sic, "command \"", argv[0],"\" failed: ",
strerror (errno), NULL);
else
status = SIC_OKAY;
return status;
}
In the first instance, notice that I have used the preprocessor to
redefine the entry point functions to be compatible with libltdls
dlpreopen, hence the unknown_LTX_builtin_table
cpp macro. The `unknown' handler function itself looks
for a suitable executable in the user's path, and if something suitable
is found, executes it.
dlpreopen
unknown_LTX_builtin_table
cpp
Notice that Libtool doesn't relink dependent libraries (`libsic'
depends on `libcommon', for example) on my GNU/Linux system,
since they are not required for the static library in any case, and
because the dependencies are also encoded directly into the shared
archive, `libsic.so', by the original link. On the other hand,
Libtool will relink the dependent libraries if that is necessary
for the target host.
$ make
/bin/sh ../libtool --mode=compile gcc -DHAVE_CONFIG_H -I. -I. -I.. \
-I.. -I.. -I../sic -I../sic -I../src -I../src -g -O2 -c unknown.c
mkdir .libs
gcc -DHAVE_CONFIG_H -I. -I. -I.. -I.. -I.. -I../sic -I../sic -I../src \
-I../src -g -O2 -Wp,-MD,.deps/unknown.pp -c unknown.c -fPIC -DPIC \
-o .libs/unknown.lo
gcc -DHAVE_CONFIG_H -I. -I. -I.. -I.. -I.. -I../sic -I../sic -I../src \
I../src -g -O2 -Wp,-MD,.deps/unknown.pp -c unknown.c -o unknown.o \
>/dev/null 2>&1
mv -f .libs/unknown.lo unknown.lo
/bin/sh ../libtool --mode=link gcc -g -O2 -o unknown.la -rpath \
/usr/local/lib/sic -no-undefined -module -avoid-version unknown.lo \
../sic/libsic.la
rm -fr .libs/unknown.la .libs/unknown.* .libs/unknown.*
gcc -shared unknown.lo -L/tmp/sic/sic/.libs ../sic/.libs/libsic.so \
-lc -Wl,-soname -Wl,unknown.so -o .libs/unknown.so
ar cru .libs/unknown.a unknown.o
creating unknown.la
(cd .libs && rm -f unknown.la && ln -s ../unknown.la unknown.la)
$ ./libtool --mode=execute ldd ./unknown.la
libsic.so.0 => /tmp/sic/.libs/libsic.so.0 (0x40002000)
libc.so.6 => /lib/libc.so.6 (0x4000f000)
libcommon.so.0 => /tmp/sic/.libs/libcommon.so.0 (0x400ec000)
libdl.so.2 => /lib/libdl.so.2 (0x400ef000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000)
After compiling the rest of the tree, I can now use the `unknown'
module:
$ SIC_MODULE_PATH=`cd ../modules; pwd` ./sic
] echo hello!
command "echo" not found.
] load unknown
] echo hello!
hello!
] unload unknown
] echo hello!
command "echo" not found.
] exit
$ | http://www.makelinux.net/books/autobook-1.5/autobook_188 | CC-MAIN-2013-20 | refinedweb | 1,002 | 51.75 |
- Fred Brooks,Tcl C API, where the string value observed at the script level is part ofa structure that contains both the string representation and a typed interpretation. If this typed interpretation isn’t of the appropriate type for the current context, it is discarded and replaced with a new interpretation. A script can avoid thisshimmering by consistently using a value such that its interpretation remains the same.
Descriptionedit
In a Tcl script, every value is a string . This is rooted in the fact that a Tcl scriptis a string composed ofcommands. Each component of each command, from the name which is used to locate its routine, to the arguments that are passed to that routine, is therefore also a string.Script substitution in turn implies that the result of any command is a string as well. This set of circumstances implies that every value is a string. The phrases everything is a script , everything is a command , and everything is a word allude to this same aspect of Tcl.There is only one type of value: string . A command name is just a string that, by virtue of its position in a script, is used to locate a routine. When a command is evaluated, the values Tcl passes to the routine are not identifiers, numbers, functions, variables, lists, dictionaries, blocks of code, or special values likenull. They are merely strings. Apart from commands, there is nothing else in a script. No operators, no keywords. If there were, everything could not be a string, because values would have to be differentated by their type.In addition to strings, there are the substitutions, but those don’t represent other types of data. Rather, they indicate to the interpreter how to form the string prior to passing it to the command. Once those substitutions are performed, the values are still just strings.In other languages, the syntax might mandate that an operator occur in a certain position, or it might allow for either an identifier, a string, or a number at a certain position. That language then must use some syntactic cue to determine which of those types that thing is. Tcl has none of that. Consequently, it is free to use characters like double quote or braces for purposes other than indicating a string type or a block of code, respectively. Thus, although double quotes can be used such that they look like they are denoting strings, they aren’t. Braces can be used used such a way that they look like they denote a block of code, but they don’t. Not in the sense that braces inC denote a block of code. Those denotations occur in the mind of the human reader, and in the context of the routine to which they are passed, but they do not occur to Tcl. To Tcl, double quotes and braces merely change the context for determining which characters should be interpreted as substitutions or word delimiters.This simple and unified perspective on type is fundamental to the design of Tcl, and puts it in an exclusive category programming languages that do not have at least two data types that can be distinguished. The other languages in this category areforth, BCPL, andassembly language. Almost all other languages practice a form of tight coupling of data and metadata, where the value is a pattern of bits/bytes, and that pattern must be processed according to this data about the nature of the pattern. In the most common case, this metadata provides a type for the value. In Tcl, there is only the pattern, and it is the responsibility of the programmer to use each value in a sensible way. The programmer in turn is informed by an understanding of how each command works; how it interprets its input patterns, and what output pattern it returns. The programmer is free to uselists to compose structures from multiple values, and to dedicate components of such structures to describing other components in the structure, but this is all left to the programmer. Even alist is just another value/pattern, and only acquires meaning as a list when passed to a command that understands it that way. Tcl simply provides the framework for passing these values/patterns from command to command.In a Tcl script, a value has no properties. It is nothing more or less than a sequence ofcharacters. Therefore, according to the
, any two values that have same string representation are in fact the same value. Any extension that tries to peek under the hood and identify a value by some internal property other than its string representation is ill-behaved. On the other hand, it is perfectly fair for each command to interpret the same string representation in its own way.When Tcl evaluates a command, it performs three kinds of substitutions on the words of that command in order to derive the actual routine interprets each value passed to it as it sees fit. This is analogous toassembly language, where argument types are not checked by the assembler. Instead of sequences of bits, though, in Tcl the fundamental transactional unit between instructions is the string. This string veneer makes it easy to stretch Tcl over existing projects, providing a connecting layer between components. Each command is an entry point into a system of arbitrary complexity, and Tcl may beextended simply by adding new commands.Here are some examples of the interpretations routines give to the values passed to them:
- as a dictionary, or as the name of a dictionary.
- eval
- interprets its argument(s) as a script
Thus, we see that a string can be interpreted in many ways, e.g., as a number, a list, or even a script. If one desires more types, there are many such systems that have been built inTcl, and provide multi-type facilities. Seeobject orientation for a list of such systems. That’s the nice thing about Tcl. It provides fundamental mechanisms on top of which virtually any programming paradigm can be implemented.
What’s in a Stringedit
lists anddictionaries are strings that conform to a particular format. Other values are used ashandles fordata structures or resources that are not directly accessible at the script level. The following resources are accessed by name:
- variables
- namespaces
- arrays
- procedures
- channels
- Tk widgets
- encodings
- interpreters
Types in the World of Stringsedit
Programmers coming from languages where values are typed wonder how to get information about the type of a value in Tcl. The answer is, you don’t. Instead, each command specifies how it inteprets the words passed to it, and then behaves as specified. If the requisite information does not reasonably fit into the string representation of a value, then the value can instead be a name, which is then used as ahandle to reference some more extensive resourceedit
Tcl maintains atyped interpretation alongside the string representation of each value. Modifying the string representation invalidates the typed interpretation, and vice-veraa. For example, a list can be modified either by changing its string representation or by using a command likelappend, which works directly with typed interpretation if it is of list type.After either the string representation or the typed interpretation is invalidated it is only updated when needed. This way, a value can be passed between commands. At the implementation level, there may well be twoTcl_Obj structures with the same string representation, but they could be used interchangeable with no semantic impact. A user of Tcl’s C API will gain an appreciation for the way Tcl values are handled at the C level, working with either the string representation or the typed interpretation as is expedient.
The Magic of EIASedit
EIAS is one of the grand unifying concepts of Tcl. AsEdsger Dijkstra noted in
,Lisp, as a Tcl script itself morphs to become its own result.When everything is a string, every kind of data is readily accessible: When some new data type is introduced in a language likeC orJava, aTuring machine contains a finite string of symbols.Lambda calculus is manipulation of
production systems, which model computability by replacing parts of strings with other strings.NEM 2010-12-15: One aspect ofEIAS that is worth consideration is how it has kept Tcl "pure" in some sense. Part of EIAS that is little mentioned is that Tcl’s strings are immutable . This means that Tcl’s value space is purelyfunctional, in theHaskell sense. All side-effects are confined to the shadow world of commands and variables and other second-class entities. What this means is that Tcl now possesses some very powerful purely functional data-structures that are somewhat better than those available in other languages. For instance, I cannot think of another popular language that supplies O(1) purely functional dictionaries and lists (arrays) out of the box (or even in the library). Not to mention efficientUnicode and binary strings.
Peeking Behind the Curtainedit
DKF: See also tcl::unsupported::representation , which can peek behind this veil. If you use this, feel dirty!AMG: In testing and debugging high-performance applications I use this to confirm that I’m avoidingshimmering.
EIAS the Misunderstoodedit
Programmers more familiar with other language sometimes criticize Tcl’s EIAS design, usually because they assume that complex algorithms requiring data structures are asC features that make
in a possiblity. The data structures that others may think Tcl is missing are simply expressed in another way, but that is difficult to see at the outset.HoweverLV would like to point out that the true philosophy of Tcl says Do all that you can in Tcl – but then, do the rest in C/assembly/whatever and create glue and handles to it for Tcl.
Miscedit
Donald Porter remarked in theT,[A little Korean editor]? Of course, everything is aUnicUnicode instead ofASCII. 2003-05-13: Recently, Bruce Eckel in
, and Robert C. Martin in
talk about weak typing and dynamic languages.CL thinks these two make mistakes, but hasn’t time now to explain more. In any case, yes, these are good noteworthy references makeTk widgets serializable? I was thinking aboutxml2gui and wondering what it would take to make a widget produce anXMLGUITk 9.0 WishList, but I would certainly like to see whatever changes would be necessary to allow this (if it’s practical at all).jcw 2003-05-17: WhileEIAS is indeed a wonderfully powerful and flexible abstraction, I’d like to point out thatLISP’ers andSchemeLISP).NEM 2005-07-25: replying to this a couple of years too late… The difference withLisp is that cons cells aren’t universal; as I understand it, some basic data types like numbers are not represented as cons cells. You could build up everything from cons cells, in a similar way to building everything from set theory, butLPlaying TRAC. JE :
, or M , is anotherEIAS language.Forth and BCPL are also typeless, but there the fundamental type is a "cell" or native machine word instead of strings. (BCPL seems to be extinct, butForth and MUMPS are still around. (likeSmalltalk) to do some useful operations on objects and classes. I likeSnitreferences) such that a classifier (say [string is object …] ) could return a yes or no answer.Even better would be one that could tell which object system implemented the object (say [string is objectsystem …] ).This might be possible in a system likeJim if theJim References encoded the object system and whether something was an object.Even without add-on object systems, it would be nice to be able to determine if there could be [string is command …] , but that in some respects defeats the purpose ofunknown. (I’m still fuzzy from sleep, so maybe there is something that does this already, otherwise how wouldunknown get called?)Lars H 2005-07-24: I think the best way of pointing out how your analysis here is wrong is to point out that
- Tcl has no whattype command;unknown :
- What design error did you make that made you ask that question in the first place? Where did you (or someone else) throw away the information that you now find you need?
[*] Techincally, on the C level, most Tcl values kind of know from theirTcl_Obj internal representation whether they are command names, integers, variable names, etc., but it is more accurate to describe this information as if I’m a command name/integer/whatever, then I’m the name of that command/integer/whatever since this type information isshimmered away whenever theT usingSnit to delegate to some arbitrary objects), you don’t know (and as you pointed out, perhaps cannot know ) what object behavior a particular object (for which you have a string to use as areference) might exhibit.If I have a string, I can use winfo exists to see if it’sintrohandles,Interpreting TOOT has my earlier thoughts on the subject. I’ve been thinking about this some more since, and will hopefully soon have time to write some more code and an essay detailing my further thoughts. For now, I will point atMonpartial evaluation, a TOOT bundle of
type: value
canJava andJSON.
perform action on this input and then
- produce output.
- cause a side effect.
- produce output and cause side effect
- Raise an error.
See Alsoedit
- Everything is a Symbol
- the other side of the coin
- shimmering
- the discarding and regeneration of the internal typed representation of a value.
- Tcl_Obj
- homoiconic
- Is everything a list?
- How Tcl is special
- Uses the term, "stringly-typed language", not directly in reference to Tcl, but in a way very relevant to Tcl.
评论 抢沙发 | http://www.shellsec.com/news/26393.html | CC-MAIN-2017-47 | refinedweb | 2,261 | 60.85 |
Getting Started with Service Bus for Windows Server 1.1
Updated: November 5, 2013
Applies To: Service Bus for Windows Server 1.1
This section describes how to install Service Bus for Windows Server locally and set configuration options. Once Service Bus for Windows Server is running, you can follow a tutorial that shows how to create a queue, as well as some basic messaging operations. To start developing an application, see the Tutorial.
Install Service Bus for Windows Server
This section describes the basic steps required to set up Service Bus for Windows Server. Note the following prerequisites:
- All SQL instances are placed in a local SQL Server.
- The SQL Browser service must be enabled and running.
- TCP/IP must be enabled. This includes disabling the firewall on a specific port and enabling SQL Browser services.
- If you had an earlier version of Service Bus for Windows Server installed, see Upgrading Service Bus from Previous Releases.
- If you had previously installed Service Bus, make sure the following databases are deleted: SBGatewayDatabase; SBManagementDB; ServiceBusDefaultContainer.
- Services run with the current user credentials.
- The installation script requires a domain account.
- The Service Bus uses an auto-generated certificate.
Installing Service Bus
First, be sure to uninstall any existing Windows Fabric services as well as Service Bus. Then, do the following:
Using a Web Platform Installer public feed
Configure Service Bus for Windows Server
Configuring Service Bus using the Configuration Wizard
The steps required to configure a Service Bus for Windows Server 1.1 farm are similar to the ones specified here.
After the Web Platform Installer finishes, you can start the Service Bus configuration wizard. Use the following procedure:
- From the Start menu, click All Programs. Then click Service Bus 1.1. Click Service Bus Configuration to start the Service Bus configuration wizard.
The configuration wizard guides you through configuring a new Service Bus farm (cluster of servers), joining an existing farm, or leaving a farm that you have already joined. This getting started tutorial walks you through the farm creation process, with default settings.
The Service Bus configuration wizard uses the Service Bus PowerShell cmdlets for all the operations. You can use the wizard to set your farm properties, and then export the generated cmdlet script for future use. You cannot use the wizard to modify settings or to perform operations after the farm is created.
-. To verify that the instance name you have entered points to a valid instance, click Test Connection. If the connection is made correctly, a green check mark icon appears next to the button. If an error occurs, a message is displayed in the wizard.
- Under Configure Service Account, your user ID appears in the USER ID text box to identify the user account under which services run. Enter the password for that user ID in the PASSWORD text box. The wizard validates the user ID and password combination, and if it finds an error, notifies you to re-enter the user ID and password. The same user credentials are used for all Service Bus services.
- Under Certificate Generation Key, enter a key in the first text box, and then re-enter it in the text box under CONFIRM CERTIFICATE GENERATION KEY to confirm the first key you entered. Record the key for future use; you must Service Bus.
- If you want the Service Bus farm to be managed in the Windows Azure Pack portal, click Manage this farm with the Service Bus Management Portal.
- Set the username\password (not domain-joined user) for the portal to communicate with Service Bus. Note that you are required to provide two different sets.
- Click Next. The wizard displays the Summary screen, which lists the values that you entered, along with the default values for the remaining configuration options. The screen also displays the configuration options and values for the entire farm, an application, it may not be possible to unblock it. If it is not possible to continue with the default configuration, you must create a new farm with custom settings.
- Click Apply to approve the listed options, create the new farm, and add the server to the new farm. Click Back to return to the New Farm Configuration page and change the entries you have made.
Configure Service Bus in the Windows Azure Pack Admin Site
After a Service Bus for Windows Server farm is configured, you can connect it to a Windows Azure Pack management site to enable administrators and tenant to use Service Bus for Windows Server using the Windows Azure Pack tenant site.
You can start by setting up the Windows Azure Pack admin site or install it after you have configured the Service Bus for Windows Server farm.
- Install and configure the Windows Azure Pack admin site. See the Windows Azure Pack deployment guide here.
- Browse to the Windows Azure Pack Service Management Portal. Click New and then click Service Bus Clouds followed by Connect To.
- Provide a friendly, unique name by which the Service Bus cloud will be identified in the Windows Azure Pack site.
- Enter the Resource Provide endpoint of your farm. It should be similar to this:
- Enter the administrator and tenant username and password you provided when creating the farm (either in the new-sbFarm cmdlet or within the Service Bus for Windows Server configuration wizard).
- When you are successfully authenticated by the Service Bus for Windows Server farm, you can see the newly created Service Bus for Windows Server cloud in the Windows Azure Pack site.
Provision a Service Bus Namespace Using the Windows Azure Pack Site
Create a plan that includes Service Bus in the Windows Azure Pack administrator site. Do the following:
- In the Windows Azure Pack admin portal, click Plans, and then click Create Plan.
- Enable Service Bus in the newly created plan. Select the Service Bus cloud which will be offered as part of the plan.
- So that a tenant can use it, set the plan to be a public plan. Or, set an invitation code.
- Make sure to set the plan to allow unlimited subscriptions.
Configuring:
- Create a farm:
- Add a host to the farm
- Check status of the farm
- Create your first service namespace
If you need to reset the auto-generated key, issue the following PowerShell command:
Provision a Service Bus Namespace Using PowerShell (No Windows Azure Pack)
Check to see if you have created a service namespace by issuing the following Get-SBNamespace PowerShell command:
If no service namespace exists, create one by issuing the following New-SBNamespace PowerShell command:
This command creates a Service Bus service namespace named “DemoSB”.
Retrieve the Service Bus connection string by issuing the following Get-SBClientconfiguration PowerShell command: | https://msdn.microsoft.com/en-us/library/dn282152.aspx | CC-MAIN-2015-35 | refinedweb | 1,114 | 53.81 |
OpenVMS Alpha Version 8.2 is a major version release in which a number
of privileged data structures have changed. It might.4 Privileged Data Structures Updates
OpenVMS Version 8.2 contains updates for a number of privileged data
structures. These changes apply to both Alpha and I64
Note: On I64 systems, these versions are reported as
SYS$K_VERSION_xxxx.
The versions of these subsystems are linked into.4.1 KPB Extensions
Prior versions of OpenVMS supported the use of KPBs for kernel mode
above IPL 2. To make the transition to I64 easier, usage of KPBs has
been expanded for use in outer modes and all IPLs. This Alpha and I64
change allows certain code that previously had private threading
packages to make use of KPBs on both Alpha and I64. In order to support
these changes to kernel processes, some changes to the KPB structure
were required. No source changes should be necessary for existing Alpha
code.
5.4.2 CPU Name Space
OpenVMS currently has an architectural limit of a maximum CPU ID of 31.
Various internal data structures and data cells have allocated 32 bits
for CPU masks. We are increasing the amount of space allocated for
these masks to 64 bits for Alpha and 1024 bits on I64 to allow
supporting.4.3 64-Bit Logical Block Number (LBN)
OpenVMS today supports LBNs of only 31 bits. This limits our support of
a disk volume to 1 terabyte. The amount of space allocated for internal
LBN fields is being increased to 64 bits to allow support for larger
disk volumes in the future. The existing longword LBN symbols will
still be maintained and will be overlaid with a quadwords symbol.
5.4.4 Forking to a Dynamic Spinlock
In order. We are adding this capability. Code should
use the symbol FKB$C_LENGTH for the size of a FKB.
5.4 highly recommends that you use the provided internal
routines for linking and unlinking.4.4.7 Per-Thread Security Impacts Privileged Code and Device Drivers
Permanent Change
The method used for attaching as follows:
#include <security-macros.h>
/* Increment REFCNT of PSB that is now shared by both IRPs */
nsa_std$reference_psb( irp->irp$ar_psb );
Device drivers need to.5 Applications Using Floating-Point Data
The Itanium® I64, I64, refer to
the OpenVMS Floating-Point White Paper on the following website:
s.html.7.8. | http://h71000.www7.hp.com/doc/83final/6677/6677pro_prog.html | CC-MAIN-2015-18 | refinedweb | 398 | 56.55 |
I have a CSV file where fields are delimited with a comma. The fields of this CSV file contains the attributes of Permanent Survey Marks and I’ve created a GIS python script to convert it to a table that is stored it in our Enterprise GIS Spatial Database (SQL Server).
Within each row, there are some field’s that contain whitespace only. For example, part of a typical line shown here:
, ,N,NRM ,SP109773 , ,CK3693 , ,CK3543 ,
I discovered that these whitespace fields were being stored in the table as a string of whitespace characters. I needed to determine if each field had whitespace characters only and then make the script store these particular fields with a null value in the table. I came up with this function to do the job:
def isWhiteSpaceString(string): """ Check if string only contains whitespace characters. Input: string value Output: Returns True if string contains only whitespace characters otherwise returns False """ if (str == None): return False flag = 0 for char in string: if char == " ": continue else: flag = 1 break if flag == 0: # string only contains whitespace characters return True else: # string contains as least one alphanumeric character return False # ---------------------------------------------------------------------------- # a = 'abcdefg12345' b = 'abcdefg12345 ' c = ' abcdefg12345' d = '! ' e = ' ' print isWhiteSpaceString(a) print isWhiteSpaceString(b) print isWhiteSpaceString(c) print isWhiteSpaceString(d) print isWhiteSpaceString(e)
*** Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32. ***
>>>
False
False
False
False
True
>>>
This works but I’m looking for alternative solution that might be a little more compact or even more efficient. | https://www.daniweb.com/programming/software-development/threads/268714/determine-if-fields-of-a-csv-file-has-whitespace-characters-only | CC-MAIN-2018-13 | refinedweb | 263 | 65.56 |
Using .NET Dapper, I am having an issue getting a database field that contains an integer value (0/1) to map to a nullable boolean property in a class.
To keep things simple, I have stripped down and renamed the class to the bare minimum needed to reproduce the problem:
public class Test { public bool? TestField { get; set; } }
If the following code is called to populate the Test class:
var Results = DBConnection.Query<Test>("SELECT 0 As TestField]").ToList();
the following error will be thrown:
Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
If I remove the question mark, making the field a non-nullable boolean (i.e. public bool TestField), everything works fine.
The immediate answer might appear to remove the nullable and call it a day. However, the reason that won't work is because we are using this same class to serialize records to and from a web service, and we need to be able to tell the difference between false and null. I thought of having two classes, one with nullable property types, and one without, but then I have the added overhead of maintaining two classes instead of one.
A custom data transformation during a property set would be ideal. Though, I haven't found anything in the dapper documentation to suggest that this is even possible.
Looks like there may be an issue in the Dapper code regarding nullable bool/long, etc.
Here are three lines from the source code (lines 2375-2377 version 1.12.1.1). The issue is on the first line:
il.Emit(OpCodes.Ldtoken, unboxType); // stack is now [target][target][value][member-type-token] il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null); // stack is now [target][target][value][member-type] il.EmitCall(OpCodes.Call, typeof(Convert).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type) }), null); // stack is now [target][target][boxed-member-type-value]
When this code is emitted, it becomes equivalent to the following line of code:
Convert.ChangeType(0, typeof(bool?));
Unfortunately, this throws the error that I am seeing. By changing the first il.Emit( ) line above to the following:
il.Emit(OpCodes.Ldtoken, nullUnderlyingType ?? memberType); // stack is now [target][target][value][member-type-token]
The equivalent line of code generated becomes this, noting the typeof(bool?) at the end no longer has the nullable question mark after it:
Convert.ChangeType(0, typeof(bool));
This line of code does not throw an error.
So the solution was a recompile of the source. I will submit this change back to the project for them to review to see if this will cause any unwanted side effects. | https://dapper-tutorial.net/knowledge-base/16971087/-net-dapper-nullable-cast-error | CC-MAIN-2019-04 | refinedweb | 453 | 57.67 |
16 July 2008 15:25 [Source: ICIS news]
LONDON (ICIS news)--US diammonium phosphate (DAP) fertilizer production reached 699,000 short tons in June, down 12% month on month and down 1% year on year, according to data released by The Fertilizer Institute on Wednesday.
Production was thought to be down due to a combination of sulphur shortages and planned maintenance at Agrifos’s Pasadena DAP facility.
Monammonium phosphate (MAP) production reached 332,000 short tons, down 21% on May 2008 and down 7% on June 2007.
DAP inventories were 601,000 short tons, down 15% on May 2008, but up 9% on June 2007 levels. MAP inventories totalled 321,000 short tons, up 5% on May 2008 but down 7% on June 2007.
Total shipments - or producer disappearance - for DAP reached 803,000 short tons, down 6% on May 2008 but up 8% on June 2007. Increased DAP movement to ?xml:namespace>
Producer disappearance for MAP reached 316,000 short tons, down 46% on May 2008 and 16% on June 2007 | http://www.icis.com/Articles/2008/07/16/9093165/us-june-dap-production-drops-12-from-may.html | CC-MAIN-2014-52 | refinedweb | 172 | 67.79 |
Buy this book at Amazon.com
Code examples from this chapter are available from.
Python is an object-oriented programming language, which means
that it provides features that support object-oriented
programming.
It is not easy to define object-oriented programming, but we have
already seen some of its characteristics: Chapter 16, we defined a class named
Time and in Exercise 1, you
wrote a function named print_time:
print_time
class Time(object):
"""Represents the time of:
print_time(start)
start.print_time().
Rewrite time_to_int (from Section 16.4) as a method.
It is probably not appropriate to rewrite int_to_time as a
method; what object you would invoke it on?
time_to_int
int_to_time
Here’s a version of increment (from Section 16.3)
rewritten as a method:
# inside class Time:
def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)
This version assumes that time_to_int is written
as a method, as in Exercise.
is_after (from Exercise 2) is slightly more complicated
because it takes two Time objects as parameters. In this case it is
conventional to name the first parameter self and the second
parameter other:
is (short for “initialization”) is
a special method that gets invoked when an object is instantiated.
Its full name is __init__ (two underscore characters,
followed by init, and then two more underscores). An
init method for the Time class might look like this:
__init__
#.
Write an init method for the Point class that takes
x and y as optional parameters and assigns
them to the corresponding attributes.
__str__ is a special method, like __init__,
that is supposed to return a string representation of an object.
__str__.
Write a str method for the Point class. Create
a Point object and print it.
By defining other special methods, you can specify the behavior
of operators on user-defined types. For example, if you define
a method named __add__ for the Time class, you can use the
+ operator on Time objects.
__add__.
Write an add method for the Point class.
In the previous section we added two Time objects, but you
also might want to add an integer to a Time object. The
following is a version of __add__
that checks the type of other and invokes either
add_time or increment:
add_time
#:
__radd__
# inside class Time:
def __radd__(self, other):
return self.__add__(other)
And here’s how it’s used:
>>> print 1337 + start
10:07:17
Write an add method for Points that works with either a
Point object or a tuple: object’s:
__dict__
>>>.
print_attributes
The built-in function getattr takes an object and an attribute
name (as a string) and returns the attribute’s value.. Solution:
This exercise is a cautionary tale about one of the most
common, and difficult to find, errors in Python.
Write a definition for a class named Kangaroo with the following
methods:
pouch_contents
put_in_pouch
Test your code
by creating two Kangaroo objects, assigning them to variables
named kanga and roo, and then adding roo to the
contents of kanga’s pouch.
Download. It contains
a solution to the previous problem with one big, nasty bug.
Find and fix the bug.
If you get stuck, you can download, which explains the
problem and demonstrates a solution.
Visual is a Python module that provides 3-D graphics. It is
not always included in a Python installation, so you might have
to install it from your software repository or, if it’s not there,
from.)
read_colors
You can see my solution at.
Think Bayes
Think Python
Think Stats
Think Complexity | http://greenteapress.com/thinkpython/html/thinkpython018.html | CC-MAIN-2017-43 | refinedweb | 584 | 63.29 |
On 3/5/07, Phillip J. Eby <pje at telecommunity.com> wrote: > At 07:13 AM 3/5/2007 -0800, Bob Ippolito wrote: > >On 3/5/07, Christopher Fonnesbeck <fonnesbeck.mailing.lists at gmail.com> wrote: > > > I have been using bdist_mpkg to build Mac distributions of Numpy, > > Matplotlib > > > and other scientific programming packages. However, when I use > > bdist_mpkg to > > > build matplotlib, the resulting package is broken. In particular, I get: > > > > > > In [3]: import pylab > > > --------------------------------------------------------------------------- > > > exceptions.ImportError Traceback (most recent > > > call last) > > > > > > /Users/chris/<ipython console> > > > > > > > > /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/pylab.py > > > ----> 1 from matplotlib.pylab import * > > > > > > ImportError: No module named matplotlib.pylab > > > > > > Sure enough, when I look into the problem, it seems that the __init__.py > > > file is being left out by distutils. If I install directly using setup.py, > > > this does not occur. > > > > > > Any ideas? > > > > > > >I've never seen that happen before. Must be something funny matplotlib > >is doing... > > When a namespace package is installed using a backward-compatibility mode, > the __init__.py goes away, otherwise you'll have multiple packages > installing it. Is bdist_mpkg not including the .pth file that setuptools > generates to handle this? > It should include whatever is generated. I don't recall the specifics, and I don't really have time to look at it... but if someone can track it down to some root cause or provide a patch then I'd see about fixing it. It's worked for pretty much everything I've thrown at it the past few years. Setuptools probably throws a bit of a wrench into the mix, but I see very little reason to bother with mpkg when there's an egg available. -bob | https://mail.python.org/pipermail/distutils-sig/2007-March/007376.html | CC-MAIN-2016-40 | refinedweb | 284 | 61.63 |
What level of privileges are required to install the product?<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” />
Someone recently asked a question regarding what level of privileges are required to install the product and later they asked me why the accounts had to be what they were. I thought I would take some time to write this blogs and explain these accounts in a simple way.
The account doing the install on the server where the SQL server and Root Management Server are going to be installed needs to have local administrator privileges. To run MSI packages users must at a minimum have local admin privileges. In addition to this account would also require system administrator privileges on the instance of SQL where the Operations manager Database is going to be hosted. This would be required so that the setup can configure the necessary privileges for the SDK and Config service account and assign them the proper roles and rights on the Operations Manager Database as the SDK and the Config services read and write to the database Operations manager DB. The reason why we require the user installing to be an admin is because setup creates services, file/folders. It also creates SQL DB, SQL logins/roles so it needs to have necessary permission in order to do this.
Does the OpsMgr team support SQL 2005 database mirroring functionality?
Database mirroring is something that is OpsMgr team is not supporting at the moment (slight possibility we may support it in the future). But from what we know there should not be any reason why it would not work. SQL Full recovery mode is supported in OpsMgr 2007 and therefore log shipping is also supported. MSIT has built out their OpsMgr infrastructure which is using log shipping for their database; you can read more about their log shipping implementation here.
How do I know on which day the evaluation version of OpsMgr 2007 will expire?
Unfortunately there is no easy way to do this. But the one thing you can do is check the date installed in the registry and the eval expires after 180days (6months).
The registry key is
HKLMSoftwareMicrosoftMicrosoft Operations Manager3.0SetupInstalledOn
Note: Trying to change the registry key to extend the evaluation period or change the license key will not work, all this data is encrypted in the database.
Capacity Planner for OpsMgr 2007 is currently only in Beta how do I plan my customers OpsMgr deployments?
There is an internal alias called OMCAPREQ (OpsMgr 2007 Capacity Planning Requests) where internal MS employees can email information on their customers environment such as number of agents they want to monitor, kind of management packs they are planning to deploy and if they are planning to leverage new features like AEM and ACS and we will give guidance on what hardware is recommended and if we can scale to your customers needs. If you are a customer and want to get your deployment reviewed please get in touch with your TAM or Consultant and ask them to email this alias at Microsoft. In would be helpful if you sent a pictorial diagram of what you think your environment looks like.
Is it supported to install the Gateway role onto a domain controller?
I have tried it out in my Virtual environment and it works. I can’t day for sure we officially support it because I don’t think our test team has actually tested this scenario but if the customer runs into an issue we will help debug it but if there is no resolution to the problem then they will need to put it on a regular server. Just be aware of KB946428 and the likely need to run the HSLockdown tool.
Is MSIT using a three node cluster to host the database and root management server roles? Why is it not supported?
MSIT was at one point in time using the Active-Active-Passive scenario. However, since it is not a supported scenario by us they redeployed their RMS and SQL systems to two separate two node clusters prior to the RTM release. One of the limitations we have is not being able to monitor instances for SQL running on same cluster. If customer runs different databases on same HW, he would need to proceed with agentless monitoring for those instances.
How do I change the account the OpsMgr Services are running under?
Follow the steps in this KB article:
Satya Vel | Program Manager | System Center |
Satya Vel | Program Manager | System Center |
Join the conversationAdd Comment
The following is installed:
-Windows Server 2003 (Enterprise Edition, x64bit)
-SQL Server 2005 (Enterprise Edition, x64bit)
-SCOM 2007
I try installing Reporting Server getting the following err. "Microsoft SQL Server 2005 Reporting Services Service Pack1" and "Verify if Software Update specified by KB918222 for SQL 2005 is installed."
Microsoft website does not have "Microsoft SQL Server 2005 Reporting Services Service Pack1"
I download KB918222 but during the wizard I can’t select the RMS check box.
Can anyone help????
I think KB if for SQL and not OpsMgr 2007. Also open try opening reporting services configuration manager and see if checks are green.
How many agents are supported on the GW server under SP1? Can and should the GW server be used in a primary role as a concentration point for agents, regardless of the authentication method used? | https://blogs.technet.microsoft.com/momteam/2008/01/22/answering-some-common-deployment-questions-part-1/ | CC-MAIN-2017-47 | refinedweb | 902 | 58.52 |
A Programmers Take on “Six Memos for the Next Millennium”
by Malte Skarupke.
The memos are about
- Lightness
- Quickness
- Exactitude
- Visibility
- Multiplicity
- Consistency
The sixth one is not written, but I think consistency is very important in programming, so I’ll write about it a little bit.
Lightness
Italo Calvino is referring to lightness as opposed to weight. In all his memos he only says that he prefers the thing he talks about over its opposite. So he prefers to take weight out of his stories, but that doesn’t mean that there isn’t also value in weight, and other authors may prefer weight. But I agree with Calvino in that I prefer lightness in my stories. A specific kind of lightness that is. Calvino says that
I hope that what I have said so far shows that there is a lightness that is thoughtful and that is different from the frivolous lightness we all know. Indeed, thoughtful lightness can make frivolity seem heavy and opaque.
He has lots of examples for this in the book, but the one that I connected most with (maybe because it’s from a book I actually read) is Milan Kundera’s book The Unbearable Lightness of Being. It’s a book about very, very heavy topics. But it feels like a light book. Calvino says it like this:
His novel shows us how everything in life that we choose and value for its lightness quickly reveals its own unbearable heaviness. Perhaps nothing escapes this fate but the liveliness and nimbleness of the mind – the very qualities with which the novel is written
And as a game developer, the obvious example to mention is Jenova Chen’s work. His first famous work was literally titled Cloud and what could be lighter than that? He later created Flower, which is a game about being a flower petal floating in the wind, and Journey, which has similarly light movement. The game that he is currently working on is called Sky. I absolutely loved Flower and Journey, I think Journey in particular is one of the masterpieces of our medium. And I think its lightness has a lot to do with that. There is a simple delight in weightlessness, and it’s rare that someone manages to turn that delight into a full game.
A small interesting aside is that when Jenova Chen spoke at the NYU Game Center last month, he says that in the dichotomy between light and dark games, he prefers to make light games. He still values dark games, because his favorite game is Dark Souls, but in his personal work he prefers light. It’s a quirk of the English language that light and lightness are so closely related, but it’s also fitting because weight drags you down, away from the light.
Anyways, I was going to talk about programming. What is lightness in programming? I think lightness is related to “simplicity”, but it explains why I make certain choices that I wouldn’t make when talking about simplicity. Meaning I have had arguments about which solution to pick, and which one would be simpler, and in hindsight I was actually arguing for the lighter solution, not the simpler solution.
For example it explains why I still like to write code in C++. While C++ is an incredibly heavy language, it allows me to write light code. The idea of “you don’t pay for what you don’t use” is very important in C++, and is very rarely violated. In other languages I always feel like little weights are added to my program when I have to do something in a way that would be more efficient or more elegant in C++. (like having to heap-allocate something that could just be stored inside of another object, or having classes be bigger in memory than just the members that I added, or having overhead for virtual function calls that I don’t need)
The “you don’t pay for what you don’t use” concept gives us an idea where weight comes from in code: It comes from dependencies, and especially dependencies that we didn’t want or aren’t even using. It’s the old joke about object oriented programming: You wanted the banana, but what you got was the gorilla holding the banana. (and sometimes the whole jungle) But to further support that meaning of the word, when people talk about a “lightweight” library or framework, they usually mean a library that doesn’t have many dependencies itself, and that doesn’t force you to use more than what you need.
When I think about heavy objects, I’m immediately thinking about the “character” or “vehicle” classes of most game engines. For some reason these two classes in particular are usually messes. I’ve seen character classes that contain code for animation, model rendering, IK, skeleton queries, interactions with environment objects (like doors, chairs etc.) inventory, damage handling, effect playing, physics interactions, weapon handling, melee combat, camera code, ragdoll code, bone-attachments (like playing a effect attached to the hand) UI checks, AI code, random other game-specific logic, random file IO, lots of player-specific code (that’s still being paid for by all non-player-characters) special code for quadrupeds, water interactions, ammo handling, LODing, transform math, vehicle interactions, sound code, auto aim code, and more.
All that in one class that’s thousands of lines of code. How does that happen? Well the quadruped code gives us a hint: At some point people decided that they needed animals in the game. Animals need a lot of the code that characters already do: Animation code, damage handling, model handling, and random other interactions. Just turn off half of the other code and you’re fine. And then add some more code for quadrupeds.
It’s clear that this results in very heavy classes, and it’s also clear to the programmers who make those decisions. It’s one of those “yes, we’re concerned about it, but we can’t deal with it right now” situations that keeps on not getting dealt with for years, until you have a monster class, and now you can do even less about the problem.
The more I program, the more I think that inheritance is a big source of this. In that same engine, I once tried to create a new object that had overlap with characters, but it needed to be flying. And I didn’t want to add logic for flying to the messy character class. It was actually possible to write a new class that used a bunch of the existing logic, because most of the logic actually didn’t live in the character class. Usually the way it worked was “if you want to be able to receive damage, inherit from this base class and override this function.” The new class started off really clean, but because of this inheritance, we immediately started accumulating little bits of functionality to totally unrelated topics in the same class. Damage handling was now in the same class as animation code and effects code. And soon we had another monster. And once you have a monster, it’s easy to justify adding a little bit more logic into it, after all all of the other logic that you need to talk to is already in the monster class.
The only way I have ever seen this handle well is in an entity component system. An entity component system takes the “prefer composition over inheritance” to an extreme: You don’t even have a central class in which you compose all of the functionality. You just add components to a collection, and all components in the collection are part of the same logical object. Just the fact that you don’t have a central object forces you to be a bit more disciplined: If you want to add logic for foot IK, you’ll probably add a new component which can talk to your animation component. You can’t be lazy and say “I’ll just add it to the character class for now, and we can move it out later.” For an entity component system to work, it’s very important that it’s easy for components to communicate with their siblings, meaning it has to be easy to get the pointer to a sibling to talk to it. If you still have to coordinate through a central class, that central class tends to accumulate behavior like our character class above.
I personally like the system that the Unity game engine has. (whenever I bring it up as a model, people complain that Unity is slow. You could make their entity component system very fast, they just can’t do it because old code has to keep on working, so it’s hard to make things data-oriented or multi-threaded) One additional thing that that engine does is that it’s super easy to add glue code between components. It’s very easy to add small scripts that do the communication between two different components on the same object. I think the ease of adding scripts is one of the reasons why they have few clever components that try to magically find out what the right thing to do is based on their siblings. If you want custom behavior, just add a small script.
Talking about lightness, an interesting case is the C++ class std::function. It’s a heavy object, but it allows you to get away from inheritance, and as such it makes it easier to keep code light. For example you can write an update loop that doesn’t require inheriting from a base class. I have seen engines with requirements like “you have to inherit from CGameObject to be in the update loop,” where CGameObject also has other things on it, like a transform matrix. That’s another pitfall where inheritance leads to weight in the long term: The more classes something is inherited by, the more people will want to add functionality to it. You always get cases where there is common functionality between ten derived classes, so why not just add it to the base class? Well because there are another five objects that don’t need the shared functionality. std::function is an escape hatch out of this surprisingly often. This is actually the main reason why I should really learn Rust: I think their “Traits” form of polymorphism looks like it’ll be much better about this, while being lighter weight than std::function.
Quickness
Italo Calvino starts by telling.
Calvino goes on to tell how, since it’s such an old legend, there are many different versions of it. Most of them are longer, but somehow the length doesn’t actually make them better. He likes the quick version.
As a game developer, the value of quickness is most obvious when comparing the Blizzard games Warcraft III and Starcraft 2. Quickness alone probably explains why I preferred the story of Warcraft III. To illustrate, watch the introduction of two missions early in Warcraft III. Just watch until the cutscene is over and gameplay starts:
Now I already set you up to expect “quickness,” so maybe you were expecting something shorter. But to make the point, here is someone playing Starcraft 2:
I’m not going to link a second video for Starcraft 2, because this one is already long enough. This is the second level in the game, and the periods between the levels only get longer from here. The person who plays this talks a little bit, but even without that it takes almost seven minutes to get through all the things between missions. And if you don’t talk to everyone between missions, you’re missing out on the story.
When Calvino talks about “quickness,” he doesn’t talk about rushing the story. The old legend he is telling doesn’t feel rushed, even though it’s certainly quick. The Warcraft III introductions don’t feel rushed either. But in Starcraft 2 in comparison it can feel like people are just rambling on and on, and the story suffers.
In general I feel like quickness is a property that games have lost. I got a SNES classic last year, and I had forgotten how quickly those games get to the action. No long tutorials or slow intro missions. The first level is always a good level. And getting to the first level doesn’t take long. Take F-Zero for example:
You’re in the game, racing at high speeds within seconds of turning on the game. I don’t know precisely when we turned away from this, but I feel like it must have been with the advent of 3D gaming. Controls are much more complicated in 3D games, so suddenly you needed tutorials. And maybe an intro level that’s not too hard to allow you to get used to the controls. But often it just ends up feeling like the game doesn’t respect my time.
So what about programming? Quickness matters most for me in iteration times. As an example, let’s take how long it takes to write a unit test. I strongly believe that unit tests should live in the same file as the code that they’re testing. The reason is quickness. I’m not a TDD zealot, but I do write some of my code in a TDD style. When I do, my speed of programming is partially determined by how long it takes me to write and run a test. So you want to avoid adding steps to that. Like having to create a new file. Or having to launch a separate executable. If the environment is set up correctly, I find that coding with tests can be faster than coding without tests, simply because tests can have faster iteration times. Without tests you often have to start the game and load a level where you can test your content. That can add more than a minute to iteration times. I personally like to just scroll to the bottom of a file and add this code:
#ifdef TESTS_ENABLED #include "gtest/gtest.h" TEST(foo, bar) { ASSERT_EQ(5, foo(bar(10))); } #endif
This is pretty low-friction for me. I have the ifdef and the include memorized, so I can quickly add tests to any file. But I recently realized that even this may be too much. The video games industry is oddly backwards about testing, so I constantly try to push people to write more tests. Recently, I told someone who was writing some math code “you know, you would be much more productive if you just wrote a small test for this, to iterate more quickly” and he mumbled something about wanting to write more tests but never getting around to it. I realized that he didn’t know how simple it is to write tests. I showed him the above block with an example call to his function, and suddenly he was much more open.
So how could this be even easier? We need at least one include, and we need the ifdef check if we want the tests in the same file as the production code. We need to be able to compile this without the tests. We also need the macros because of C++ complexity reasons. It’s hard to see how to make this any easier. (neither the preprocessor nor templates are powerful enough to make any of this go away) The D programming language shows how to make it much easier. In D you can use the unittest keyword in pretty much any scope to quickly write a test:
unittest { assert(foo(bar(10)) == 5); }
This takes away all excuses. It’s even important that you can use the normal assert macro here, as opposed to the custom ASSERT_EQ macro of googletest. In my C++ example above the other programmer didn’t immediately start writing tests, because his math code was buried deep in the internals of a class. He had to pull it out to make it testable. That wasn’t hard, but it was something he had to do. Just being able to write unittest at any scope in D makes that part much easier. So this matters.
In fact iteration times is one of those areas where it’s never really fast enough. I use the tup build system because it adds less than a tenth of a second of overhead to a build. Does it really make a difference if the build system adds a second of overhead or a tenth of a second? Yes, you bet it does. When it comes to iteration times, a quantitative difference will quickly turn into a qualitative difference. If a build takes a fraction of a second, I can recompile and reload code every time that I save a file. That may not be doable when compiling C++, but it is doable when compiling shaders. Before using tup, I had to hack that workflow by doing a custom build from game code whenever the file watcher detected a change to the file. That’s ugly because you’re going around the build system, and you may be putting your build into an inconsistent state. If the build system overhead is near zero, suddenly you can just run a normal build on every save. And if there are derived build steps from your shaders, those will get compiled correctly, too. The moment that you have shaders that reload in a fraction of a second, you start working differently. You experiment a lot more. You tweak numbers more. You investigate small oddities of behavior to find the underlying cause and to get a better understanding of the code. Things that you needed to schedule time for (even if just mentally “I’ll get to that later”) you suddenly just do.
So is a fraction of a second fast enough for iteration times? I’d like to think that there are more qualitative differences for even faster compiles. Bret Victor’s talk Inventing on Principle comes to mind. Just like his visualization of “here are many possibilities for a jump,” I feel like there should be similar visualizations like “here are many possibilities for this shader.”
Exactitude
As is appropriate for the topic of exactitude, Calvino is very precise in what he means with the word:
For me, exactitude means above all three things:
- a well-defined, well-considered design for the work;
- the evocation of clear, sharp, memorable images;
- a language that is as precise as possible in its choice of words and in its expression of the nuances of thought and imagination.
The value of these things might be self-evident, but there are many, many works for which the above does not apply. I once gave a talk about The Game Outcomes Project, which looked into what made successful games and what made unsuccessful games. And one of the main things they found was that clarity and communication of vision was incredibly important. Of course “clear vision” is one of those things that is hard to get if you don’t already have it. But I think it can serve as a useful filter for ideas.
In programming I value exactitude most when it comes to robustness and reliability. As such, I very much disagree with Postel’s law: be conservative in what you do, be liberal in what you accept from others. That law is for internet connections. If somebody sends you a packet that isn’t 100% correct, you should still accept it. But you should only send out data yourself that are 100% correct. I understand why people do this on the internet: If your browser can’t load a website because the website doesn’t send out 100% correct HTML, people won’t blame the website, they will blame the browser. For that reason it’s more an unfortunate practical matter than a law. When it comes to your own data, or your own internal network, accepting bad data is exactly the wrong thing to do.
The big problem with Postel’s law is that it leads to weird semi-standards being established. Yes, you’re not supposed to do X, but in practice it works out. And you get weird edge case behavior because things aren’t properly specified in the “liberal” area of data. There have been security bugs because different software interprets the edge cases differently.
In your own code things get even worse, because now you are responsible for fixing the weird edge case bugs. In my experience, the more layers that follow Postel’s law, the more difficult bugs you will end up with. If a designer does something weird in the editor of your game, (like say accidentally using a naughty string) but the editor allows the designer to save it, and then the compiler allows it, and the loading code of your game allows it, the bug you may end up with may be really confusing. All you see is bad data in the game. You have to first debug the loading code to figure out if it messed with your data. You then find the edge case that should never be hit that came from bad data in the compiled file. So you logically conclude that the bad data must have come from the compiler. When you finally figured out what happened in the compiler, you see that a certain pattern in the source format can end up causing the compiler to write bad data. So how did we get that pattern in the source file? Off we go to the revision control history to figure things out. Was it a merge error? No it was actually saved out that way from the editor. So we open the file in the editor, and can’t find the problem there. In fact when we save it out again, the problem goes away. Because we hit a weird edge case. So we ask the designer what they were doing, and finally get a clue for what caused the issue.
How do you solve issues like this? Verify data every step along the way. Verify on save in the editor. Verify in the compiler. Verify on load. These edge cases that were caused by earlier edge cases are the worst bugs, in fact they can often be weird one-off bugs that go away by themselves. (as in the above example where the problem goes away if you just save the file again) Be precise about what you accept, and accept nothing else.
This is also one of the reasons why I prefer statically typed languages. The more messy you allow a programmer to be, the more likely it is that you will get really weird edge cases like this. Not saying that programmers will be messy all the time. 99% of the time they will have great behavior and not put in weird edge cases. But then something comes along that is causing a big problem, but it’s really hard to change, so they put in a little weirdness just this once. And if you’re maintaining that software over years, you will eventually accumulate enough of these little weirdnesses that making any large change becomes a giant pain. Not saying it’s easy to change large projects in statically typed languages, just saying it’s easier compared to dynamically typed languages.
Visibility
As we’re progressing through the book, the chapters are becoming less and less finished. In Visibility, Calvino talks mostly about the interaction between visual imagination and written words.
[…] the only thing I was certain of was that all of my stories originated with a visual image. One of these images, for example, was that of a man cut in two halves, each of which goes on living independently; another was a boy who climbs up a tree and travels from tree to tree without ever coming back down; yet another was an empty suit of armor that moves and speaks as if someone was inside it.
For me, then, the first step in the conception of a story occurs when an image that comes to mind seems, for whatever reason, charged with meaning, even if I can’t explain that meaning in a logical or analytical terms. As soon as the image has become clear enough in my mind, I begin developing it into a story, or rather the images themselves give rise to their own implicit potentialities, to the story they carry within them. Around each image others come into being, creating a field of analogies, symmetries, juxtapositions. At this point my shaping of this material – which is no longer purely visual but conceptual as well – begins to be guided by my intent to give order and sense to the story’s progression. Or, to put it another way, what I’m doing is trying to establish which meanings are compatible with the general design I want to give the story and which are not, always allowing for a certain range of possible alternatives. At the same time, the writing, the verbal rendering, assumes ever-greater importance. I would say that as soon as I begin to put black on white, the written word begins to take over, first in an attempt to match the visual image, then as a cohesive development of the initial stylistic impulse, until little by little it rules the whole field. Then it is the writing that must guide the story toward its most felicitous verbal expression, and all that’s left for the visual imagination is to keep up.
For me as a programmer, I thought “Visibility” was going to be about something else entirely. The word makes me think of software that shows how it works. I don’t do web programming often, but when I do, I still use Knockout as my library of choice. And the main reason is visibility. Knockout shows how it works. Knockout has a simple promise: It will re-evaluate code automatically when data changes. Like an excel spreadsheet, except for UI code. With that alone a huge amount of state propagation and cache invalidation bugs go away. How does it do that? It has two simple concepts: Observable variables and Computed variables. Computed variables are like formulas in excel spreadsheets. They get re-evaluated when one of the input variables changes. But I can write arbitrary code in the computed variables, so how does it know which observables I used? Easy, observables are not normal variables. You have to call a function to access them. So it just has to remember which observables I called that function on. The model makes perfect sense and I can see how the whole library is built on top of that. I don’t need to know the details because I can imagine how they work myself.
The last time I tried web-programming I did the tutorials for Vue.js and for React. Vue looks very similar to Knockout, except somehow everything works magically. Normal Javascript variables are suddenly observable. I don’t know how it works. Is it super expensive internally? Does it magically transform my structs? It doesn’t show how it works. React is even worse. The tutorial starts off with several layers of deep magic, including writing html tags in the middle of Javascript code.
Why do I care how it works internally? Who cares if the internals require a huge amount of code and weird magic to work, as long as they work, right? But I’m concerned about the law of leaky abstractions. While doing the React tutorials I got some error messages that looked truly terrifying. I’m concerned that if things go wrong, I won’t be able to fix the issue. Or if things are slow, it will be very tricky to figure out how to make them fast. I don’t want to have to make random changes until things are working better.
Some of this can just be solved with good tutorials. Maybe Vue.js actually works exactly like Knockout, just using automatically created getters and setters. Just explain that in the tutorial, and I’d be happy.
The error messages of React reminded me of C++ templates. They were created with visibility in mind: Nobody could debug macros, and templates were supposed to be a more easily understandable alternative. What went wrong? When stepping through STL code, you often come across functions that seem to do nothing, like this one:
template 〈class _Ty〉 inline _Ty * _Unfancy(_Ty * _Ptr) { // do nothing for plain pointers return (_Ptr); }
What does this function do? It just returns its input. Why have such a function and why call it _Unfancy? The answer to that question lies in how you do conditionals in template code. This is actually part of the template-equivalent of a switch/case, and this is the “do nothing” default case. Templates are a weird accidental functional programming language, so people often write really weird code like this to do branching logic like switch/case or if/else. Visibility is definitely low on this. There are talks of making “if constexpr”more powerful, so that this could be an if/else. The C++ community is oddly resistant against that though. The other planned thing that will help here is that modules will remove some of the symbol salad, reducing the number of underscores, and removing those parens around the result. (those are often defensive coding to protect against insane preprocessor use)
Another weird one is how customization points are done in C++ templates. Those also often end up as functions that seem to do nothing. But at compile time, depending on your type, the compiler might have chosen a different function to call that actually does something. Talking about these as problems in visibility makes it obvious what the problem is: If this is a customization point, it should look like a customization point. Not like a function that does nothing. But I shouldn’t be complaining too much. Templates are better than macros, and it looks like things are slowly getting better.
Multiplicity
In the final chapter Calvino talks about a certain kind of richness or complexity that is inherent to life, and he calls it multiplicity. The word is used for example in this quote:
He would assert, among other things, that an unforeseen disaster is never the consequence or, if you prefer, the effect of a single factor, of only one cause, but rather is like a whirlwind, a point of cyclonic depression in the consciousness of the world, toward which a whole multiplicity of converging causalities have conspired.
Calvino uses other books to illustrate this as well, like a book that has one chapter for every room in a Parisian apartment complex. Or here is another quote I like:
The best example of these networks that radiate from every object is the episode from chapter 9 of Quer pasticciaccio brutto de via Merulana in which the stolen jewels are recovered. We get accounts of every precious stone – its geological history, its chemical composition, its artistic and historical connections, along with all its potential uses and the associated images they evoke.
In game design, the closest thing I can think of, that explores this richness and complexity of everything, is a game design approach that Jonathan Blow and Mark ten Bosch talked about in this talk:
In that talk they explain a design philosophy in which you focus on one idea, and you explore all of its implications and its richness. You can see this most easily in Jonathan Blow’s game Braid, in which he explores the implications of the ability to control time.
I also think that Nintendo games follow a similar design philosophy. Here is Game Maker’s Toolkit talking about how it applies to Super Mario Odyssey:
And the shrines in Breath of the Wild also allowed the designers to fully explore their gameplay mechanics.
How does this apply to programming? I think certain parts of programming have this richness, this good kind of complexity. The unix shell for example. Many separate programs that do one task, and they do that one task so well that they have explored every single angle of it. But most important is that those programs can talk to each other through a shared interface. This kind of richness is often missing in programming. What is the unix shell equivalent in C++? Maybe the STL containers and algorithms, but they’re not nearly as rich as the unix shell.
I also feel like many concepts aren’t sufficiently explored. I said above that Knockout is following the same state propagation model as Excel spreadsheets: If any of your inputs change, you get updated automatically. That simple model makes a huge number of bugs and complexity go away. Try to open a random file in your codebase, and measure the fraction of code that is responsible for pushing state around: Making sure to recompute X whenever Y changes, making sure that the new value of a variable gets pushed to all the places that use it, and making sure to invalidate all the caches that have duplicated some state for performance reasons. (like how the transform of a game object is usually cached in at least the physics system and the renderer, but usually in many other places as well) I bet you it’s more than half of your code, and in Knockout it’s so nice that all of that goes away. I feel like it should be used for more than just Excel spreadsheets and UI code. I’ve tried to explore it more fully, but it’s slow work that I can only really do in my spare time, where I already have dozens of other projects.
I think programmers are hesitant to do this work because our main problem is complexity. And when I say things like “explore a concept fully” I am also immediately thinking of over-engineering and unnecessary complexity that’s going to come back and bite me. Calvino also talks about how this is a problem in the books that he is referring: A lot of them are unfinished works. Sometimes the author spent decades on them before he passed away, and the unfinished book was published posthumously. It’s also a problem that Jonathan Blow ran into, The Witness took him seven years to complete, and Mark ten Bosch has been working on Miegakure for something like ten years. In that sense it’s amazing that Nintendo can release these very rich games at a regular schedule. I should look into how they do that…
Consistency
Calvino hadn’t started on his talk about consistency when he passed away, so we don’t know what he was going to say about it. But Jonathan Blow actually does a great job talking about the value of consistency in game design in the talk that I embedded at the top of this blog post. So I will just tell you to watch that.
In programming, consistency is such a commonly voiced value, I almost don’t have to say anything. The one thing I’ll add to the usual is that I think we’re pretty good about presenting consistency to other programmers (avoid surprises in interfaces etc.) but we’re not that good in presenting consistency to users of our software. Dan Luu has two blog posts that seem relevant here. Here is one on the huge number of bugs that we expose our users to, and here is one about UI backwards compatibility. Here is an example quote:
Last week, Facebook changed its interface so that my normal sequence of clicks to hide a story saves the story instead of hiding it. Saving is pretty much the opposite of hiding! It’s the opposite both from the perspective of the user and also as a ranking signal to the feed ranker. The really “great” thing about a change like this is that it A/B tests incredibly well if you measure new feature “engagement” by number of clicks because many users will accidentally save a story when they meant to hide it. Earlier this year, twitter did something similar by swapping the location of “moments” and “notifications”.
I honestly don’t know what to do about that. In video games, it feels like our games are now complex enough that lots of developers simply can’t manage the complexity any more. Features just stop working, even if no one removed them intentionally. See for example this video comparing Far Cry 2 to Far Cry 5:
I can tell you exactly how the above happened: some of these features just broke during development and nobody noticed until it was too late. Other features were re-written, maybe when porting the engine to a new console version, or just because somebody wanted to rewrite them. The new feature then didn’t have all the features of the old version, either because there was no time, or because the person doing the rewrite didn’t know about all the features that the old version had. Some things were just redone for the sake of redoing them, like the damage animations. Animators always want to redo all the animations, just like artists want to redo all the art, designers want to completely change the design and programmers want to rewrite all the code. Sometimes people just delete old stuff with the intent that somebody will redo them, and they never get redone. (like the underwater death animation that was “replaced” by a “stumble and fall to the ground” animation that makes no sense underwater) And of course the projects are always under time pressure, and features like “destructible vegetation” get down-prioritized early on after a rewrite of the vegetation system. After all there are several other new features that are high priority, not to mention all the bugs that were caused by the rewrite. So “destructible vegetation” becomes a down-prioritized “nice to have” feature, never mind the fact that the engine used to have it.
How do you solve it? I don’t know. I mean clearly more automated tests would help, but the difficulty lies in convincing people to actually write tests, learn how to write good tests, and to maintain their tests. I once wrote a lists of potential improvements that we could do at work, and it had dozens of entries, ranging from “more automated tests” to “more static analysis” and “write postmortems for crashes” and “put a sticker on the programmer’s desk every time they introduce a crash, to see who collects the most” (a form of public shaming), “more strict code reviews” and others. But the problem obviously doesn’t lie in lack of ideas, since we have known most of this for decades.
I have a hunch that whoever solves this will make a lot of money. It does seem to me like Blizzard has much more solid game development practices. I remember watching the development of Starcraft 2, and even early versions of it looked super solid. Nintendo also clearly has this figured out: They used the same Mario engine for many years, and they also used the same Zelda engine for many years. It helped that the Gamecube, Wii and Wii U had very similar hardware.
It’s important to not confuse consistency with stagnation. Developers who ship the same game (or nearly identical games) multiple times will soon die. But I do think that if you have a development process where things don’t break all the time, you would free up a lot of time that we can put into making better games.
Conclusion
Italo Calvino was clearly a genius, and it shows in his choice of topics. Which game designer has ever said that they want to make a game that has “Lightness, Quickness, Exactitude, Visibility, Multiplicity and Consistency”? We strive for much simpler goals like “fun” or “intense” or “scary”. I like Calvino’s choice of topics because they make me think. Thinking about lightness revealed what I actually like when I talk about simplicity. And thinking about quickness revealed why the story in Stacraft 2 had always bothered me. I like the topic of multiplicity most though, perhaps because it leaves me with the most open, intriguing questions. How do you get that kind of richness in a reasonable amount of time? It’s something I’ll spend time investigating, hopefully without falling into an impossible to finish mega-project…
I’m not sure what else to say but thank you for this. As a fan of Italo Calvino and an aspiring programmer, the connections and elaborations were something I would have never connected. There is so much here, most of which I am not at a level to understand or appreciate. I believe I will keep coming back to this. In short, this is just to say someone acknowledged and valued your post.
Thanks for writing the comment. Honestly, I was very unsure about whether I should even publish this blog post. I felt I was rambling too much, and I almost gave up on it. It was either hit the “delete” button or publish, because I could feel my dislike for it growing the more I was working on it. It actually is a kinda popular blog post for me. Which I really wouldn’t have predicted.
Regarding iteration time, I’m experimenting with extremely lightweight unit testing library (works only in gcc, still waiting for std::source_location to appear in the standard). You can achieve something similar to D unittest with a pinch processor magic.
unittest(“math works”) {
assert_eq(2, 1 + 1);
} | https://probablydance.com/2019/03/09/a-programmers-take-on-six-memos-for-the-next-millenium/ | CC-MAIN-2019-22 | refinedweb | 7,015 | 69.41 |
Re: Trivia Question
- From: "\\\\\\o///annabee" <faq@xxxxxxxxxxxxxx>
- Date: Thu, 05 Jan 2006 01:01:08 GMT
På 4 Jan 2006 15:18:23 -0800, skrev randyhyde@xxxxxxxxxxxxx <randyhyde@xxxxxxxxxxxxx>:
\\\o///annabee wrote:På 4 Jan 2006 08:14:02 -0800, skrev randyhyde@xxxxxxxxxxxxx <randyhyde@xxxxxxxxxxxxx>:
> > \\\o///annabee wrote: > >> Who need that? Someone dealing with writing a compiler! > Or a debugger. Or maybe someone really wants to *change* one of the > register values on return (and, therefore, needs to poke a value into > the stack frame where the value for that register is sitting). > > Make all the excuses for your ignorance that you like, but, yes, > assembly programmers *should* know about this stuff.
I disagree. This is the kind of stuff that is trivial to enquery once you
written
about as much code as I have. You know, the stack may seem strange at
first, but the
fact that it grows to lesser adresses, is not really THAT hard to figure
out.
??? First you say that people don't need to know this. Then you seem to be confused about what the question actually was as what you've posted has nothing to do with the original question.
You misunderstand. By knowing how the stack works, and using RosAsm I can using the incredible RosAsm runtime debugger, inspect the stack, and confirm the order of pushed registers.
Its just that I never needed to know.
And that lack of knowledge means that you cannot take advantage of this information when it would be useful. This is what I meant by "ignorance".
But as usual you are wrong. First we have a problem, then we have a solution.
If , for some reason this solution had to involve knowing the order of the
pushed registers, then we would have done the steps to find out.
There a million things I never needed to know, and even more that I will never need.
No doubt. But the more you do know, the better the position you'll be in to recognize when that information is *applicable* to your current problem, rather than hacking out a different, and less elegant, solution.
Need to know. As long as I never needed to know, and as long as an elegant solution offer just its elegance, which in the actuall cases seen, is usually the complete oposite of fact, while they tend to be rather obscuring solutions, and called elegant just because they obscure the thinking.... I have no need for dead knowledge like that.
If you want to see elegance, take a look at some of the RosAsm sourcecode.
But this doesn't make it impossible to wrote FULL PEs in assembly, quite the oposite.
This has nothing to do with writing PEs. Indeed, the whole concept is independent of the executable file format in which the PUSHA/PUSHAD instruction appears. You are simply over your head on this one and you're making stuff up so that you don't look quite so stupid.
:)) You life story master P. The above sentance is YOUR LIFE STORY. - Not to say the Your Lie Story.
Allow me to give you a hint: when you don't have a clue what you're talking about, don't post (unless, of course, it's a question). Trying to cover up your ignorance with additional nonsensical posts just makes you look worse.
Ah. Getting tired Master PDF? I didnt think you had it in you. I am only adressing your many strange claims, as best as I can. This is what this whole "n"g story is about.
You are actually probably scaring beginners by providing too much info at
once.
??? Where would this be?
Pages and pages of nonsensial, teoretical infos at Webster.
1000 pages? More? Dear god, there used to be 2 chapters on just how to install HLA!
RosAsm = download, unzip, start. Takes at most 15 seconds.
I guess you've completely missed the whole point of HLA? Leveraging people's *existing* HLL knowledge to learn assembly language programming? This was the big improvement over the 16-bit edition, which *did* blast people with "too much information at once."
The whole point of HLA is imo, to become the greates joke on asm of all times.
> After all, the
> point of assembly language is *not* to write HLL-like code in assembly,
The point of assembly is to program the machine.
Funny, I thought that this was the point of *all* programming languages (HLLs included).
It is. You are its seem correct. One of your occational good shots. :)
Its the native language ( -es ) of the machine.
And what does this have to do with anything?
Well. Itsa bit like me, I suck at english and thus dont get all the nuiances with me all the time. If I spoke your mother toungue, it would be more easy for me to explain myself.
For many complex topics I dont know the words at all, and just have to leave those subjects alone as its very important to have a presise language for communcating certain ideas.
In particular, what does this have to do with the order by which registers are pushed on the stack for PUSHA/PUSHAD? You're going off the deep end here.
We been though this. This is a trivial subject : even Hutch--,.-- could figure it out.
To read more into it than that is not fair.
Sure it is. If people are less productive in assembly than in HLLs, it's *fair* to compare those languages on this basis.
But thats not a fact at all. Its just the oposite.
Assembly usually comes up short.
Huh? A two year beginner can really near damn blow _you_ away.
But again, please explain what this has to do with PUSHA/PUSHAD. Sounds like you're trying to change the subject to avoid attention being drawn to your ignorance about these assembly language statements.
:)))))))))))))))))))) Comming from you, thats not only funny, its sick!
> but to take advantage of what the machine has to offer. Now, knowing > the exact sequence of the registers on the stack isn't something that > every programmer ought to have memorized (it's easy enough to look up > when you need it, or you can do something like #include( "x86.hhf" ); > and get symbolic equates for these offsets), but a decent assembly > programmer *should* understand why knowing this information may be > useful.
Information are rarely useful until needed.
And that information remains useless if you don't know about it. That's why its a good idea to know things like how PUSHA/PUSHAD work.
Redundant argumentation. Allready attended.
No matter how many manuals, how many infos you memorized, this will only be a small help at writing programs.
The true hacker's motto. What can I say? You do realize that you're preaching that ignorance is better than knowledge, right?
No, I preach that its better to know HOW to apply and seek knowledge than to stuff everything without sensurship into the old hat.
Its not like your memory is the one that moves and inspires you to do programming,
Been taking too many drugs, lately?
Well, no, but feel free to explain how your memory inspires you. Oh I forgot, You worte an assembler bak in what was it 1786? , that could do everything the RosAsm can do. Sorry. Which I had such an assembler when starting with Delphi.
It is your imagination. Then the language becomes a tool to make that thought a running application. After working with the needed instructions some times, repleatly, they tend to stick around in your memory.
Ah, I see, you're following the "Betov philosophy" of only needed to use 20 or so instructions in an application.
Its a bit more, maybe 50. I havent counted.
You're *not* thinking in assembly when you do this.
Of course not. I am thinking in terms of how I can make my apps do what I want.
And you're *not* taking advantage of the machine when you do this.
Nope. My head and thoughts are 100% true blue human.
And if you don't study the instruction set and learn what the majority of the instructions do (and their relative timings), how do you know when to use, say, LODSB and STOSB versus a MOV and INC/DEC instruction?
I watch other apps, step through the debugger, read about just those instructions that I can see right in front of me, running, and try to make use of them in my own apps.
And when you ever discover something that you cannot formulate, you may take a look at the instruction set for clues. Then, by and by, you build the needed base to do what you want.
Well, from the code of your's that I've seen, what normally happens is that you hack out a solution with a sequence of instructions rather than taking the time to learn about the one instruction that does it all. Don't feel bad, this is human nature (and your mentor Rene is a classic example of someone who follows this philosophy).
But seeing as RosAsm is the better assembler, and that HLA is just a joke :> I may prefer Renè philosphy.
> Hopefully, in a few more years, you'll discover why it just > might be important to know the order of the registers pushed on the > stack by pusha/pushad.
If the situation where important, it will be important. Sure. But for more
then 2megas
of written sourcecode, between all my apps, this was never needed.
What you mean to say is that you've never recognized when this would have been useful.
No, it means I found solutions that wore good enough and that didnt require it.
So thats why, it is useless info to throw at a beginner, unless he asks for it.
Wrong. Most beginners don't even know the question to ask.
To some extent this is correct. But to read a whole boook the size of PDU, is certainly not needed at first.
The fact that Chuck's little quiz pointed out your ignorance on this subject makes that abundantly clear in your case.
My ignorance has been debated before. I have no problems saying it like it is
I know 3 eflags, about maybe 30-50 instructions and thats basically it.
But since I use RosAsm, I can pop out applications easy as that.
Its just 4 clicks to create an application with RosAsm. To expand it from there is not incrediby difficult.
Beginners need to herded in the right direction.
Away from PDU.
Then their education is far more efficient than if they simply "wander around in the desert for 40 years" as you seem to be doing.
10 years blindfolded, using Delphi, 2 years with RosAsm.
You do realize, don't you, that most people become *expert* level assembly programmers when doing it constant for two years.
How dumb can you be to think I did it constantly for two years ?
The fact that you're still calling yourself a "beginner" after all this time (and the ignorance displayed in many of your posts confirm your opinion of yourself) suggests that the educational approach you're using could stand for some improvement.
Looking at HLA, its safe to assume you competance to be equal to &NULL HLA nomatter what you claim, is a very very talentless application.
Then again, if you programmed in Delphi for ten years and still couldn't figure out how to do a linked list, I suspect than *any* educational approach isn't going to work well with you.
:))) I just love it when you repeat that Prototype9+ :)
Cheers, Randy Hyde
.
- References:
- Trivia Question
- From: Charles A. Crayne
- Re: Trivia Question
- From: hutch--
- Re: Trivia Question
- From: Charles A. Crayne
- Re: Trivia Question
- From: \\\\\\o///annabee
- Re: Trivia Question
- From: randyhyde@xxxxxxxxxxxxx
- Re: Trivia Question
- From: \\\\\\o///annabee
- Re: Trivia Question
- From: randyhyde@xxxxxxxxxxxxx
- Prev by Date: Re: [repost]Eorros for me, in the assembly history
- Next by Date: Re: [repost]Eorros for me, in the assembly history
- Previous by thread: Re: Trivia Question
- Next by thread: Re: Trivia Question
- Index(es): | http://coding.derkeiler.com/Archive/Assembler/alt.lang.asm/2006-01/msg00351.html | crawl-002 | refinedweb | 2,040 | 73.17 |
About me he was tired of Spring and wanted to take a look at Guice. He also told me about jQuery a while ago and that was pretty cool, so maybe he is right again.
Guice is a dependency injection framework and does some AOP stuff (which isn’t handled in the video). The video takes about an hour and handles the basic concepts of Guice. It’s convenient when you know something about dependency injection because it isn’t explained in great detail (which is a good thing when you only have one hour). My main goal of watching the video was to see whether this was an alternative to Spring. I have absolutely no complaints about Spring, but sometimes the grass is greener on the other side.
Injecting with annoations
The developers of Guice don’t like to configure things in XML. They developed a DI framework where you configure everything with annotations.
Let’s say you have a class called Service and want to inject this class into your code. It would look like this (note that all code examples are copied from the Guice manual):
public class Client { private final Service service; @Inject public Client(Service service) { this.service = service; } public void go() { service.go(); } }
Guice automatically finds the Service class and injects it into your Client class. That’s pretty cool at first sight. But here’s the catch. You usually progam to interfaces. That’s also possible with Guice, but when you have more than one implementation of your interface it’s going to look weird.
First let’s take a look at the situation when there’s only one implementation:
bind(Service.class).to(ServiceImpl.class);
(this code is entered in a class that handles the configuration)
That looks pretty compact and still very understandable. But when there are two implementations we have to create two annotation files. Assume we have two implementations of the Service interface, called RedService and BlueService.
To inject the Blue implementation to the service we have to add a @BlueService annotation:
@Inject @BlueService Service service;
We have to define this @BlueService in a separate file and bind the @BlueService annotation to the injector:
bind(Service.class) .annotatedWith(BlueService.class) .to(BlueService.class);
The BlueService annotation file:
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) @BindingAnnotation public @interface BlueService {}
The same goes for the RedService implementation. I think this is too much work and you end up with a BlueService.java and RedService.java file that are not really needed.
When we use Spring it would’ve looked like this:
<bean id="client" class="com.google.Client"> <property name="service"> <ref bean="service"/> </property> </bean> <bean id="service" class="com.google.BlueService"/>
My personal opinion is that this is much clearer and the information is in one place instead of 2 (or actually 3 when you count RedService). Ok, it’s XML, but to work around that by creating an extra file is too much hassle for me. One good point might be that it’s very easy to rename BlueService to DarkBlueService, renaming this in XML might lead to errors (but probably your IDE can help a great deal with this)
Another bad thing about using annoations is that your Client class now depends on Guice. When you use setter injection and program to interfaces (with Spring for example) you don’t know which framework is used, which is a good thing.
Conclusion
The video was fun to watch. Of course Guice is a direct competitor of Spring, but the google guys didn’t talk about Spring, they just told why Guice is good and didn’t bashed the Spring guys. I can’t agree with all the arguments they gave me. Typo’s for example. Because everything is in the code it’s much less likely that you make typo. But my argument against that it that if your application breaks because of a typo your unit test probably isn’t right. The first time I made a typo in Spring I was a bit confused, but now I learned to recognize them and of course the unit test will also discover it. And nowadays with IntelliJ IDEA and the Spring IDE plugin for Eclipse most typo’s are discovered before you start compiling your classes.
There was also a short part about what’s bad about the Factory and Service Locator pattern, also very interesting to watch.
The part of the unit testing I didn’t really get. I think you can unit test this way with every DI framework, or maybe I just missed something out here. And what’s bad about extending from the AbstractDependencyInjectionSpringContextTests, it’s not very likely that you start switching a DI framework. A DI framework is the foundation of an application, changing that is like moving walls in your house, it’s possible but probably too expensive.
For now I’ll stick with Spring, but Guice might be worth a shot when you can decide which framework to use. But I can’t see any big advantages. Spring is widely spread, there are many books about Spring and a lot of developers have experience with Spring.
But the video isn’t a waste of time, even when you don’t plan to use Guice. It’s good to know what frameworks are around and you’ll learn some other things too.
Sources
Guice home page
Blog entry of Dion Almaer
Guice User’s guide
Google’s comparison to Spring
5 thoughts on “A quick look at Guice A dependency injection framework by Google”
Thanks for the feedback.
First, the Guice manual uses “@Blue” not “@BlueService”. You typically have a small set of reusable annotations which you can share across multiple bindings; you don’t create a new annotation for each binding. It’s not like Spring where each name must be unique. Also, from my experience, you only use annotations about 5% of the time (if that); these aren’t equivalent to Spring’s bean names which you must always use.
Second, Spring actually spreads your configuration out more and requires more of it. With Spring, you have the configuration for Service, the XML mapping Service to Client, and Client itself–3 places. With Guice, you just have the configuration for Service and Client itself–two places.
I agree that there appears to be little benefit from using Guice in this small example (I point this out in the manual before we even start this example). The benefits from Guice kick in when you use Service again from another object. With Spring, you would need external XML to wire Service to each new object (autowiring is not an option). With Guice, you just put @Inject anywhere you need Service.
If maintainability is a high priority (we spend a lot more time reading code than we do writing it), then I would try Guice–that’s why we built it. For more information, check out our Guice/Spring comparison:
I think he just wanted something else. When you’re working on a Spring project for months something completely different can be quite refreshing.
You started your blog with the remark that your old collegue is “tired of Spring”. It made me curious to read why….. Was your collegue just ready for a new challenge or did he mention an argument against this framework? I agree with your arguments that Guice DI does not offer any special benefits, as you described it.
While I was writing the blog entry yesterday I thought I saw something like the Guice config in Spring, but couldn’t find it on the Spring site.
Thanks for pointing me to that site, it looks promising and I totally forgot about it, but I have to read more about JavaConfig to see how it compares to Guice.
How would it look using the Spring Java annotation based configuration? | https://technology.amis.nl/software-development/java/a-quick-look-at-guice-a-dependency-injection-framework-by-google/ | CC-MAIN-2021-43 | refinedweb | 1,321 | 62.68 |
Introduction
A Stream is a sequence of objects that supports many different methods that can be combined to produce the desired result.
They can be created from numerous data sources, which are most often collections but can also be I/O channels,
Arrays, primitive data types etc.
It's important to emphasize that a stream is not a data structure, since it doesn't store any data. It's just a data source wrapper which allows us to operate with data faster, easier and with cleaner code.
A stream also never modifies the original data structure, it just returns the result of the pipelined methods.
Types of Streams
Streams can be sequential (created with
stream()), or parallel (created with
parallelStream()). Parallel streams can operate on multiple threads, while sequential streams can't.
Operations on streams can be either intermediate or terminal:
Intermediate operations on streams return a stream. This is why we can chain multiple intermediate operations without using semicolons. Intermediate operations include the following methods:
map(op)- Returns a new stream in which the provided
opfunction is applied to each of the elements in the original stream
filter(cond)- Returns a new stream which only contains the elements from the original stream that satisfy the condition
cond, specified by a predicate
sorted()- Returns the original stream, but with the elements being sorted
Terminal operations are either void or return a non-stream result. They're called terminal because we can't chain any more stream operations once we've used a terminal one, without creating a new stream from it and starting again.
Some of the terminal operations are:
collect()- Returns the result of the intermediate operations performed on the original stream
forEach()- A void method used to iterate through the stream
reduce()- Returns a single result produced from an entire sequence of elements in the original stream
In this tutorial, we'll go over the
map() operation and how we can use it with Streams to convert/map objects of various types.
Stream.map() Examples
Let's take a look at a couple of examples and see what we can do with the
map() operation.
Stream of Integers to Stream of Strings
Arrays.asList(1, 2, 3, 4).stream() .map(n -> "Number " + String.valueOf(n)) .forEach(n -> System.out.println(n + " as a " + n.getClass().getName()));
Here, we've made a list of integers and called
stream() on the list to create a new stream of data. Then, we've mapped each number
n in the list, via the
map() method, to a String. The Strings simply consist of
"Number" and the
String.valueOf(n).
So for each number in our original list, we'll now have a
"Number n" String corresponding to it.
Since
map() returns a
Stream again, we've used the
forEach() method to print each element in it.
Running this code results in:
Number 1 as a java.lang.String Number 2 as a java.lang.String Number 3 as a java.lang.String Number 4 as a java.lang.String
Note: This hasn't altered the original list in the slightest. We've simply processed the data and printed the results. If we wanted to persist this change, we'd
collect() the data back into a
Collection object such as a
List,
Map,
Set, etc:
List<Integer> list = Arrays.asList(1, 2, 3, 4); List<String> mappedList = list.stream() .map(n -> "Number " + String.valueOf(n)) .collect(Collectors.toList()); System.out.println(list); System.out.println(mappedList);
This results in:
[1, 2, 3, 4] [Number 1, Number 2, Number 3, Number 4]
Stream of Strings into Stream of Integers
Now, let's do it the other way around - convert a stream of strings into a stream of integers:
Arrays.asList("1", "2", "3", "4").stream() .map(n -> Integer.parseInt(n)) .forEach(n -> System.out.println(n));
As expected, this code will produce the following output:
1 2 3 4
List of Objects into List of Other Objects
Let's say we have a class
Point that represents one point in a cartesian coordinate system:
public class Point { int X; int Y; Point(int x, int y){ this.X=x; this.Y=y; } @Override public String toString() { return "(" + this.X + ", " + this.Y + ")"; } }
Then, say we want to scale a certain shape by a factor of
2, this means we have to take all the points we have, and double both their
X and
Y values. This can be done by mapping the original values to their scaled counterparts.
Then, since we'd like to use the new coordinates, we'll collect this data into a new list of scaled points:
List<Point> originalPoints = Arrays.asList(new Point(1, 2), new Point(3, 4), new Point(5, 6), new Point(7, 8)); System.out.println("Original vertices: " + originalPoints); List<Point> scaledPoints = originalPoints .stream() .map(n -> new Point(n.X * 2, n.Y * 2)) .collect(Collectors.toList()); System.out.println("Scaled vertices: " + scaledPoints);
This example will produce the following output:
Original vertices: [(1, 2), (3, 4), (5, 6), (7, 8)] Scaled vertices: [(2, 4), (6, 8), (10, 12), (14, 16)]
Conclusion
In this article, we explained what streams are in Java. We mentioned some of the basic methods used on streams, and focused specifically on the
map() method and how it can be used for stream manipulation.
It is important to mention that streams are not really mandatory part of programming, however they are more expressive and can significantly improve the readability of your code, which is why they became a common programming practice. | https://stackabuse.com/java-8-stream-map-examples/ | CC-MAIN-2021-21 | refinedweb | 927 | 61.26 |
Introduction to Blazor
Blazor is an Open Source, single-page web application development framework developed by Microsoft. Unlike other frameworks like Angular, React, and VueJs, Blazor allows you to write and run C# code in web browsers through web assembly.
You can download the source code of this project from GitHub and use it as a reference.
To track changes, see this commit.
Hosting models
Blazor apps can be hosted in two different ways.
- Client-side Web Assembly.
- Server-side ASP .NET Core hosted.
Now you might be wondering, what are there things? How are they different. Lets find the answer.
Client-side Web Assembly Hosting model
According to the documentation, a client-side web assembly Blazor app runs in the browser similar to other frameworks like Angular, React, and Vue Js. When a user requests a web page or your web application, the entire code related to the client-side logic is downloaded. All dependencies and runtime required to run the application will also be downloaded.
This allows us to use the application even if the app goes offline and syncs the changes later.
Benafits
- Can even work offline.
- Can utilize serveries deployment.
- Faster in challenging network conditions.
- All events created by the user are handled on the client side itself instead of sending it to a web server. This will reduce the server load.
Drawbacks
- The entire application and its will be downloaded to the end device. Therefore, the initial loading time will be higher that the server side hosted model.
- Limited to the capabilities of the client device.
Server-side ASP .NET Core hosted Hosting model
If we choose the Server Side hosting model, the Blazor app will run on the server. Every change or events that occurred at the client side is sent to the server via SignalR communication. The server will then process the events or changes and update client-side UI if necessary. This means that the UI rendering will occur at the server-side.
Benafits
- Initial loading will be faster.
- Requires a network connection to work.
- Need a server that can host your .NET Core application.
- Can utilize the capabilities of a web server.
- Good for SEO as the result is processed on the server-side.
Drawbacks
- No good in bad network conditions.
- As the number of users increases, you have to scale the hosting.
- Users far from the server location may experience small delays in processing their requests.
Which hosting model should you choose
Choosing a hosting model depends on the application. Choose Blazor server-side app if your app is too complex and SEO is your paramount. If the app is small and needs the capability to run offline, choose Blazor Web assembly.
Prerequisites
Before continuing, please make sure that you have installed Visual Studio 2019. If you are using a Linux machine, install Visual Studio Code.
Next, we should install the latest version of .NET Core SDK. If you are new to .NET Core SDK, it is a tool that allows developers to create .NET applications and libraries.
The latest version of .NET Core SDK can be downloaded from here. After installing .NET SDK, run the following command to validate the installation.
dotnet --info
If .NET SDK is installed properly on your computer, you will get an output similar to this:
If the .NET SDK is not installed properly, you may get an error like this.
'dotnet' is not recognized as an internal or external command
Create a Blazor project
Step 1: Now, let’s create our first Blazor Application. To create the app, open Visual Studio, select Blazor app from the project template, and click Next.
Step 2: Give a name for the project. Here, I am naming the project as BlazorApp.
You can also pick a location to save the project. Click Create to continue.
In this page, you can select the hosting model of your Blazor App. You can learn more about Blazor hosting models from here.
First, we’ll be working with Blazor Web Assembly. So, select Blazor web assembly as the hosting model. Also, make sure that you have selected Configure for HTTPS, and ASP .NET Core Hosted.
Click Create to create the project.
Project Structure
Visual Studio will now create a Blazor project. Before continuing, let us take a look at the project structure of our Blazor application. You can run the project to see a demo app created for you.
In the Solution Explorer, we’ll have three projects.
- BlazorApp.Client
- BlazorApp.Server
- BlazorApp.Shared
BlazorApp.Client
The name itself is self explanatory. The BlazorApp.Client is the project that deals with the client side logic. Anything you write in this project will be sent to the sent to the browser and will be executed there.
BlazorApp.Server
This application will not be sent directly to the client. This project is performing server-side activities. For example, this project can be used to build an API for the application.
BlazorApp.Shared
This project holds the common or shared elements. For example, this project can be used to define the models used in the client-side and server-side app.
Files and folders
Now let us get familiarized with the important files and folders of the project.
wwwroot
This folder holds all static files like CSS, images, icons, fonts etc. used by the application.
This folder is used to store the shared or reusable components. For example, you can store the NavBar of the project in this folder because it is a shared component that you’ll be using on multiple pages.
Program.cs
This is the entry point of our application. It contains the Main method that is executed first when the app runs.
In a Blazor server project, the Main() method calls CreateHostBuilder() method which sets up the ASP.NET Core host. In a Blazor client-side project, the Program.cs file will be in the <app-name>.server project.
App.razor
This is the root or base component of the application and contains the routing mechanism of the client-side application. It captures the requested URL and renders the page. If the page os not found, a message saying Sorry, there’s nothing at this address. will be displayed
MainLayout component (MainLayout.razor)
The application’s main layout component.
NavMenu component (NavMenu.razor)
This is the default Navigation bar template of the Blazor application.
_Imports.razor
This is similar to _ViewImports.cshtml file in an asp.net core MVC project. This file holds the references to commonly used classes and namespaces so that you don’t have to import that chasses in each component or page.
wwwroot/index.html
It is the root page of our application and contains all tags such as HTML, HEAD, BODY, etc that are common for all pages. It is responsible for loading the required scripts (_framework/blazor.webassembly.js) to run the application.
Startup.cs
This file contains the project’s startup logic. The DI model and middlewares are configured here. In a Blazor Web Assembly app, you will see this file in both setver-side and client-side projects.
ConfigureServices – The ConfigureServices method can be used to configure the built-in dependency container of the framework.
Configure – Configures the app’s request processing pipeline. Here, we can declare the middlewares of our application.
You can learn more about the startup.cs file from here.
appsettings.json (Blazor Server)
As the name indicates, this file is used to store the project settings and configurations. For example, you can store the database connection string in this file. In classic ASP .NET Web Form Apps and MVC apps, we used web.config instead of appsettings.json. This is the default content of appsettings.json.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
What’s next?
In the next post, we’ll learn about components and create a component to display a list of movies. | https://www.geekinsta.com/get-started-with-blazor/ | CC-MAIN-2020-40 | refinedweb | 1,320 | 69.07 |
Both the JNDI and LDAP models define a hierarchical namespace in which you name objects. Each object in the namespace may have attributes that can be used to search for the object. At this high level, the two models are similar, so it is not surprising that the JNDI maps well to the LDAP.
You can think of an LDAP entry as a JNDI DirContext. Each LDAP entry contains a name and a set of attributes, as well as an optional set of child entries. For example, the LDAP entry "o=JNDITutorial" may have as its attributes "objectclass" and "o", and it may have as its children "ou=Groups" and "ou=People".
In the JNDI, the LDAP entry "o=JNDITutorial" is represented as a context with the name "o=JNDITutorial" that has two subcontexts, named: "ou=Groups" and "ou=People". An LDAP entry's attributes are represented by the
See
As a result of federation, the names that you supply to the JNDI's context methods can span multiple namespaces. These are called composite names. When using the JNDI to access an LDAP service, you should be aware that the forward slash character ("/") in a string name has special meaning to the JNDI. If the LDAP entry's name contains this character, then you need to escape it (using the backslash character ("\")). For example, an LDAP entry with the name "cn=O/R" must be presented as the string "cn=O\\/R" to the JNDI context methods. For more information about Names check out the
JNDI Tutorial. The
LDAP names as they are used in the protocol are always fully qualified names that identify entries that start from the root of the LDAP namespace (as defined by the server). Following are some examples of fully qualified LDAP names.
cn=Ted Geisel, ou=Marketing, o=Some Corporation, c=gb cn=Vinnie Ryan, ou=People, o=JNDITutorial
In the JNDI, however, names are always relative; that is, you always name an object relative to a context. For example, you can name the entry "cn=Vinnie Ryan" relative to the context named "ou=People, o=JNDITutorial". Or you can name the entry "cn=Vinnie Ryan, ou=People" relative to the context named "o=JNDITutorial". Or, you can create an initial context that points at the root of the LDAP server's namespace and name the entry "cn=Vinnie Ryan, ou=People, o=JNDITutorial".
In the JNDI, you can also use LDAP URLs to name LDAP entries. See the LDAP URL discussion in the | http://spec-zone.ru/Java/Tutorials/jndi/ldap/jndi.html | CC-MAIN-2018-39 | refinedweb | 420 | 61.16 |
Aastra Dialog 4223 Professional
Here you can find all about Aastra Dialog 4223 Professional like manual and other informations. For example: review.
Aastra Dialog 4223 Professional manual (user guide) is ready to download for free.
On the bottom of page users can write a review. If you own a Aastra Dialog 4223 Professional please write about it to help other people. [ Report abuse or wrong photo | Share your Aastra Dialog 4223 Professional photo ]
Manual
Preview of first few manual pages (at low quality). Check before download. Click to enlarge.
Aastra Dialog 4223 Professional
User reviews and opinions
Comments posted on are solely the views and opinions of the people posting them and do not necessarily reflect the views or opinions of us.
Documents
Headset See section Headset - Dialog 4223 Professional on page 114. Volume control To adjust the volume. Also space/backspace in writing mode. Clear To disconnect calls or to clear the display in programming. Microphone Optional key panel 17 Dual-Function programmable keys per key panel. Four panels can be connected. Note: Use only optional key panels of type DBY 419 01.
Loudspeaker Handset with hearing aid function Please note: The handset may attract and retain small metal objects in the earcap region.
Dialog 3213 Executive
Display 3x40 characters. See section Display info on page 14. Menu Function keys The functions depend on the traffic state and will be shown on the last line of the display. When you are requested to (see display), press the required key to access the function. 2nd Key for access to secondary key functions (these functions are stated on the second line of the corresponding key). Message / Info a. To send and receive messages. See section Messages on page 62. b. To enter information. See section Absence Information on page 57. Dual-Function programmable keys (A-N) Storing numbers, program functions. See section Settings on page 100. Dual-Function programmable key (C) / Headset key a. Storing numbers and program functions. b. The Headset function is only available with option unit (DBY 410 02) installed. The Headset key is programmed by the system administrator. See section Accessories on page 111. Transfer / Diversion a. Transfer an ongoing call. See section During Calls on page 35. b. Activate/Deactivate diversion. See section Call Forwarding on page 50. Inquiry / Conference a. To make an inquiry to an internal or external party. b. To establish a telephone conference. See section During Calls on page 35. Line 2 / Read & a. Line key 2 for in and outgoing calls. b. Read information. See section Absence Information on page 57. Line 1 / Save/Redial a. Line key 1 for in and outgoing calls. b. Save or redial an external number. See section Outgoing Calls on page 21. Volume control To adjust the volume. Also space/backspace in writing mode.
Mute To switch the microphone on or off. See section During Calls on page 35. Loudspeaker on/off To switch the loudspeaker on or off. See section During Calls on page 35. Clear To disconnect calls or to clear the display in programming. Microphone Optional key panel (A-Q) 17 Dual-Function programmable keys per key panel. Four panels can be connected. Note: If one or two key panels are used, the optional key panel DBY may be used. However, if three or four key panels are used, all optional key panels must be of type DBY 409 02.
Phone keys Dialog 4223 / Dialog 3213
This table gives you an overview of the different key design of the Dialog 4223 Professional and the Dialog 3213 Executive. In this user guide you will only find illustrations of the Dialog 4223 keys. If you are using the Dialog 3213 Executive, please refer to the table below to find out the appropriate key combination. Key Dialog 4223 Dialog 3213
Headset
Loudspeaker
Programmable Function key
X h s m g
Volume
Lamp indications
The key lamps on your telephone indicate with different signals the traffic state of the ongoing call or function. Extinguished lamp Steady light Slowly flashing lamp Rapidly flashing lamp Light with short breaks The function is not active. The function is active. The line (or function) is put on hold. An incoming call or message waiting. Ongoing call.
Display info
The display assists your actions on the phone with step-by-step instructions. When your phone is idle, the upper line shows general information. The mid line shows your name and extension number. The lower line presents lead texts for the menu keys.
12 May 10:35 +15 ANDERSEN ANDREAS directory
200 redial
During an internal call the middle line shows the other partys name, directory number and status.
12 May 10:35 BURNES BOBBY +SPEECH
If you make an internal call to someone who has activated a diversion, the first line shows the name and extension number of the person you called and the middle line shows where the call is diverted.
DAVID CHAMBERS BURNES BOBBY FREE call-back
During an incoming external call the middle line shows the other partys number and status.
12 May 10:35 +save
SPEECH
The provisioning of external calling numbers is network dependent. If it is not provided, the display shows EXTERNAL and the directory number of the external line. Even when it is provided it might happen that callers are suppressing their numbers, in this case the display shows DISPLAY RESTRICTED. If a name is available to the external callers number in your system, it is also shown on the display. (Please contact your system administrator whether the feature Name presentation for external calls is available in your system).
Status information
Status information during internal calls:
BLOCKED BUSY CALLING CONFERENCE CONGEST DISPLAY RESTRICTED FREE FREE L2 INCOMPLETE INTRUSION NOT ALLOWED TO PICK UP FROM COB PARKED PARKED CALL RECALL SPEECH UNAVAILABLE UNKNOWN WAIT & % C! +15^
The called number is blocked. The called extension is busy. Incoming call. Conference. Congestion in the system. ISDN call, Number Secrecy is activated on the called/calling extension. The called extension is free. The called extension is free on Line 2. The number was incomplete. Intrusion. Not allowed to pick-up incoming calls from the Common Bell. The called extension has put a call on hold. A call is put on hold. Recall from an individually call that has been put on hold. Speech mode. The dialled number is unavailable. Number unknown. Camp-on mode. The called extension has Text info stored. The called extension has Voice info stored. Missed calls Indicates outside temperature and tendency (up or down) if your telephone system is equipped with optional temperature sensor.
Tones are audible in the handset. Dial tone
(System ready to accept digits)
Special dial tone
(System ready to accept digits, active diversion on telephone)
Ringing tone
(Ringing signal to called party)
- repeated after 4 s - repeated after 4 s
Special ringing tone
(Sent to all participants in a Conference)
- repeated after 15 s
Signals
Ringing signals are emitted from the phone. Internal ringing signal External ringing signal Automatic Callback signal Note: The tones and ringing signals in this guide refer to the standard system but may vary between countries. - repeated after 4 s - repeated after 4 s
Incoming Calls
Internal calls
A ringing signal and a flashing lamp indicate an incoming call. The display shows the number and the name of the internal caller.
External calls
A ringing signal and a flashing lamp indicate an incoming call. If you are connected to a digital trunk line (ISDN), the display shows the number of the external caller and in case of diversion in the public net the display shows the number of the diverted as well as the calling party, see also section ISDN Facilities on page 85. A trunk line is the same as an external line.
Line 1
Answer calls
Lift the handset.
Handsfree
Press without lifting handset. Or: Press without lifting handset. You are connected to the caller via the loudspeaker and microphone. Press to terminate a handsfree call.
To another extension (Call pick-up)
pick-up
You can answer a call to another extension from any phone in your office. Call the ringing extension. You receive busy tone.
12 May 10:35 +15 ANDERSEN ANDREAS camp-on call-back
200 pick-up
BUSY intrusion
Press (see display).
Allow calls on Line 2
Free On 2nd Access
If you also want to receive calls also while speaking you first need to program Free On 2nd Access on a programmable key. See section Settings on page 100. Press to activate / deactivate Free On 2nd Access (pre-programmed). When Free On 2nd Access is active the lamp lights and you can receive calls while speaking.
Answer a second call
Line 2
You are on the phone, when a muted ringing signal and a Line key flashes to indicate a new incoming call: Press the flashing Line key. The first call is put on hold. Note: If you want to see who is calling, first press L2-info (see display). To switch back to the first call: Press the first Line key. The second call is put on hold. You are connected to the first caller.
Press if you want to terminate the ongoing call.
Silent Ringing
This function is useful if you do not want to be disturbed by the ringing of the telephone. Incoming calls will only be indicated on the display and by the flashing Line key. Note: For the Dialog 3213 this function requires the release number R9B or higher, see the underside of your telephone.
In idle mode: Press to mute the ringer for incoming calls.
Save and redial incoming calls
When you receive an incoming external call, you can save the number in order to redial it easily (the number can contain 24 digits maximum). Previously saved number is erased.
Save number
Before you quit the call:
Redial number redial
Press to redial the saved number (see display).
Outgoing Calls
Sometimes you make a call but the person is not available. These functions will help you in your attempts to establish contact with the called party.
Make calls
How to make internal and external calls.
z 0z u d
Enter either a directory number to make an internal call. Or: Enter the digit(s) for external line access and the desired public number. Note: Which digit to press for external line access, depends on the configuration of the system. Lift the handset. Note: You can make your calls faster, using Common Abbreviated Numbers and by programming your own Abbreviated Numbers. Press to end the call.
12 May 10:35 +15 CONFERENCE
Individual Hold
Line 1 Line 1
You have an ongoing conversation, i.e. the Line 1 key is lit. Now you want to put the ongoing call on hold for a short while. Press the Line key. The lamp flashes slowly. Press again to retake the call that has been put on hold.
Common Hold
Press (pre-programmed). The Line key lamp flashes slowly. The call can be picked up on any extension within one minute, if not it will recall on the holding extension. Press to pick-up on own extension. Or: Pick-up on another extension: Enter the extension number that put the call on hold. Press (see display).
Call List
The Call List includes a complete history of recently made calls. It offers access to previously dialed/received, internal/external numbers The Call List provides following options: Indication of the total number of calls (maximum 20) Calling or erasing the listed numbers Scrolling through the list Indication of time and date of the calls Indication of the number of call attempts
In case of any calls in the list the menu key list is activated. Additionally you are notified about missed and unchecked calls with CALLS ! See display below:
12 May 10:35 +15 ANDERSEN ANDREAS directory list
CALLS ! prog
Retrieve calls
To see the first entry in the Call List:
Press (see display). The display shows e.g.:
12 May 10:35 +call next
[<time
1/20 erase
Incoming/outgoing calls are shown as: [<-. incoming call answered !<-. incoming call not answered = missed call [->. outgoing call 1/20 indicates the first of the 20 stored calls in the list. If a name is available to the external callers number in your system, it is shown alternating to the number. (Please contact your system administrator whether the feature name presentation is available in your system) Note: If you do not react within 30 seconds the display reverts to idle state. If you want to leave the function before the time-out, press the Clear key.
next call
Press to scroll through the list (see display). Press to call the selected number (see display). When the call is successful, the number is automatically removed from the Call List. The system automatically adds the digit(s) for external call access. Note: If digit(s) for external call access has not been defined for your Call List, contact your system administrator.
Show date, time and call attempts for the selected call
When you are retrieving calls from your Call List.
Press to see the date and time for the selected call (see display). You will see when the call was dialed/received and how many times the same call was sent/came in.
12 May 10:35 CALL: +May 08:22 12x return
Press to return to the previous display (see display).
Erase calls from the Call List
Press to erase the selected call (see display). The call is erased from the list and the next call is displayed. The display will inform you if there are no more calls in the list. Note: If you do not react within 5 seconds the display reverts to idle state. If you want to leave the function before the time-out, press the Clear key.
Call Metering
When the BusinessPhone Communication Platform is provided with metering information from the public net, the call metering function can be used to check the cost of outgoing calls. The BusinessPhone Communication Platform offers several options to obtain this information.
Cost Indication
During an outgoing external conversation the display shows the actual cost. If you want to deactivate the Cost Indication you have two options: To deactivate the indication of the ongoing call:
cost-off
Press (see display). To toggle between cost indication or no cost indication. The system will only show the call duration in case of an incoming external call or if the public net does not provide the system with metering information. To deactivate the indication for all further calls: Press. Verification tone, the Cost Indication is deactivated. Press. To activate the Cost Indication again for all further calls, repeat the procedure.
Cost of the last call
*46# *45#
After finishing an outgoing external call, you have the possibility to see the cost of the last call. Press. The display shows the cost of the last call. Press to finish the procedure.
Read out your own cost counter
This is useful, when you want to check the accumulated cost of your own counter. Press. The system shows the accumulated cost since the last reset. Press to finish the procedure.
Read out cost counter for others
If you have the authority, you can read out and reset the cost counters for other extensions and trunk lines. If your system is equipped with a printer you can initiate a printout. Press. The system shows the accumulated cost of your own extension since the last reset.
12 May 10:35 +15 OWN COSTS: 50 other check
EUR return
Press (see display). The system requires a Password. Enter the Password. Ask your system administrator for the defined Password.
activate
In case of a typing error, press the Volume Down key to delete the latest entered digit. Press to confirm the Password (see display). Select the type of meter you want to read out.
Note: If you do not acknowledge the Notification within the pre-programmed time, the connection is cancelled and repeated later (ask the system administrator for the programmed number of Notification attempts).
Program Notification number and time
Press to view the Mailbox. Note: Depending on the configuration, you might be asked for your Password.
administr
12 May 10:35 +15 ADMINISTRATION outcall
outcall number change
Press (see display). Press (see display). Press (see display). Enter the digit(s) for external line access and the desired public number. The number can consist of up to 24 digits. Note: Which digit to press for external line access depends on the configuration of the system.
Press to save the number (see display).
12 May 10:35 +15 OUTCALL NOTIFICATION NOT ACTIVE number time on return
time change
Press (see display). Press (see display). Enter the Notification time. The time is entered in 24h format, e.g. 2030 for half past eight. Values are automatically set to even quarters, i.e. 2013 will be 2015.
immediate
Press if you want immediate Notification (see display). Press to save the Notification time (see display). This step is excluded if you program immediate Notification. Press to finish programming.
administr outcall on
Activate/deactivate the Notification
Press. Press (see display). Press (see display). Press to activate (see display). Or:
Press to deactivate (see display). Note: The Notification number and time must be programmed before you activate the Notification. Press to finish programming.
Check and store received messages
You can check and store your received messages. Received messages are divided into the following three categories: New messages (not heard or read) Heard/Read messages Stored messages
Voice messages can also be forwarded to other Mailbox numbers (Individual or Common), see section Forward a Voice message on page 69. Note: Messages are deleted from the system after a certain time. The time depends upon the category of the message. Please ask your system administrator regarding this.
The Account Numbers can also be used via the DISA function, see section Direct Inward System Access (DISA) on page 94.
Verified or own Account Number
Press. This code cannot be entered during the call. Or: Press (pre-programmed). Enter Account Number and press. Valid digits 0-9.
DTMF Tones.
Immediate Answer
It is possible to get automatic hands-free answering on internal calls without pressing the Line key. If you require this facility, please ask your system administrator. Press the Immediate Answer key (pre-programmed). Incoming calls will be indicated by one muted ringing signal, the On/Off lamp lights and the call comes straight in through the loudspeaker. Note: To accept a transferred external call you must first press the Transfer key.
Cancel Immediate Answer
Press the Immediate Answer key (pre-programmed). The lamp extinguishes.: Press. Press. During the procedure the other party is put on hold. When the procedure is ready you will receive a special ringing tone and the call is resumed in the non-IP net.
12 May 10:35 +15 SPEECH PATH REPLACEMENT
Note: A switch to a non-IP Call can only be performed if the original call is an IP Call, otherwise you will receive a Blocking tone. analyzed and the cheapest routing will be selected.
Use Least Cost Routing
Enter the digit(s) for external line access and the desired public number. The usual way of making an outgoing external call. Note: Which digit to press for external line access depends on the configuration of the system.
Calling Least Cost Routing
If LCR has been installed in your system, but your extension is not configured to use it automatically, you also have the opportunity to get the cheapest connection by dialling the LCR code before you dial an external number. Enter the LCR code. Please ask your system administrator for the LCR code. Enter the digit(s) for external line access and the desired public number. Note: Which digit to press for external line access depends on the configuration of the system. You can also program the LCR code on a Function key.
Write Text
It is necessary to write text, e.g. when you are typing Absence Information, sending a Text message or searching the integrated telephone directory. Use the keypad to write text, e.g. when you are sending a Text message. You have selected text mode. Select characters by pressing digits repeatedly.
Example: Press a digit 1 time 2 times 3 times 4 times result result result result J K L 5
Note: Key
1 is reserved for national characters.
Press the Volume Up key to enter the character. Moves cursor to next position. Use also for space. Press the Volume Down key as backspace to erase incorrect entry. Example: Enter the first character code, followed by the Volume Up key. This sequence - numbers always followed by the Volume Up key - gives the word IN_. Note: You can also write the following characters: ? -., !: /# * Press repeatedly.
Settings
If you require frequent use of certain functions, you may program them on the Dual-Function keys on the telephone and the key panel. When you want to use the function, just press the key. Notes: The Dual-Function keys allow programmed functions and short numbers to be combined on the same keys. Remove the transparent cover in order to write the name beside the key. Put the name referring to the programmed function in the field above the line to indicate that it is the primary function. If a function is already programmed on the key, this will be displayed when you start programming. Programming of Dial-by-Name keys and Individual Abbreviated Numbers are described in section Abbreviated Numbers and how to program a new diversion address is described in section Call Forwarding. Automatic Callback Answer calls, to another extension (Call pick-up) Intrusion 8 4
Handset and loudspeaker volume
Use the volume keys. You can set different volume levels for internal and external calls and for Background Music. During a call, adjust handset listening volume in handset mode. Adjust loudspeaker volume in Monitor mode or during Background Music. Press to change the volume.
For people with impaired hearing, the handset hearing volume level can be extra amplified. To change the level: Press and hold simultaneously until a ring signal is heard. The display shows:
Setting Mode
The Line 1 key lamp indicates the setting of the option unit: ON = amplified volume level. OFF = default volume.
Press to change to amplified volume level, Or: Press to change to default volume,
Press to save setting and exit. Note: A level change also effects a headset connected to the headset outlet.
Ringing signal
By programming, you can adjust ringing type (2 types), ringing volume (10 steps) and ringing character (10 characters).
Press (see display). You can now select ringing type, volume or character.
Ringing type
Select type 1 if you want to set the ringing volume at a constant level, select type 2 if you want gradually increasing volume when the phone rings.
type next
Press (see display). You will hear the selected type. Press to change (see display). Press to finish the procedure. Note: When type 2 is selected, the programming of the ringing volume is not applicable.
Ringing volume volume lower
Press (see display). You will hear the selected volume (0.lowest volume, 9.highest). Press lower or higher to change the level (see display). Press to finish the procedure. Note: This programming is not applicable when you have selected ringing type 2.
Ringing character character next
Press (see display). You will hear the selected character. Press to change (see display). Press to finish the procedure.
Melody programming
If you want a personal melody when your telephone rings, this can be programmed for internal, external or Callback calls. Note: This function requires a certain release number of your telephone (for the Dialog 4223 Professional/Dialog 3213 it is R9B or higher, see the underside of your telephone). If you can enter Melody Mode your telephone supports this function.
Each key panel offers 17 additional keys for storing of your most frequently used telephone numbers and functions, and for supervising extensions. Your telephone can be expanded with up to four key panels. Note: If one or two key panels are used, the optional key panel DBY may be used. However, if three or four key panels are used, all optional key panels must be of type DBY 409 02.
Option unit
The Option unit DBY 420 01/1 is an optional accessory, to be installed on the bottom of your telephone set. The following devices can be installed via the Option unit: Extra bell or busy indication outside your door
To check or set the option unit for extra bell or for busy signal: Press and hold simultaneously until a ring signal is heard. The display shows:
OPTION PROGRAMMING
The Line 2 key lamp indicates the setting of the option unit: Off=Extra bell On=Busy signal lamp Flashing=Combined extra bell & busy lamp.
Press to change to busy signal, Or: Press to change to extra bell & busy signal, Or: Press to change to extra bell. Press to save the setting and exit. Note: If you do not press #, the phone automatically returns to idle about 30 seconds after the last key press.
Dialog 3213
The Option unit DBY is an optional accessory, to be installed on the bottom of your telephone set. The following devices can be installed via the Option unit: Tape recorder Extra bell or busy indication outside your door Enhanced Headset functionality PC Sound Card Second handset Note: For people with impaired hearing the Option unit offers the possibility to amplify the receiving volume in the handset and headset.
Extra handset
Useful for involving a second person in your conversation, for talking or just listening.
Tape recorder
When a recording of the telephone conversation is needed, for evidence purposes, a tape recorder can be connected.
Headset - Dialog 4223 Professional
How to install the headset, see section Installation on page 119. The following headset functions are available.
Activate/Deactivate the headset
Press the Headset key to activate/deactivate. See section Description on page 6. All calls can be handled via the headset.
Press the flashing Line key to answer. Press to terminate a Headset call.
Enter the number. Press to terminate the call.
Headset to handset
Handset to headset
Press the Headset key.
Loudspeaker Paging All members of an extension group are paged, i.e. receive a short, sharp tone on the loudspeaker followed by a Voice message from the sender. See section Group Features on page 80. Mailbox The Mailbox system controls the messages that are left for or sent by you when you are absent. See section Messages on page 62. Message A message can be sent to any extension. This is useful when you receive the busy tone or get no answer. There are three kinds of message: 1. Call Me message. 2. Text message (only to a display phone). 3. Voice message. See section Messages on page 62. Metering Outgoing external calls can be metered on individual call meters or specified Account Numbers. See section Call Metering on page 43. Mute To switch the microphone temporarily off. See section During Calls on page 35. Night Switching Used for directing all incoming calls to one extension (answering position), for example when the office is closed. See section Other Useful Features on page 90. Password A four-digit code needed to e.g. block your extension and retrieve messages from the Mailbox system. You can set your own Password. See section Security on page 77. PBX Private Branch Exchange. Your telephone switching system (e.g. BusinessPhone 250). Pre-defined text Pre-programmed absence information. See section Absence Information on page 57. 131
Third party A third connection (person), which can be included in an ongoing two person conversation. The connection can be internal or external. See section During Calls on page 35. Tie line An external line from the private network.
Transfer During an internal or external ongoing call you can make an inquiry and then transfer the call to another party (internal or external). See sections During Calls on page 35 and Useful Hints on page 118. Trunk line A trunk line is the same as an external line. Can be either digital or analog.
A Abbreviated Numbers 27 Common 28 Individual 29 Absence Information 57 Change 60 Diversion 61 Enter 58 Erase 60 For another extension 60 Free text 59 Pre-defined 58 Voice 59 Accessories 111 Account Number 95 Alternative programming for Automatic Callback, Camp-on, Intrusion 104 Answer an incoming call from an ISDN-line 86 Automatic Callback 23 Automatic Redial 24 B Background Music 92 Block extension 79 Busy extension 26 Bypass blocked extension 78 Bypass call forwarding 27 C Call Forwarding 50 Diversion when caller receives busy tone 50 Diversion when there is no answer 50 Fixed Diversion 51 Follow-me 56 Individual Diversion 53 Call List 40 Call Metering 43 Cost Indication 43 Cost of the last call 44
D4 mode information
The Dialog 4223 Professional phone can be connected to the exchange in two different modes (user interfaces), either D3 mode, or D4 mode. There is one user guide for each mode. To find out the mode for your telephone, check the right hand side of the second row of the display (see picture), when the telephone is in idle mode: No extension number is shown (i.e. blank) - your telephone is using D4 mode = This is the correct guide. Extension number is shown - your telephone is using D3 mode = This is not the correct guide, download the user guide from:
Brown James Absence 2222 11:06 Account Authority 28 Aug 2008 more.
Note: This user guide is not valid for the Dialog 4223 Professional in D3 mode. Dialog 4223 Professional/Dialog 4225 Vision 9
Dialog 4225 Vision
Display See section Display information on page 16. Display menu keys The key functions depend on the traffic state. When you are requested (see display), press the required key to access the feature. Navigation key left Navigate one step to the left in the top menu. See section Display information on page 16. Home Return to home position (idle mode), when you are navigating the top menu. See section Display information on page 16. Navigation key right Navigate one step to the right in the top menu. See section Display information on page 16.
Callback Indicating/activating Callback. See section When you receive a busy tone on page 40. The feature can be removed or moved to another programmable function key by your system administrator. Diversion (Follow-me) Indicating/activating and deactivating Diversion (Follow-me). See section Call Forwarding on page 62. The feature can be removed or moved to another programmable function key by your system administrator. Programmable function keys Program numbers or features. See section Programming of function keys on page 98. Note: The key marked with a b is also used to program a melody, see section Melody Ringing on page 109.
Pull-out leaf for easy guide (optional) See section Pull-out leaf (optional) on page 121. Key panel With 17 programmable keys. Up to four panels can be connected. See section Key panel on page 117. Use the Designation Card Manager to make and print your own key panel designation cards, see below. Designation card Use the DCM (Designation Card Manager) to make and print your own designation cards. DCM is included on the Enterprise Telephone Toolbox CD or it can be downloaded from: http:// For more information, please contact your Aastra Certified Sales Partner.
ShowDate
Menu structure Dialog 4223 Professional
Menu structure for each of the menus that can be selected from the idle menu. When you are navigating the menus, a selected menu is marked with a black frame. Idle display menu keys n Missed* CallList PhoneBook more.
Call List Unanswered calls Outgoing calls Incoming calls
Absence Account Authority Lock/Open LogOn/Off Timer Redial Program
Select Profile Direct Diversion to nnnn** Follow Me Absence reason External Follow Me Do not Disturb Div on no answer to nnnn** Div on busy to nnnn** Program mode key: RingChar: Programming of function keys*** Display Contrast Melody Programming Firmware Indication Headset Preset Local Test Mode Option Unit Settings Set Hearing Level
Explanations * Only shown when there are missed calls. n = Number of missed calls. ** Current number is shown. *** Text is not shown on the display.
PhoneSet Hide/ShowMenu
Menu structure Dialog 4225 Vision
Menu structure for each of the menus that can be selected from the idle menu. When you are navigating the menus, a selected menu is marked with a black frame. Top menu Program PhoneSet CallList PhoneBook Messages
Programming of keys
Display Contrast Melody Programming Firmware Indication Headset Preset Local Test Mode Option Unit Settings Set Hearing Level
Central Directory
Message Waiting
Program mode key: RingChar: Programming of function keys***
Call List Unanswered calls Outgoing calls Incoming calls Idle display menu keys n Missed* Absence Account more.
Explanations * Only shown when there are missed calls. n = Number of missed calls. ** Current number is shown. *** Text is not shown on the display. Home. Return to home position, when navigating the top menu.
Select Profile Direct Diversion to nnnn** Follow Me Absence reason External Follow Me Do not Disturb Div on no answer to nnnn** Div on busy to nnnn**
Authority Lock/Open LogOn/Off Timer Redial Hide/ShowMenu
Display language (optional)
One of the following languages can be selected to display information on your phone. Digit 09 = the language code: 0 English 1 French 2 German 3 Spanish 4 Italian 5__________ 6 _________ 7 _________ 8 _________ 9 _________ Note: By default 5-9 are programmed for English. These can be changed locally to other languages.
*08* (09) #
To select a language: Dial. Enter the language code. Press.
Free Seating
The Free Seating feature is used for persons who have an office extension number but no phone set of their own. For example, flexible office workers, persons mostly working outside the office, etc. As a Free Seating user and working from the office, you logon to any free phone set that will be temporarily assigned with your extension number and your system authorities.
** ( ) *51* ( ) *z #
To use: Dial and press the relevant digit. Note: Finland, dial
* * ( ); Sweden, dial ( ) #. * * ( ).
To program and alter individual Speed Dialing numbers: Dial and press the selected digit. Note: Finland, dial
Press and dial the phone number.
Press. Note: The programmed number may consist of a maximum of 20 digits plus , which indicates the second dial tone from the public network.
#51* ( ) # #51#
To erase one programmed number: Dial and press the selected digit. Note: Finland, dial Press.
#51*(19)
To erase all programmed numbers: Dial. Press.
Dial by a function key
Both features and phone numbers can be programmed on a function key. To program a key, see section Programming of function keys on page 98. Press the function key. This function key is programmed by you.
Head office
Dial by Phonebook
By use of the Integrated Telephone Directory you can search for a name, group, operator, etc. via your display and then call the desired person or group by use of a menu function key below the display. On the Dialog 4223 Professional:
PhoneBook
Press to enter the Phonebook (see display). Continue with any of the Phonebook options.
On the Dialog 4225 Vision: Select PhoneBook in the top menu (see display). Press (see display). Continue with any of the Phonebook options.
Phonebook options:
Delete Space Find Exit
Press to delete the last entered character (see display). Press to enter a space (see display). Press to search using the entered characters (see display). Press to return to the previous menu (see display). Use the key pad to enter the characters of the name. The characters are shown above the keys. Example: Select characters by pressing digits repeatedly. The cursor is moved automatically when you stop pressing.
Press a digit. 1 time result A 2 times result B 3 times result C When the desired character is shown on the display, wait for the cursor to move to the next place. The name must be entered as follows: Family name - Space - Name. It is not necessary to enter all the characters, just as many to get as close as possible to the requested name when you start to search. Note: If you want to specify the person's first name, you must enter the full family name before you can enter a space.
Example:
To search for Bob Smith: Press for S Press for M Press for I The display shows:
Brown James 2222 11:06 Space PhoneSet CallList Find 28 Aug 2008 Exit PhoneBook Messages 11:Aug 2008 Brown James 2222
Delete Program
Delete Space
Press to find (see display). If SMI was sufficient to find Bob Smith, the display shows:
Smith Bob 3333 Smith John 3434 Call Up Down more. PhoneBook Messages
Program PhoneSet CallList Sanders Anne 1234 Smith Bob 3333 Smith John 3434 Swanson Kate 3654 Call Up
If SMI gives a name close to Bob Smith, e.g. Ann Smith, scroll down until you find the requested name.
Call Up Down more. Details Exit Back Return
Press to call the framed number (see display). Press to scroll up through the name list (see display). Press to scroll down through the name list (see display). Press to show more options (see display). Press to show additional directory information (if available) for the framed name (see display). Press to exit the PhoneBook menu (see display). Press to go back and enter a new name (see display). Press to return to the previous menu key options (see display). The display will inform you if no name matches your search and show the name alphabetically preceding the name you entered.
Data privacy
Data privacy allows you to make a call without any disturbances, i.e. Intrusion. This feature is automatically cancelled when the call is finished.
u *41# z
To order: Lift the handset. Dial and enter the number.
Authorization Code, common
If you are authorized to use a common Authorization Code (1 to 7 digits) you can temporarily change any phone used within the exchange to the authority level connected to this code. You can use the code for one call only or you can open the phone until you lock it when leaving the phone. To use for a single call:
Press (see display). If Authority is not shown, press more. until it appears. Enter Authorization Code and press (see display). Verification tone. Note: You can also dial and press.
Open Enter
* *, enter the code
Dial the digit or digits to get an external line and the external number. To open an extension for several calls: Press (see display). If Open is not shown, press more. until it appears. Enter Authorization Code and press (see display). Verification tone. Note: You can also dial and press.
# *, enter the code
To lock an extension:
Lock Enter
Press (see display). If Lock is not shown, press more. until it appears. Enter Authorization Code and press (see display). Verification tone. Note: You can also dial and press.
Press to activate the Call Duration feature (see display). If Timer is not shown, press more. until it appears. The display shows:
11:06 00:00
Start Program Clear PhoneSet CallList
ShowDate Exit
Start Clear
PhoneBook Messages 11:06 00:00 Brown James 0012345678 2222
Key functions that are available during call duration mode:
Start Clear ShowDate Exit Stop ShowTimer
Press to start the timer (see display). The elapsed time is shown. Press to clear the timer (see display). Press to show date (see display). Press to exit the Call Duration feature (see display). Press to stop the timer (see display). Press to show the measured time (see display).
Automatic Timer
The timer automatically starts when the called person answers, and automatically stops when the call is finished. Both outgoing and incoming calls are measured. If you make inquiries, conferences, or put calls on hold, etc. during the call, the timer is not stopped. I.e. the time measured is the total time from when the first called person answers, until the call to the last connected person is finished. Note: The timer shows the elapsed time from the last call until a new call has been answered. If you need to keep a record of your calls, always write down the time at once when a call has been finished.
Press to show the Call Duration feature (see display). If Timer is not shown, press more. until it appears. The display shows:
Program
PhoneSet
ShowDate Exit ShowTimer
Press to show date (see display). Press to exit the Call Duration feature (see display). Press to show the measured time (see display).
Call Forwarding
Diversion
If you do not want to be disturbed or will be out of the office, you can have all calls to your extension diverted to a preprogrammed answering position. During Diversion you will hear a special dial tone and the Diversion lamp indicates that your Triple Access Line is diverted. You can still make calls as usual. Diversion can be made direct, on no answer, on busy or to another information service facility. Note: If your phone is programmed with Multiple Directory Diversion and Do Not Disturb (ask your system administrator), Diversion is ordered and cancelled simultaneously on all lines.
reason
When a return time or date is requested: Enter the date (MMDD) or time (HHMM) of your return. (Example shows Back on September 15). Note: The order in which the date is stated is system dependent. Press (see display). The display shows the selected absence reason, the time or date of return, and diversion information. Note: You can also use the following procedure to order: dial , enter the absence code (0-9), enter time or date of return (if requested), press and press the Clear key. The absence code is system dependent. Contact your system administrator regarding the available absence codes.
Cancel NoDiversion
*230* z* (09) *0915 # #230* z#
Order for another extension
Dial. Dial the extension number and press. Enter the absence code. Press and enter the date or time of the other person's return. Press. The display on the other person's extension shows the reason for absence and, if entered, time or date of return.
Cancel for another extension
Dial. Dial the extension number and press. Note: If the special dial tone is received, the Authorization Code for the other extension is required. Add the code and press before pressing the Clear key.
Messages
Manual Message Waiting (MMW)
If the called extension does not answer you can initiate a message waiting indication on that extension (if this feature is allowed). If there is a message waiting, the Message key lamp is on and you will hear a special dial tone after lifting the handset.
Answer
Press. Note: The function key is preprogrammed by your system administrator. A call is initiated to the extension that requested Message Waiting.
Checking the party that requested MMW
Dialog 4223 Professional:
Program Select
Press (see display). If Program is not shown, press more. until it appears. Press (see display). Press. Note: The function key is preprogrammed by your system administrator. The number that requested Message Waiting is shown in the display.
Press to finish the procedure (see display).
Dialog 4225 Vision: Select Program in the top menu (see display). Press to select Programming Press. Note: The function key is preprogrammed by your system administrator. The number that requested Message Waiting is shown in the display.
z z # z z z # z z
If you are asked to enter your security code: Enter your security code. Code at delivery = your extension number. From another phone: Dial the number to the Voice Mail system. If you are asked to enter your security code (if the phone you are using has a mailbox of its own): Press. Dial your mailbox number. (normally your office extension number) Enter your security code (if required).
To access someone elses mailbox
Dial the number to the Voice Mail system. If you are asked to enter your security code (if the phone you are using has a mailbox of its own): Press. Dial the mailbox number. (normally the office extension number of the other person) Enter the security code of the other person (if required).
To handle the mailbox
Recorded information on the line tells you the number of new and stored messages. If you have too many messages stored, you will first be asked to delete saved messages. Recorded instructions ask you to press different digits in order to listen to callers messages, record your own greetings, change your password or exit your mailbox, etc. The following diagram gives an overview of the mailbox system and the digits to be used.
Group features
Group Call-pick-up
People working in a team can have their phones programmed by their system administrator to form Call Pick-up groups. In a Call Pick-up group, any member can answer any individual call to group members.
GrpPickUp
Press to answer (see display). If GrpPickUp is not shown, press more. until it appears. Notes: You can also press
One Call Pick-up group can serve as an alternative to another group. Calls to the alternative group can only be answered when there are no calls to your own group. Finland and Sweden, press
Common Bell Group
Calls are signalled on a common bell.
Finland and Sweden, press
Group Hunting
An internal Group Hunting number is a common directory number for a group of extensions. Calls to the group will be indicated at a free extension in the group. When you leave the group temporarily, you make your phone unavailable for incoming calls.
*21* z # #21#
To leave the group temporarily
To re-enter the group
Dial. Note: U.K., dial Press.
*24* z* z # #24* z #
If you are authorized you can divert all calls to your group, to another extension or group: Dial. Dial the number of the group to be diverted and press. Dial the extension number of the new anwering position. Press.
General Deactivation
The following features can be simultaneously cancelled: Callback (all Callbacks are cancelled). Diversion/Internal and External Follow-me. Manual Message Waiting/Message Diversion. Do Not Disturb.
#001#
Night Service
When the exchange is in Night Service mode, all your incoming calls to the operator are transferred to a selected extension or group of extensions. The exchange has three different Night Service modes:
Common Night Service
All incoming calls to the operator are transferred to one specific extension. Answer the call in the normal way.
Individual Night Service
Selected external calls to the operator are transferred to one specific extension. Answer the call in the normal way.
Universal Night Service
All incoming calls to the operator are transferred to a universal signalling device, e.g. the common bell. Answer the call as descibed in section Common Bell Group on page 85.
Hot Line
This feature is programmed by your system administrator.
Delayed Hot Line
When the handset of the delayed Hot Line phone is lifted or when the Line key is pressed, a timer is started. If no digit is pressed before time out, a call is automatically generated to a specific extension or external line. If a digit is pressed before time out the phone works as an ordinary phone.
Direct Hot Line
The same feature as described above, but without a delay. Only Hot Line calls can be placed from this line. To be used e.g. as alarm phone, door phone etc.
Emergency mode
In the event of an emergency the operator can set the exchange into Emergency mode, during which only preprogrammed extensions are permitted to make calls. If your extension is not assigned with this category and you try to make a call, you will not receive a dial tone.
Additional Directory Number
You can be assigned (preprogrammed by your system administrator) one or more Additional Directory Numbers (lines) on free function keys. To answer, make calls and use features on the additional directory lines, use the same procedure as for the Triple Access Line, unless you have other instructions. However, you have to press the additional Line key after lifting the handset. Example:
Additional line
To make a call on an additional directory line: Lift the handset. Press. Note: The function key is preprogrammed by your system administrator. Dial the extension number.
Multiple Represented Directory Number
Your extension number can be programmed on a dedicated key on other system telephones, i.e. your number is represented on these phones. Other extension numbers can of course also be represented on your phone. Note: This feature has to be programmed by your system administrator.
Incoming calls
Incoming calls can be answered (indicated with a flashing key lamp, calling party information and/or ring signal) on all phones where the number is represented.
Outgoing calls
The dedicated key can be used to call the programmed extension. How outgoing calls are handled depends on the programming of the phone, please contact your system administrator regarding this.
Malicious Call Tracing
If you are disturbed by bothersome or malicious external incoming calls, you can request number tracing from the network provider. You can invoke tracing during or after an ongoing conversation. The external line can be held for a limited period of time.
During an ongoing conversation:
TraceMalC
Press (see display). If TraceMalC is not shown, press more. until it appears. Note: You can also press Mal. Call Tracing (The function key is preprogrammed by your system administrator). The system acknowledges with different tones whether the tracing request was accepted or rejected.
DISA = Direct Inward System Access
If you are assigned to use this feature and you are working externally, you can call your office and get access to an external line in order to make business calls. The business call will be charged your office extension number or an account number. You will be charged just for the call to the office. The external phone must be of push button type provided with pound key ( ) and star key ( ) or a mobile phone adapted for dial tone pulses (DTMF). After a completed DISA call you must hang up before a new DISA call can be made. There are different procedures depending on the type of Authorization Code, or when an Account Code is used.
z *72* z# z z *75* z* z# z
With common Authorization Code
Call the DISA feature at your office. Dial tone. Dial. Dial the Authorization Code and press. Dial tone. Dial the external number.
With individual Authorization Code
Call the DISA feature at your office. Dial tone. Dial. Dial the Authorization Code and press. Dial your own extension number and press. Dial tone. Dial the external number.
Call list
With this feature, calls to and from your phone will be logged. By use of the display menu keys below the display, you can browse the Call list, make calls to numbers in the list and delete numbers from the list. You can choose to browse in the complete list of all calls, or in specific lists of unanswered, outgoing and incoming calls. When new unanswered calls have been stored in the list, n Missed is shown in the display (n = number of missed calls). Your phone must be idle and unlocked to be able to browse the Call list.
Press to change the volume. The handset and loudspeaker volume level is stored.
Lift the handset and press.
Extra amplification of the handset/headset hearing volume level
For people with impaired hearing, the handset hearing volume level can be extra amplified. To adjust the level: Note: A level change also effects a headset connected to the headset outlet.
PhoneSet Select Down or Up Select
Press (see display). If PhoneSet is not shown, press more. until it appears. Press (see display). Press to frame Set
Hearing Level
Press (see display). A tone signal is heard, and the display shows the current setting. The Line 1 key lamp also indicates the current setting; key lamp off=standard level, key lamp on=increased level. Press to adjust the volume level (see display). The display shows the new setting. The Line 1 key lamp also indicates the new setting as described above. Press to finish setting (see display). When extra amplification has been selected, the Line 1 key lamp turns off.
Change
Dialog 4225 Vision: Select PhoneSet in the top menu (see display). Press to frame Set
Press (see display). A tone signal is heard, and the display shows the current setting. The Line 1 key lamp also indicates the current setting; key lamp off=standard level, key lamp on=increased level. Press to change the volume level (see display). The display shows the new setting. The Line 1 key lamp also indicates the new setting as described above. Press to finish setting (see display). When extra amplification has been selected, the Line 1 key lamp turns off.
Ring signal volume
Use the Volume keys to adjust the ring signal volume when the phone is in idle mode or ringing. Adjusted volume is stored. Press to adjust the volume.
Mute ring signal
You can suppress the ring signal for an incoming call. Press to suppress the ring signal. The ring signal is switched off for the current call, and your phone is automatically set to Silent Ringing (see below).
Silent Ringing
If you do not want to be disturbed by the ring signal but still want to answer an incoming call, you can switch off the ring signal. Incoming calls are only indicated by a flashing line lamp and display information.
When the phone is in idle mode, or when ringing: Press to switch off the ring signal. The Mute key lamp and the Ringer off symbol are switched on to indicate Silent Ringing. The ring signal will automatically be switched on the next time you Lift the handset or press any key.
Melody Ringing
If you want to replace the ring signal with personal melodies when your phone rings, you can program one melody to signal an internal call, a second melody for an external call and a third melody to signal a Callback call. Dialog 4223 Professional:
Press (see display). If PhoneSet is not shown, press more. until it appears. Press (see display). Press to frame Melody Press (see display). Continue with section Melody mode.
Programming
Dialog 4225 Vision: Select PhoneSet in the top menu (see display). Press to frame Melody Press (see display). Continue with section Melody mode.
Melody mode
The display shows Melody Mode and if there is a stored and activated melody for internal calls (Line 1), external calls (Line 2) or Callback calls (Inquiry), the corresponding key lamp is switched on. In melody mode you can: Program new melodies Edit or delete stored melodies Activate or deactivate stored melodies
Press if you want to exit melody mode (see display). Note: If you do not press any key within 30 seconds, melody mode is automatically cancelled.
Program a new melody, edit or delete a current melody Program
Press (see display). The display shows Program Melody. The upper most function key lamp (for Dialog 4225 the upper most key to the left) is also switched on, indicating Program mode.
Line 2
< or >
Press the key for the requested type of call: If there is a current melody, the melody is played and the last 19 notes or signs are displayed. Press for internal calls, or press for external calls, or press for Callback calls.
To edit the current melody: Press to move the cursor to the right of the position to be edited (see display). Press to erase the note to the left of the cursor. Keep pressed to erase all the notes. To enter a new melody or notes, see section To enter notes on page 113.
Installation
Install cables
Handset cable to the left Handset cable to the right
You can put the cable to the handset into the notch underneath the telephone. The cable to the exchange has to be plugged into LINE and the handset cable has to be plugged into HANDSET.
Change cables
To remove a cable, use a screwdriver to unlock the stop.
Install stands and adapt telephone
Position high Position low
Press to fasten stand
Release to remove stand
Tiltable display Adjustable angle
Install card
Use the DCM (Designation Card Manager) to make and print your own designation cards. DCM is included on the Enterprise Telephone Toolbox CD or it can be downloaded from: http:// For more information, please contact your Aastra Certified Sales Partner. Dialog 4223 Professional:
Install key panels
Fasten the connector in the bottom of the hole using a finger or a blunt tool. Make sure the connector fits before pressing it down.
Press where the arrows are pointing, until you hear a Click sound. Install the stands as shown in the picture in section Stand positioning. Notes: All key panels must be of type DBY 419 01.
Stand positioning (1-4 key panels)
Use the DCM (Designation Card Manager) to make and print your own key panel designation cards. DCM is included on the Enterprise Telephone Toolbox CD or it can be downloaded from: For more information, please contact your Aastra Certified Sales Partner.
Install pull-out leaf (optional)
Remove the protective film from the guiding rails. Attach the guiding rails to the bottom of the phone, observing the direction of the cut corner.
Insert the pull-out leaf.
Wall mounting
The phone can be wall mounted without using a special console. Useful for instance in conference rooms or public areas.
Use a screwdriver to remove the handset hook. Turn the hook upside down and insert.
Use a screwdriver to remove the two plastic covers. Drill wall holes according to measurements given here.
Place screws according to measurements and mount the phone.
M Mailbox 84 Make calls 35 Malicious Call Tracing 94 Manual Message Waiting (MMW) 79 Melody Ringing 109 Message Waiting 81 Messages 79 Manual Message Waiting (MMW) 79 Message Waiting 81 Voice Mail 82 Multiple Represented Directory Number 94 Mute 53 Mute ring signal 108 N Night Service 91 Number Presentation Restriction 36 O Option unit 122 Other useful features 89 Outgoing calls 35 Authority 49 Bypass 43 Call Waiting 42 Callback 40 External calls 35 Handsfree 36 Individual External Line 37 Internal calls 35 Intrusion 42 Last External Number Redial 39 Number Presentation Restriction 36 Redial calls from the Call list 37 Save external number 39 Speed Dialing 44 When you receive a busy tone 40 P Parallel Ringing 33 Personal Number 69 Programming of function keys 98 Programming of ring signal tone character 104 Programming of ring signals 102 Pull-out leaf 121 Put a call on hold 56 R Redial calls from the Call list 37
Redial number 39 Refer Back 54 Ring signal volume 108 Ring signals 15 S Safety instructions 6 Save external number 39 Send Caller Identity Code at transfer 57 Setting form for search profiles 75 Settings 98 Display backlight 116 Display contrast 115 Features and required data 100 Handset and loudspeaker volume 105 Melody Ringing 109 Mute ring signal 108 Programming of function keys 98 Programming of ring signal tone character 104 Programming of ring signals 102
Ring signal volume 108 Silent Ringing 108 Short numbers 44 Silent Ringing 108 Speed Dialing 44 T Timer 60 Tones and signals 14 Transfer 54 Troubleshooting 132 V Voice Mail 82 Volume 105 W Warranty 5 Welcome 4 When you receive a busy tone 40
Subject to alteration without prior notice. For questions regarding the product, please contact your Aastra Certified Sales Partner. Also visit us on
E-RDA-850-LW PEG-SJ30 Ar-m205 VP-D323I 410GSM CD-290DJ LT-26S60 PSR-62 LN32A610 DMR-E85HEB GDU 620 MYZ-55 DT50R DLT-32G1 CMT-ED2 21GR1251 CPC 6128 ESI662X-60 Layout 21PT1664 58S SC-25 ET-608 MP500 Volt SP90 Antara AL-1000 SD-P71SK NN-T573sbbpq Minox LX Space N1000V Advance PL50A450 XM-3546 AX-M82D ICF-C795RC 21HT-15C 16C RY46501B PL-43A82T HT-A100T NV-HD625B T 984 Photosmart 8250 RH7796W DCP850-37 ASD 9UA SAM 2010 Primare I21 SCX-4220 DSC-H1 Pacific P4S61 Annexe A MP101 Hipath 1220 NP2500 NP-N150-jp01 Nokia N93I PD112 PS122KB XR-4200R DVP-SR101p B BH-208 MS-2642DP P50-XR01-1 Blade 2 GA-P35-ds4 4345MFP Focus 2005 Quest Carrera SRE 166 Rino 530 RZ-15LA31 LI 3710 5002V-EW 4000S SE6R2 RS20ncsl NWZ-E436F S3300 Lexmark X654 Multipass F30 IFP-180 Qtouch 2 WEP470 ATA 188 Review Meade LPI BIW125W FE1027G 5100 S SX-KC200 HOW-TOS GR-D200us-gr-d200 DSP-A2 42LH30 8002DX Citadel XR2 Casio 3071 DR-S2 | http://www.ps2netdrivers.net/manual/aastra.dialog.4223.professional/ | crawl-003 | refinedweb | 10,138 | 66.13 |
Java Collection, TreeMap Exercises: Get a portion of a map whose keys are greater than or equal to a given key
Java Collection, TreeMap Exercises: Exercise-23 with Solution
Write a Java program to get a portion of a map whose keys are greater than or equal to a given key.
Sample Solution:-
Java Code:
import java.util.*; import java.util.Map.Entry; public class Example23 { public static void main(String args[]) { // Declare tree maps TreeMap < Integer, String > tree_map = new TreeMap < Integer, String > (); // Put elements to the map tree_map.put(10, "Red"); tree_map.put(20, "Green"); tree_map.put(30, "Black"); tree_map.put(40, "White"); tree_map.put(50, "Pink"); System.out.println("Orginal TreeMap content: " + tree_map); System.out.println("Keys are greater than or equal to 20: " + tree_map.tailMap(20)); } }
Sample Output:
Orginal TreeMap content: {10=Red, 20=Green, 30=Black, 40=White, 50=Pink } Keys are greater than or equal to 20: {20=Green, 30=Black, 40=White, 50 =Pink}
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
New Content: Composer: Dependency manager for PHP, R Programming | https://www.w3resource.com/java-exercises/collection/java-collection-tree-map-exercise-23.php | CC-MAIN-2019-18 | refinedweb | 187 | 59.4 |
Shortcut to plotting in Matplotlib
Matplotlib has a well deserved reputation for being a labyrinth. It has dark twisted passageways. Some lead to dead ends. It also has shortcuts to glory and freedom. In this series I’ll help you get where you want to go as directly as I know how, while steering clear of horned monsters.
Part of Matplotlib is a simplified interface called pyplot that doesn't require you to know about the innards of the system. For the most common tasks, it gives a convenient set of commands. We'll take advantage of it.
import numpy as np import matplotlib.pyplot as plt
To use pyplot in a script, first we import it. We also import numpy, a numerical processing library that is great for working with data of any sort.
Plotting curves
The most common thing to do in Matplotlib is plot a line. First we have to create one.
x_curve = np.linspace(-2 * np.pi, 2 * np.pi, 500) y_curve = np.sinc(x_curve)
We create the x values for our curve using numpy's linspace() function. The way we called it, it returns an array of 500 evenly spaced values between -2 pi and 2 pi.
Then we create the y values using numpy's sinc() function. It's a curve with some personality, so it illustrates the plotting quite well.
plt.figure() plt.plot(x_curve, y_curve) plt.show()
This bit
- initializes the figure,
- draws the curve described by our x and y, and
- displays it on the screen.
And that's it! You just plotted a curve in python. One of the very best things about Matplotlib is how it streamlines common tasks. Once we had our data, it only took three lines of code to make a plot.
Plotting points
The second most common plotting task is show points in a scatter plot. This is streamlined too.
x_scatter = np.linspace(-1, 1) y_scatter = x_scatter + np.random.normal(size=x_scatter.size)
The first step again is create some fake data. Here we generate some evenly-spaced x values between -1 and 1 and make some y values that are similar, but have some normally-distributed random noise added to them (zero mean and unit variance).
plt.figure() plt.scatter(x_scatter, y_scatter) plt.show()
Like before, this bit
- initializes the figure,
- plots each of the points described by our x's and y's, and
- displays the resulting plot on the screen.
And there you have your scatterplot! With just this little bit of Matplotlib, you already know enough to be dangerous. | https://e2eml.school/matplotlib_just_plot_it.html | CC-MAIN-2020-16 | refinedweb | 428 | 76.62 |
Software products slated for the iOS market have to be frugal in their use of memory. iOS devices such as the iPhone and iPad have limited physical memory, much less than their flash storage. Using Xcode can help design frugal code and subject source files to static analysis. You can also use its Instruments tool to track down memory problems at runtime. In this article, I discuss some common memory problems and how they can affect a typical iOS app. I show you how to detect these problems with the aforementioned tools and some ways of fixing them.
You will need a working knowledge of ANSI-C, Objective-C, and Xcode. The sample project needs version 3.x (or newer) of the Xcode development suite.
Types of Memory Problems
Most memory problems are one of four types. The first type is the dangling pointer. This is an object or data pointer that still refers to a deallocated memory block. The block may still have valid data, but the data can "disappear" at some point in time. Attempts to access a dangling pointer may lead to a segmentation fault (
EXC_BAD_ACCESS or
SIGSEGV). A dangling pointer should not be confused with a
NULL, which is defined as
((void *) 0).
Consider the snippet in Listing One. Here, class
FooProblem has a single property (
objcString) and a single action method. The action method,
demoDanglingPointer:, initializes
objcString to an empty
NSString (line 18). Then, in a separate code block, it creates an instance of
NSMutableString (line 20). It sends the instance a release message (line 22), but also assigns that same instance to
objcString (line 25). Once the code block exits, deallocation occurs and
objcString is left holding a dangling pointer.
Listing One
// -- FooProblem.h @interface FooProblem : NSObject { // -- properties:demo NSString *objcString; } // -- methods:demo:actions - (IBAction) demoDanglingPointer:(id)aSrc; @end // -- FooProblem.m @implementation FooProblem - (IBAction) demoDanglingPointer:(id)aSrc { NSString *tBar; objcString = [NSString string]; { tBar = [[NSMutableString alloc] initWithString:@"foobar"]; //... do something else [tBar release]; } //..do something else objcString = tBar; } @end
Now consider now the snippet in Listing Two. This variant of
FooProblem declares a C
struct named
FooLink (lines 1-6). In its
demoDanglingPointer: action, it declares the local variable
tTest and assigns the latter the output from method
danglingPosix() (line 26). The
danglingPosix() method creates a local instance of
FooLink (tBar) inside a code block (lines 38-41). It assigns values to the
struct fields and sets the local
tFoo to
tBar (line 42). But just before the code block exits,
danglingPosix() disposes of
tBar with a call to
free() (line 44) and returns the pointer held by
tFoo (line 48). The result local
tTest now has a dangling pointer.
Listing Two
typedef struct Foo { char *fFoo; unsigned int fBar; struct Foo *fNext; } FooLink; // -- FooProblem.h @interface FooProblem : NSObject { // -- properties //... } // -- methods:demo:actions - (IBAction) demoDanglingPointer:(id)aSrc; - (FooLink *)danglingPOSIX; @end // -- FooProblem.m @implementation FooProblem - (IBAction) demoDanglingPointer:(id)aSrc { FooLink *tTest; tTest = [self danglingPOSIX]; // ...do something else } - (FooLink *)danglingPOSIX { FooLink *tFoo; // initialise the output result tFoo = nil; { FooLink *tBar; tBar = malloc(sizeof(FooLink)); tBar->fFoo = "foobar"; tBar->fBar = 1234; tFoo = tBar; //... do something else free(tBar); } // return the string result return (tFoo); } @end
The next type of memory problem is the double free. This occurs when a code routine tries to dispose of an object or structure that has already been disposed of. Disposal need not happen in succession, so long as it affects the same pointer. A double free also leads to a segmentation fault, followed by a crash.
Listing Three is a classic example of a double free. The action method
demoDoubleFree: creates an instance of
FooLink and populates its fields (lines 3-5). It sends the instance to the method
doubleFreePOSIX:, which updates the two fields (lines 14-15). But then
doubleFreePOSIX: disposes of the
FooLink instance with a call to
free() (line 18). When it returns control to
demoDoubleFree:,
demoDoubleFree: also disposes of the same
FooLink structure using
free() (line 8).
Listing Three
- (IBAction) demoDoubleFree:(id)aSrc { tFoo = malloc(sizeof(FooLink)); tFoo->fFoo = "Foobar"; tFoo->fBar = 12345; [self doubleFreePOSIX:tFoo]; free(tFoo); } - (void)doubleFreePOSIX:(FooLink *)aFoo { //...do something else aFoo->fFoo = "BarFoo"; aFoo->fBar = aFoo->fBar + 123; //... do something else free(aFoo); }
Listing Four shows another double free example. The action method
demoDoubleFree: creates and adds an
NSNumber instance to the mutable array property
objcArray (lines 23-24). Then it invokes the method
doubleFreeObjC. This method parses the array property and uses its entries to create an
NSString object (line 39-40). Later, it sends a release message to each entry (line 44). If the entry is the
NSNumber object, a double free error occurs. This is because the
NSNumber object was marked for autorelease. An explicit release interferes with the autorelease pool's attempt to dispose of the object.
Listing Four
// -- FooProblem.h @interface FooProblem : NSObject { // -- properties NSMutableArray *objcArray; } // -- methods:demo:actions - (IBAction) demoDoubleFree:(id)aSrc; // -- methods:demo:utilities - (void)doubleFreeObjC; @end // -- FooProblem.m @implementation FooProblem // ...truncated for length - (IBAction) demoDoubleFree:(id)aSrc { NSNumber *tNum; tNum = [NSNumber numberWithLong:rand()]; [objcArray addObject:tNum]; //...do something else [self doubleFreeObjC]; } - (void)doubleFreeObjC { NSString *tText; id tObj; tText = [NSString string]; for (tObj in objcArray) { tText = [tText stringByAppendingFormat:@"/@", tObj]; //...do something else [tObj release]; } } @end
A memory leak is another typical memory problem. It occurs where a routine fails to dispose of its objects or structures. The failure may be due to an error or exception, or it may be due to poor code design. A continuous memory leak can lead to a low-memory condition. At best, it could cause iOS to terminate the offending app. At worst, it could force users to perform a hard reset.
Listing Five is one example of a memory leak. This variant of
FooProblem creates an empty
NSMutableArray instance and assigns it to the property
objcArray (lines 17-18). Its
dealloc method, however, does not send a release message to
objcArray. The result is, of course, a memory leak, even if the array object remains empty.
Listing Five
// -- FooProblem.h @interface FooProblem : NSObject { // -- properties NSMutableArray *objcArray; } @end // -- FooProblem.m @implementation FooProblem - (id)init { if (self = [super init]) { // prepare the following properties objcArray = [[NSMutableArray alloc] initWithCapacity:1]; return (self); } else // the parent has failed to initialise return (nil); } //...other methods go here - (void)dealloc { //...do something else // pass the message to the parent [super dealloc]; } @end | http://www.drdobbs.com/cpp/lock-options/cpp/debugging-memory-in-ios-apps/240144285 | CC-MAIN-2014-35 | refinedweb | 1,056 | 58.28 |
Hybrid Testing
Introduction
You can easily test your CAP application using a local database and mocks. But at some point of time, you want to test with real cloud services. Of course, you can deploy your application to the cloud.
With the hybrid testing capabilities, you stay in your local development environment and avoid long turn-around times of cloud deployment and you can selectively decide which services you want to use from the cloud.
Use the
cds bind command to connect your application to services on the cloud. Start your application with the
hybrid profile to use these service bindings. You can switch between local mocking configuration and cloud service configuration, by just setting or omitting the profile parameter.
Bind to Cloud Services
Bind a Local Application to Services on Cloud Foundry
cds bind -2 my-hana:my-hana-key
Binds your CAP application to the service key
my-hana-key for the service instance
my-hana using your currently targeted Cloud Foundry space.
Output:
[bind] - Retrieving data from Cloud Foundry... [bind] - Binding db to Cloud Foundry service cpapp-db key cpapp-db-key with kind hana. [bind] - Saving bindings to .cdsrc-private.json in profile hybrid . [bind] - [bind] - TIP: Run with cloud bindings: cds watch --profile hybrid
The service key needs to be created beforehand.
You can omit
:my-hana-key here, because the key name is just the name of the instance with
-key added.
In many cases CAP knows which CDS service and kind to use for a cloud service. Like in the previous example, the CDS service
db gets bound and set to kind
hana, because the given service instance is of type
hana with plan
hdi-shared.
Learn how to bind to arbitrary cloud services.
The binding information is stored in the .cdsrc-private.json file of your project in the
requires section:
{ "requires": { "[hybrid]": { "db": { "kind": "hana", "binding": { "type": "cf", "apiEndpoint": " "org": "your-cf-org", "space": "your-cf-space", "instance": "my-hana", "key": "my-hana-key", "vcap": { "label": "hana", "plan": "hdi-shared" }, "resolved": false } } } } }
Bindings are assigned to the
hybrid profile by default.
Note that no credentials are saved. Only the information where the credentials can be obtained is stored on your machine.
All
cds bind command line options
Bind a Local Application to Services on Kubernetes
You can bind to Service Bindings of Open Service Broker service instances, such as SAP BTP services, on your Kubernetes cluster and to plain Kubernetes Secrets by adding the
--on k8s option to the
cds bind command:
cds bind -2 <service binding or secret> --on k8s
The command uses your current Kubernetes context. That is your current server and namespace. You need to be logged in as a precondition.
Bind to Kubernetes Service Bindings
To list all Service Bindings in your current Kubernetes context, you can use the
kubectl get servicebindings command:
NAME SERVICE-INSTANCE SECRET-NAME STATUS AGE cpapp-xsuaa-binding cpapp-xsuaa cpapp-xsuaa-secret Ready 11s
Use the service binding name for the
-2 option:
cds bind -2 cpapp-xsuaa-binding --on k8s
Output:
[bind] - Retrieving data from Kubernetes... [bind] - Binding uaa to Kubernetes service binding cpapp-xsuaa-binding with kind xsuaa [bind] - Saving bindings to .cdsrc-private.json in profile hybrid [bind] - [bind] - TIP: Run with cloud bindings: cds watch --profile hybrid
The binding information is stored in the .cdsrc-private.json file of your project in the
requires section:
{ "requires": { "[hybrid]": { "uaa": { "binding": { "type": "k8s", "name": "cpapp-xsuaa-binding", "cluster": " "instance": "cpapp-xsuaa", "namespace": "dev", "secret": "cpapp-xsuaa-secret", "resolved": false, "vcap": { "label": "xsuaa", "plan": "application" } }, "kind": "xsuaa" } } } }
Bind to Kubernetes Secrets
Alternatively, you can bind to Kubernetes Secrets.
You can use the
kubectl get secrets command to list all secrets in your current Kubernetes context:
NAME TYPE DATA AGE cap-hdi-container Opaque 11 44h
Use the secret name for the
-2 option.
You need to provide either the service argument or the
--kind option as well, because secrets have no service meta data.
cds bind -2 cap-hdi-container --on k8s --kind hana
Output:
[bind] - Retrieving data from Kubernetes... [bind] - Binding db to Kubernetes secret cap-hdi-container with kind hana [bind] - Saving bindings to .cdsrc-private.json in profile hybrid [bind] - [bind] - TIP: Run with cloud bindings: cds watch --profile hybrid
If a service binding with the same name exists,
cds bind will connect to the service binding instead.
Run with Service Bindings
Run CAP Node.js Apps with Service Bindings
Now, you can run your CAP service locally using the cloud service bindings:
cds watch --profile hybrid
It will resolve the cloud bindings in your configuration:
- Bindings to Cloud Foundry: The credentials are downloaded from the service key of the Cloud Foundry API endpoint, org and space that were targeted when
cds bindwas being called. This requires that you’re logged in to the right Cloud Foundry API endpoint.
- Bindings to Kubernetes: The credentials are downloaded from the service bindings and secrets of the Kubernetes cluster and namespace that were in the current context when
cds bindwas being called.
You can also resolve and display credentials using the
cds env command:
cds env get requires.db.credentials --profile hybrid --resolve-bindings
Example output:
{ url: 'jdbc:sap://BDB9AC0F20CB46B494E6742047C4F99A.hana.eu10.hanacloud.ondemand.com:443?encrypt=true&validateCertificate=true¤tschema=BDB9AC0F20CB46B494E6742047C4F99A', host: 'bdb9ac0f20cb46b494e6742047c4f99a.hana.eu10.hanacloud.ondemand.com', port: '443', driver: 'com.sap.db.jdbc.Driver', schema: 'BDB9AC0F20CB46B494E6742047C4F99A', hdi_user: 'BDB9AC0F20CB46B494E6742047C4F99A_DT', hdi_password: 'abc...xyz', user: 'BDB9AC0F20CB46B494E6742047C4F99A_RT', password: 'abc....xyz', certificate: '-----BEGIN CERTIFICATE-----\n' + '...' + '-----END CERTIFICATE-----' }
Only
cds watch and
cds env (the latter with the
--resolve-bindings option) resolve cloud bindings. Bindings are resolved by
cds serve or
cds exec.
Run Arbitrary Commands with Service Bindings
With
cds bind you avoid storing credentials on your harddisk. If you need to start other applications with cloud service bindings from local, then you can use the
exec sub command of
cds bind.
For example, you can run the approuter from the
approuter child directory:
cds bind --exec -- npm start --prefix approuter
This works by building up a
VCAP_SERVICES variable from the bindings in the chosen profiles (default:
hybrid). You can run the following command to print the content of the generated
VCAP_SERVICES variable:
cds bind --exec -- node -e 'console.log(process.env.VCAP_SERVICES)'
Run CAP Java Apps with Service Bindings
Start your CAP Java application through the
cds bind --exec command to use the service bindings.
For example:
cds bind --exec mvn spring-boot:run
Run with Service Bindings from a Running Cloud Application
Run CAP Apps Using Cloud Application Bindings
Instead of binding to specific cloud services, you can run your application with all service bindings of an application on the SAP BTP Cloud Foundry environment.
But you need to have (1) your application deployed and be (2) logged in your Cloud Foundry space using the
cf command line.
For example, you can use the following syntax with
bash or similar shells:
VCAP_SERVICES=$(cf env <CF-APP-NAME> | perl -0pe '/VCAP_SERVICES:(.*?)VCAP_APPLICATION:/smg; $_=$1') cds watch --profile hybrid
Your profile should have the
kind settings to use the bound services, for example
requires.db = hana.
cds bind Usage
By Cloud Service Only
The shortest form to use
cds bind is to specify only the Cloud Foundry service instance name:
cds bind -2 my-hana
This implies that a service key exists with the suffix
-key. In this example:
my-hana-key.
You can specify a different key after a colon (“
:”):
cds bind -2 my-hana:my-different-key
With CDS Service and Kind
If
kind or CDS
service cannot be determined automatically by
cds bind, you need to specify it:
cds bind credstore -2 my-credstore --kind credstore
You are informed by an error message if this is required.
Bind Multiple Services with One Command
There is a handy shortcut to bind multiple services with one command:
cds bind -2 my-hana,my-destination,my-xsuaa
This shortcut is only possible, if you don’t need to provide a
service or a
kind.
With Profile and Output File
By default the bindings for the profile
hybrid are stored in the .cdsrc-private.json file in your current working directory.
This can be overwritten using the
--profile and
--output-file options.
Execute Commands with Bindings
You can start arbitrary command line programs with your bindings.
The service bindings are resolved from the cloud and provided in the
VCAP_SERVICES env variable to the application. Therefore it works with every application that can consume Cloud Foundry credentials.
cds bind --exec [--] <command> <args ...>
Use the double-dash (
cds command line will try to parse them as their own options.
--) if your command has args starting with a dash (
-) character. Othwise the
Profiles can be set using the optional
--profile parameter. By default the
hybrid profile is used.
cds bind --exec --profile <profile> [--] <command> <args ...>
The
--profile parameter must follow
exec directly.
Use Cases
Most of the following use cases are shown for Node.js, but can be easily adapted for Java.
Destinations
Learn how to connect to remote services from local using SAP BTP destinations.
Authentication and Authorization using XSUAA
Learn how to do hybrid testing using the XSUAA service in the CAP Node.js authentication documentation.
Integration Tests
cds bind can be handy for testing with real cloud services in your CI/CD pipeline.
Configure your required bindings for testing and save it to your project’s package.json file for your tests’ profile:
cds bind -2 integration-test-hana -o package.json -p integration-test
No credentials are saved!
In your CI/CD pipeline you can resolve the bindings and inject it into the test commands:
# Install DK for "cds env" npm i @sap/cds-dk --no-save # Login cf auth $USER $PASSWORD ## Uncomment if your service bindings have ## no "org" and "space" set (see note below) # cf target -o $ORG -s $SPACE # Set profile export CDS_ENV=integration-test # Set resolved bindings export cds_requires="$(cds env get requires --resolve-bindings)" # Execute test npm run integration-test
With
CDS_ENV, you specify the configuration profile for the test, where you put the service binding configuration before.
cds env get requires prints the
requires section of the configuration as a JSON string. By adding the option
--resolve-bindings, it includes the credentials of the service bindings from the cloud. To make the credentials available for all subsequent
cds commands and the tests, the
requires JSON string is put into the
cds_requires variable.
Service bindings created by
cds bind contain the Cloud Foundry API endpoint, org, and space. You can allow your services to connect to the currently targeted Cloud Foundry org and space by removing these properties from the binding structure. | https://cap.cloud.sap/docs/advanced/hybrid-testing | CC-MAIN-2022-21 | refinedweb | 1,776 | 52.29 |
.
Why is their use not recommended, they are fast and capable of doing what small functions are expected to do???
Function-like macros are full of gotchas and unexpected behavior that that's avoided by using normal functions, particularly when it comes to side effects.
Consider:
Seems harmless, right?
But if you call it like this:
You'd expect the result to be 4, but you actually get 6.
This happens because ++n is copied into the macro before being evaluated, so your output statement becomes "std::cout << (++n) + (++n);"
This sort of behavior is avoided using normal functions.
The result is 5 if you have this program:
Hi Shri!
Good observation.
is an undefined operation, there is no standard way of evaluating this, so you'll get different results with different compilers. This is covered in a later lesson.
Wouldn't it be a more appropriate define for macro as given by gnu-
"A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro."
That definition would be appropriate if macros were strictly substitution-based. But function-like macros do a little more than replacement (even though we don't recommend their use).
I came across this on Stack Overflow:
"Notably, it completely misses an introduction to the STL and the proper use of it. You barely see std::cout and std::string. There's no mention of <algorithm> that I could see of and no mention of the <vector> or <deque> or <map> which are the most commonly used containers in C++."
Whats this? D:
A professional race car driver might look at a drivers education course and criticise it for not teaching you how to drive race cars. But that's not really the point, is it?
Some of these criticisms are fair, and have already been addressed in updates made over the last 5 years. Others (e.g. the omission of parts of the STL) miss the mark a bit. The point of this tutorial isn't to comprehensively cover every corner of the STL (though I'd like to get there someday) -- it's to teach you how to use the core language mechanics of C++, so that if you want to learn more about the STL (or anything else that builds upon the core mechanics), you'll be well set up for doing so!
How do we pronounce the '#' symbol here?
It doesn't really have a canonical name. Most often I hear it called "pound" (in the US), "number sign", or "hash/hashtag".
In the UK it is "hash" or "hashtag" due to Twitter. However, within the preprocessor directives context it is strictly just "hash".
hey, do you mean
if i have defined bob then if i use #ifndef it will not print it?
Right, if you've done a #define bob, then anything inside #ifndef bob will not execute..
Thanks for the quick response.
I faced another error Error C2084: 'Function already has a body'. However, I fixed the problem.
The issue is when building a project, it is always better to keep the project name the same as the cpp file that contains the main() function.
Thanks again. :). :)
Hi and first of all,
thanks for the great tutorial!
I have run into a problem trying to compile my project if I add the following preprocessor directives:
I get the following error in eclipse cdt on the first call to std::cout (I hope I'm using the correct terminology here):
error: no type named 'cout' in namespace 'std'
<iostream> is clearly included and I get no complaints about std::cout when its used later in main,
so what am I missing here?
The problem here is that lines 5 and 9 are outside of a function, so your compiler is confused because you're declaring statements somewhere you aren't supposed to.
Try copying lines 4 through 10 into your main() function (or another function that main() calls) and it should work fine.
yep.
that was the mistake obviously.
thanks again
Hi Alex.Thanks for your wonderful lessons. I am very new to programming, I hope I am asking the right question. This is the code I was practising. Here system ("paused"); does not work for some reason. It just blinks and goes away but if I use
cin.clear();
cin.ignore(255, 'n');
cig.get();
works fine.
Would you please don't mind to explain? Sorry for the bad English too :-(
Thanks
The cin method clears out any queued input, then waits for the user to press a key before proceeding.
The method of using system("pause") (no d on the end of pause) makes a call to the operating system to run the pause executable (if you open a command prompt on Windows, you can type "pause" (no quotes) and see it execute).
I recommend the cin method because it will work on any operating system.
nice article....explained well...But there are 14 directives in C++
1-#define
2-#elif
3-#elifdef
4-#elifndef
5-#else
6-#endif
7-#error
8-#if
9-#ifdef
10-#ifndef
11-#include
12-#line
13-#pragma
14-#undef
You have written about few of them.What about others?
It's an intro lesson, so I've opted not to be comprehensive here in the interest of having the lesson not be overly-long. I'll take a note that we could use a more comprehensive lesson on the preprocessor. In the meantime, there's plenty of reference material available on the internet that can explain these things. Once you understand how the preprocessor works and some of it's basic functions, picking up the other directives shouldn't be too much of an issue.
Thanks so much for these tutorials. Wish I had found them years ago. So many basic things that I needed to understand the C++ examples I was reading at the time.
You present at a good level of detail--enough examples, but not too long.
#include directives like these are also valid:
#include "dir/file.h"
#include "../file.h"
At this step
#define MY_NAME "Alex"
cout << "Hello, " << MY_NAME << endl;
i get 2 errors:
error C2143: syntax error : missing ';' before '<<'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
what's wrong? I did something wrong, or was something wrong?
Even I have the same error. I am not able to find what is wrong with the code.
I even tried with std::cout
The double quotes are wrong. They got formatted to “” instead of "". Make sure you're using standard double quotes, not the pretty ones.
VERY NICE MATERIAL, LEARNED AND PERFORMED IN FIRST ATTEMPT. THANKS.
this is just awesome teacher...made programming lot easier..thank u fellows..!
Hey Alex great tutorial!
i was just wondering why #define Print_joe
was not just #define joe?
Doesn't the word Print throw the whole thing off?
This question has been really bugging me, any answer would be appreciated
THANKS!
Your #define symbols can be whatever you like so long as they follow the normal identifier naming rules. There's no difference between #define PRINT_JOE and #define JOE and anything else. The word PRINT is meaningless in this context except maybe as a note to the reader.
I really don't understand the header guard example given here. Would the mymath.h have to be taken out of the add and subtract headers, and then put into the main class with another header guard?
Why can't you make your whole program in a header file then just have #include "headerfile.h" in the main.cpp and compile? What can and can't you put in a header file instead of a .cpp file?
You can put almost anything in a header file (there are a few exceptions). Thus, you could write your whole program in a header file and #include it into a .cpp, but if you're going to do that, why not just skip the header file and put the code in the .cpp in the first place?
Great Article , Thanks Alex
Ok the coding you provided for the header guard is going to be VERY helpful. Thanks for that.
I have a quick question... what is the benefit of using define as opposed to simply initilializing the variable?
What is the difference between
and
Personally I don't think there is any reason to use #define this way.
The only place I use #defines is when #defining symbols to use with #ifdef or #ifndef. You can't use regular variables for those.
Great!
Billerr, You can use such defines for several reasons. Header guards are the primary one. However, it can be useful to define code that only executes when certain #defines have been set. For example, you might do something like this:
This would only print out nDebugVariable if the program was compiled with the _DEBUG symbol #defined. You might turn this symbol on when compiling a version for development or testing, but turn it off for the release version.
In a game I wrote, I used a #define to toggle whether the game generated random dungeons (for the release version) or a special debug level (for testing/development). I could toggle between the two by commenting/uncommenting the #define and recompiling.
I'm not absolutely sure but from what I've read here and a book I have, I believe you are correct about it only being for the header guards when there is no replacement.
This might be a dumb question, but what exactly is the purpose of:
#define [identifier]
i.e. a #define without any replacement?
Is it useful mostly in header guards?
I'm learning programming for small electronic projects which include micro-controllers, and to me object-like macros w/o substitution text are more frequent than the others.
Here's an example.
in above code, if I don't want to blow buzzer, then I just comment out the line
There are may be million examples in every domain, but this is the best one I can think of.
Thanks, Mayur
EDIT:
MY_BAD
CORRECTION:
GovZ, as far as I know, that is an official part of the preprocessor. You should also be able to use && to test whether multiple symbols are defined at the same time:
#if defined (symbol_a) && defined (symbol_b)
I didn't cover these specific concepts in this tutorial because I don't even cover what the || and && symbols mean until section 3.6. This is just supposed to be a quick introduction, not a full preprocessor tutorial. :)
There are quite a few other neat things the preprocessor can do that I don't (and don't plan to) cover in this tutorial. If you are interested in learning more, there are quite a few preprocessor documents that are publicly available. Here's one.
Hello guys,
I just wanted to ask if you have enough room for :
#if defined(macro_name) || defined (macro_name2)
in this tutorial :) I use this quite a lot in coding. Is this a part of the standard by the way?
I have read chapter 0 up to this part and plan to read more. Thanks and more power :)
Name (required)
Website | https://www.learncpp.com/cpp-tutorial/introduction-to-the-preprocessor/comment-page-1/ | CC-MAIN-2019-13 | refinedweb | 1,887 | 73.07 |
Parsed XML allows you to use XML objects in the Zope 2 environment.
Parsed XML
Contents
- Parsed XML
- Credits
- Changes
What is. It also includes a system to create paths to nodes in Zope URLs (NodePath).
Features
The Parsed XML product parses XML into a Zopish DOM tree. The elements of this tree support persistence, acquisition, etc.. The document and subnodes are editable and manageable through management proxy objects, and the underlying DOM tree can be directly manipulated via DTML, Python, etc..
DOM and ManageableDOM
We’re implementing a lean, mean DOM tree for pure DOM access, and a tree of proxy shells to handle management and take care of the conveniences like publishing and security. The ManageableNodes are the proxy objects. These are what you see in the management interface, and the top object that gets put in the ZODB. Note that only the top proxy object is persistent, the others are transient. The Nodes are pure DOM objects. From a ManageableNode, the DOM Node is retrieved with the getDOMObj() call.
DOM API support
The DOM tree created by Zope aims to comply with the DOM level 2 standard. This allows you to access your XML in DTML or External Methods using a standard and powerful API.
We are currently supporting the DOM level 2 Core and Traversal specifications.
The DOM tree is not built with the XML-SIG’s DOM package, because it requires significantly different node classes.
DOM attributes are made available according to the Python language mapping for the IDL interfaces described by the DOM recommendation; see the mapping
URL traversal
Parsed XML implements a NodePath system to create references to XML nodes (most commonly elements).
Currently, traversal uses an element’s index within its parent as an URL key. For example:
This URL traverses from an XML Document object with id myDoc to it’s first sub-element, to that element’s second sub-element to an acquired method with id myMethod.
DOM methods can also be used in URLs, for example:
Editing XML with the management interface
XML Documents and subnodes are editable via the management interface. Documents and subtrees can be replaced by uploading XML files.
Developing with Parsed XML
We like to think that Parsed XML provides a flexible platform for using a DOM storage and extending that storage to do interesting things. See README.DOMProxy for an explanation of how we’re using this for Parsed XML.
We’ve included a comprehensive unit test suite to make testing for DOM compliance easier. See tests/README for details.
If you want to submit changes to Parsed XML, please use the test suite to make sure that your changes don’t break anything.
Bugs
There are bugs in how multiple node references reflect the hierarchy above the node:
A reference to a subnode of a DOM document won’t reflect some hierarchy changes made on other references to the same node.
If two references to a node are created, and one is then reparented, the other reference won’t reflect the new parent. The parentNode attribute will be incorrect, for example, as well as the ownerDocument and ownerElement attributes.
A reference to a subnode of a DOM document can’t be properly stored as a persistent attribute of a ZODB object; it will lose hierarchy information about its parent as well.
Entity reference handling is not complete:
- Entity references do not have child nodes that mirror the child nodes of the referenced entity; they do not have child nodes at all.
- TreeWalker.expandEntityReferences has no effect, because of the above bug.
Traversal support for visibility and roots is not complete.
Credits
Current Maintainer:
- Martijn Faassen <faassen@infrae.com>
Contributors:
- Patrick Decat <pdecat@gmail.com>
- Tim Heap
The Zope Corporation Parsed XML team:
- Karl Anderson
- Fred Drake <fdrake@zope.com>
- Todd Corum
- Martijn Pieters <mj@zope.com>
External Contributor:
- Martijn Faassen <faassen@infrae.com>
Much test and implementation help was provided by
- Chris McDonough <chrism@zope.com>
- Shane Hathaway <shane@zope.com>
- Guido van Rossum <guido@python.org>
Parsed XML also contains code from versions of the original XMLDocument, written by Amos Latteier and Fourthought Inc.
ParsedXML contains software derived from works by Fourthought Inc; see LICENSE.Fourthought for their license.
Changes
ParsedXML 1.5.1 (2010/07/15)
- Update imports and syntax to work with Zope 2.12 and Python 2.6.
ParsedXML 1.5
Bugs Fixed:
- Allow unicode characters in qualified names.
Other changes:
- Zope 2.8 transaction compatibility fixes.
ParsedXML 1.4
Features Added:
Switched the test suite over to use ZopeTestCase.
Updated UI so that the XML edit screen is the first screen seen, not the DOM screen.
UI is UTF-8 by default now, the same as the default encoding of the XML. XML encoding setting in the XML declaration other than UTF-8 are supported by the upload, but the XML text will be converted to unicode internally and will display as UTF-8, the default encoding.
You can also use the encoding in the XML declaration in the edit entry, but you will be unlikely to get it right as the interactions between various encodings becomes rather complex. If you have XML text in a non-UTF-8 encoding upload it as a file rather than copy and paste it.
Switched over to new-style security declarations and added a few.
Bugs Fixed:
- Cleaned out tests so they all pass. This was done (unfortunately) by disabling some failing tests.
- Some encoding issues should be more sane now.
Misc:
- Updated license to ZPL 2.0.
- get rid of unused HTML writing support.
- Removed old Printer.py module (PrettyPrinter works better and has more functionality).
- get rid of obsolete delegation through StrIO module to get StringIO.
ParsedXML 1.3.1
Bugs Fixed:
- Bugfix/performance improvement. Do not rely on getPersistentDocument() but instead use acquisition parent. This fixes a memory leak triggered when doing document.documentElement, and also likely improves performance when accessing the DOM through the ManageableDOM wrappers.
- The Zope Find tab should now not give an error anymore when searching with ids.
- Use the One True Way to import expat now (‘from xml.parsers import expat’).
ParsedXML 1.3.0
Features:
- All element nodes now have a _element_id id. This id is guaranteed to be unique in the document, though which id an element has may change in a reparse.
- NodePath system for creating various paths to nodes. This can be based on ‘child’ (child node index), ‘element_id’, or ‘robust’, which is not very robust as yet in some ways, but should be resistent to quite a few changes to the document.
- added pretty printing feature. A pretty print button renders the document in pretty printed form, but does not save this changed version (you can do so yourself).
Bugs Fixed:
- Removed ParsedXML’s Expat, introduced dependency on PyXML’s pyexpat instead (or just compile your own). This gets rid of lots of install hassles, especially on Windows. Just install PyXML.
- An ongoing attempt to bring sanity to the unit test story.
- Avoid XML-garbling bug in Printer by using PrettyPrinter.
- various bugfixes in the DOM.
ParsedXML 1.2.1
Features:
- pyexpat.c is now in sync with Python’s and PyXML’s version.
ParsedXML 1.2.0
Bugs Fixed:
- Tests are now more conformant with Zope unit testing guidelines.
- Should work with Python 2.1/Zope 2.4, but not all the way there yet (parser segfault..)
- new version of PyExpat
Features:
- Access to DOM from Zope environment sped up by new DOMProxy implementation
ParsedXML 1.1b1
Bugs Fixed:
- Fixed an ExpatBuilder bug that caused a DOM reference to be leaked when parsing occured at the document. There is still a leak for fragment parsing that we’re looking into.
Features:
- ZCatalog support added
- ZCache support added
ParsedXML 1.1a1
Bugs Fixed:
- Version numbers make more sense :)
Features:
- The value returned by get_size() is cached, which will often speed up the management view of an instance’s container.
ParsedXML 1.0
Bugs Fixed:
- Problems with Attr Node manipulation not being reflected by the getAttribute methods of their Elements and vice versa fixed.
- Erroneous position information for parse error output on subnodes fixed.
- Default attributes are noticed by the parser and printer, and the relevent DOM methods work.
Features:
- ManageableDOM Nodes can find the persistent Document wrapper when it has been installed in a Zope ObjectManager. This object, rather than a newly created ManageableDocument wrapper, is returned when available by OwnerDocument calls. This allows Zopish navigation and discovery out of the Document, helps shorten acquisition paths, and fixes some bugs with manipulation at the Document.
- ManageableDOM’s usage of namespaces for parsing is now optional and settable.
- The DOM 2 Traversal interface has been fleshed out, although support for visiblity and roots is not complete.
ParsedXML 0.1b3
Bugs Fixed:
- Yet a few more DOM bugs fixed.
- Fixed a distribution error that was causing build problems under Solaris.
ParsedXML 0.1b2
Bugs Fixed:
- Many bugs found and fixed as we hammered out new DOM tests, especially in namespace usage, attribute printing, and attribute children.
Features:
- Several speedups throughout the code.
- ManageableDOM refactored into several base classes to make extension easier.
Download Files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/Products.ParsedXML/ | CC-MAIN-2017-47 | refinedweb | 1,553 | 57.77 |
.Suresh, unfortunately the kernel does not boot with your patch, becauseit clears init_level4_pgt. I think the patch that follows should be applied ontop of it.If I am right, than your patch does not conflict with mine (just tested).Greetings,RafaelSigned-off-by: Rafael J. Wysocki <rjw@sisk.pl>Index: linux-2.6.14-rc2-git7/arch/x86_64/mm/init.c===================================================================--- linux-2.6.14-rc2-git7.orig/arch/x86_64/mm/init.c 2005-09-29 22:13:34.000000000 +0200+++ linux-2.6.14-rc2-git7/arch/x86_64/mm/init.c 2005-09-29 22:13:55.000000000 +0200@@ -313,7 +313,7 @@ void __cpuinit zap_low_mappings(int cpu) { if (cpu == 0) {- pgd_t *pgd = pgd_offset_k(0UL);+ pgd_t *pgd = boot_level4_pgt; pgd_clear(pgd); } else { /*Index: linux-2.6.14-rc2-git7/include/asm-x86_64/proto.h===================================================================--- linux-2.6.14-rc2-git7.orig/include/asm-x86_64/proto.h 2005-09-21 11:04:24.000000000 +0200+++ linux-2.6.14-rc2-git7/include/asm-x86_64/proto.h 2005-09-29 22:22:19.000000000 +0200@@ -22,6 +22,7 @@ #define mtrr_bp_init() do {} while (0) #endif extern void init_memory_mapping(unsigned long start, unsigned long end);+extern void zap_low_mappings(int cpu); extern void system_call(void); extern int kernel_syscall(void);-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2005/9/29/272 | CC-MAIN-2016-26 | refinedweb | 233 | 53.17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.