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 |
|---|---|---|---|---|---|
shouldn't be too difficult to implement and should be done. Unless =
we want to do more work in the kernel, it is easiest to just have the =
mount command figure out what node the device is on and do the mount =
system call on that node.
Bruce Walker
> -----Original Message-----
> From: ssic-linux-devel-admin@...=20
> [mailto:ssic-linux-devel-admin@...] On=20
> Behalf Of Javier Celaya
> Sent: Sunday, November 28, 2004 1:26 PM
> To: OpenSSI Development
> Subject: [SSI-devel] mounting devices in different nodes
>=20
>=20
> Hi all
>=20
> I've noticed recently that I cannot mount a device on node 1 from node
> 2. They must be mounted/umounted from the node they belong=20
> to. But when
> I do an 'onall mount' I can see the same information, all the mounted
> devices across the cluster. It would be great if I could mount/umount
> devices from different nodes (or at least if they are listed=20
> in fstab).
> Would it be too difficult to implement?
>=20
> Regards
> --=20
> Hay 10 tipos de personas,
> las que saben binario y las que no.
>=20
> Javier Celaya, Linux User #367634 /"\
> jcelaya@... \ / Campa=F1a del Lazo =
ASCII
> X contra el correo HTML
> / \
>=20
>=20
>=20
Walker, Bruce J wrote:
> It shouldn't be too difficult to implement and should be done. Unless we want to do more work in the kernel, it is easiest to just have the mount command figure out what node the device is on and do the mount system call on that node.
>
>
The logic is there in the code. fs/namespace.c:1514 #ifdef out.
We need to implement cfs_shipmount
if ( mount device is remote ) {
cfs_shipmount(..)
}
discover_mount
-aneesh | https://sourceforge.net/p/ssic-linux/mailman/ssic-linux-devel/thread/41AB255E.6010106@hp.com/ | CC-MAIN-2017-43 | refinedweb | 284 | 70.63 |
Php xml gds jobs
Tasks: - Build API tool (NodeJS, ExpressJS) - Parse XML, JSON data - API calls - Datafeed upload - Scripting/scraping Required: - NodeJS, ExpressJS - Javascript - XML, JSON Budget: Fixed
..
import 2 xml of different language , WPML setup , site is already done
.. to use * All development will need to take place
.. : Document status:
I need to be able to upload a file to GA that shows the date and time tha.. simple for anyone who knows the system.
...links pointing to other websites. (exclude any links around image: <a><img></a>) 2. take only domain name (example: for http:[login to view URL]us it is [login to view URL]) and save it into xml or excel file only once 3. have a field on the webform to exclude certain top-level domains (TLDs), coma separated : ch, ca, eu 4. check each domain it found if it is ava...
...and Core Java technologies o Understanding of JavaScript – working on Vue or React, [login to view • Ex...
...icons and backgrounds, must include PSD. You'll need to create backgrounds/icons for the following - C programming - HTML & CSS - Java - PHP - Python - JavaScript - Lua - .NET - Perl - Ruby - Rust - Node.JS - XML - Databases - Web hosting and hosting solutions - Web Development - Game Development - Mobile app development - Desktop Development. | https://www.freelancer.com/job-search/php-xml-gds/ | CC-MAIN-2019-22 | refinedweb | 211 | 66.23 |
I'm having issues printing to a txt file. The file contains information stored in bytes. No matter what I try, I can only get the output to print in the shell. Here's what I have - any help is welcome.
def main():
with open("in.txt", "rb") as f:
byte = f.read(1)
while byte != "":
print ord(byte),
byte = f.read(1)
with open('out.txt','w') as f:
if __name__ == '__main__':
f.write(main())
close.f()
This is a fundamental misunderstanding of what various functions and methods do. You are writing the returned value of
main() to the file, expecting
main's
print() calls to go to the file. It does not work like that.
def main(): with open("in.txt", "rb") as f, open('out.txt','w') as output: byte = f.read(1) while byte != "": output.write(str(ord(byte))) byte = f.read(1) if __name__ == '__main__': main()
Use
file.write() to write strings (or bytes, if you're using that kind of output, which you currently aren't) to a file. For your code to work,
main() would have to return a complete string with the content you wanted to write. | https://codedump.io/share/Bg0uPmVLAhT/1/writing-to-txt-file-in-python | CC-MAIN-2017-09 | refinedweb | 195 | 88.94 |
here How do I sort a list of dictionaries by a value of the dictionary? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution to sort either in ascending or descending order.
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
For instance,
import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x will be a list of tuples sorted by the second element in each tuple.
dict(sorted_x) == x.
And for those wishing to sort on keys instead of values:
import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(0))
In Python3 since unpacking is not allowed [1] we can use
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=lambda kv: kv[1])
If you want the output as a dict, you can use
collections.OrderedDict:
import collections sorted_dict = collections.OrderedDict(sorted_x)
sorted(dict1, key=dict1.get)
Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). OP was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above. | https://pythonpedia.com/en/knowledge-base/613183/how-do-i-sort-a-dictionary-by-value- | CC-MAIN-2020-29 | refinedweb | 295 | 62.58 |
XSLT Elements
Much of XSLT’s functionality is exercised in the form of elements that perform functions and tasks. In fact, the whole language is XML-based and describing its features is already the subject of several books. This section presents some of the XSLT elements and fundamentals so you can begin using it in your daily work.
The Stylesheet Element
The
xsl:stylesheet
element is always the root element of standalone stylesheets, and is
also used for embedded stylesheets. The
stylesheet element contains some optional
and mandatory attributes that provide more details about the
stylesheet to the XSLT processor. The specification defines a second
root element in the XSLT namespace, called
xsl:transform. This element is identical to
xsl:stylesheet in every way but
name, and can be used in place of
xsl:stylesheet with no change in
meaning.
The
id attribute is
optional. However, an identifier would certainly come in handy if this
stylesheet were part of a larger XML document (as would be the case
for an embedded stylesheet). The XML specification states that any
attribute of type ID (not necessarily named
id, but of the data
type ID declared in the DTD) must be unique within any XML
document. Use of an ID attribute on a stylesheet is powerful if you
are dynamically generating several stylesheets collected together in a
larger composite document.
The
version attribute
is required as it indicates which version of XSLT is being used. All
xsl:stylesheet elements must have
the
version ...
Get Python & XML now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers. | https://www.oreilly.com/library/view/python-xml/0596001282/ch06s05.html | CC-MAIN-2020-50 | refinedweb | 275 | 61.97 |
Essentials
All Articles
What is LAMP?
Linux Commands
ONLamp Subjects
Linux
Apache
MySQL
Perl
PHP
Python
BSD
ONLamp Topics
App Development
Database
Programming
Sys Admin
Editor's Note: This short article provides a great overview to the Dojo Toolkit, but be sure to check out our new Short Cut entitled Get Up And Running With Dojo that digs much deeper. We also have a new book coming out early next year, so stay tuned!
Dojo is an incredibly powerful toolkit that provides a wealth of web development utilities that you don't want to miss out on. In addition to coming packed with rich, turn-key Web 2.0 widgets for you to snap into your applications, it also includes the standard JavaScript library you've always wanted, facilities for compressing your code when it comes time for production, AJAX utilities, a suite of object oriented programming (OOP) constructs that reduces the boilerplate you'd otherwise have to write and maintain your own custom widgets, and more.
To say the least, Dojo is experiencing some serious momentum right now. Version 1.0 just landed, so get it while it's hot. Let's kick off our time together with a bird's eye view of Dojo's architecture and then follow up with some examples of how Dojo approaches OOP, AJAX, and widgets.
The refactoring involved since the version 0.4 days introduced significant improvements to the codebase, so a high-level view of the toolkit is a great way to get rolling. Architecturally, Dojo consists of five primary components: Base, Core, Dijit, DojoX, and Util. Here's a short synopsis of each complement; afterward, we'll dig into some more specifics.
Think of Base as the kernel of the toolkit. It's a tiny library wrapped up into a single JavaScript file (dojo.js) that provides the foundation for everything in the toolkit. Among other things, Base handles bootstrapping the toolkit, includes convenient language and AJAX utilities, provides mechanisms for simulating class-based inheritance, offers a slick packaging system that preserves the global namespace, and more.
dojo.js
That may sound like a lot (and it is), but the footprint of Base has been optimized to be tiny, so you won't see much overhead when you include it in your page. Base comes across the wire from AOL's Content Developer Network (CDN) at about 25 KB, and when you consider that simple Flash-based advertisements that inundate the Web are generally larger than that very size, Base seems all the more amazing.
By the way, cross-domain (XDomain) loading Dojo from AOL's server is an incredibly sweet deal and is especially noteworthy on its own. The CDN gives you full access to key parts of the toolkit without any setup or server maintenance on your own. You simply drop a reference like <script type="text/javascript" src=""></script> into your page, and have at it!
<script type="text/javascript" src=""></script>
Core builds on Base by providing additional facilities for accessing data stores, providing effects such as wipes/slides, internationalization (i18n), and back-button handling among other things. For the most part, any module or resource associated with the dojo namespace that you have to explicitly import into the page is part of Core. So, why bother with a separation between Base and Core? Basically, the division between Base and Core is a balancing act that's the result of providing fundamental support for common operations in Core (associated with the dojo namespace), while keeping Base as streamlined as possible.
dojo
The distinction between what did and didn't make it into Core may not always seem like a perfect boundary depending on how you look at it, but you're really nit-picking when you get to analyzing at that level of granularity. Besides, Dojo's packaging system makes it absolutely trivial to pull in additional modules and resources as needed with simple dojo.require statements, which is very similar to the concept of import statements in Java or #include statements in C++ code.
dojo.require
import
#include
Dijit is shorthand for "Dojo widget" and, depending on the context and capitalization, could refer to a single Dojo widget (a dijit) or to the entire component of the toolkit containing all of Dojo's widgets (Dijit). Dijit directly leverages the power of Base and Core to provide a powerful widget layer that's highly usable and simple in design.
Plugging a dijit into a page is usually as easy as specifying a special dojoType tag inside of an ordinary HTML element—a dream come true for layout designers and high level mashup developers. If you're an application developer, using dijits allows you to achieve incredibly rich functionality without having to dig into tedious implementation details. Even if you're more of a library writing type or custom widget developer, following Dijit's style ensures your widgets will be portable and easy to use essentials for any reusable software component.
dojoType
DojoX stands for "Dojo Experimental" and contains features that stand a chance of one day migrating into Core, Dijit, or even a new Dojo module that doesn't exist yet. Think of DojoX as an incubator or sandbox. It's a place where functionality can be offered in a way that doesn't incur the overhead and due diligence of testing, documentation, and support that would be required of Core or Dijit—yet it does provide a way for new ideas that may not be fully mature to be included in the toolkit. Note that everything in DojoX does come tagged with an explicit warning label, the dojox namespace, and is required to have a comprehensive README file. Right now, the work that happening with charts, graphs, and the new grid is pretty exciting.
dojox
Although DojoX may often not be the place where application developers who are counting on guaranteed stability or an easy to use resource should be looking, it simultaneously serves two incredibly important purposes: it provides a proving ground for new features to potentially move into Core and Dijit, and it ensures that there are high standards and stable APIs for resources that are already included in Core and Dijit. This approach is genius when you think about it, because it strikes a sensitive balance for critical issues central to any community-supported OSS project.
Util is a collection of Dojo utilities and includes the Dojo Objective Harness (DOH)--a testing framework, scripts for scraping documentation out of the Dojo source, and tools for leveraging Mozilla's powerful JavaScript engine, Rhino. DOH is a relatively new addition to Dojo and the tests you can produce with it will save you some serious development time. After all, you do want to benefit from well-defined, systematic tests for your widgets, don't you?
Mozilla's Rhino is used to create compressed builds of Dojo for production use; you can also use it to compress your own widgets. Rhino's effectiveness is especially noteworthy in that it never mangles a public API. It is not uncommon to reduce your overall JavaScript file sizes by more than 50 percent with Rhino. The compression is a marvelous feature that comes gratis with any custom build of your Dojo widgets.
Here's a diagram that's helpul for summing up how these different pieces relate to one another:
Figure 1. The general architectural design of Dojo
Dojo does a fantastic job of simulating classes though its dojo.declare function. In addition to dojo.declare allowing you to loosely define a class, it also manages a lot of messy details for inheritance relationships behind the scenes so that you don't have to clutter up your design with them. In the end, dojo.declare is one of the crown jewels of Base, because it minimizes the amount of brittle boilerplate you'd normally have to write if you were handling this effort all on your own; plus, it significantly increases the maintainability of your code by making the class declaration and inheritance relationships apparent to the reader.
dojo.declare
Here's a quick example of dojo.declare at work:
//A Momma Tigress
dojo.declare("my.Tiger", null,
{
_name: null,
_species: null,
constructor : function(name) {
this._name = name;
this._species = "tiger";
},
talk : function() {
console.log("I'm a "+this._species);
}
});
//And A Poppa Lion...
dojo.declare("my.Lion", null,
{
_name: null,
_species: null,
constructor: function(name) {
this._name = name;
this._species = "lion";
},
talk : function() {
console.log("I'm a "+this._species);
}
});
//Have A Baby Liger
dojo.declare("my.Liger", [my.Tiger, my.Lion],
{
_name: null,
_species: null,
constructor : function(name) {
this._name = name;
this._species = "liger";
},
// Override the talk method with a custom one.
talk : function() {
console.log("My name is "+this._name+", and I'm a "+this._species);
}
});
//And her name is lucy. Create her just like any other JavaScript object
lucy = new my.Liger("Lucy");
//Lucy, would you like to introduce yourself?
lucy.talk();
The first parameter to dojo.declare is a string value that indicates the namespace (my) and name of the class (Tiger, Lion, and Liger), and the second parameter designates the superclass for the inheritance relationship. The my.Tiger and my.Lion classes don't directly descend from any other class, so there is an explicit null value in place, but the my.Liger class directly inherits from both a my.Tiger and a my.Lion via a limited form of multiple inheritance. Although this example is very simple, dojo.declare is pretty sophisticated; it handles the prototype chaining and other messy details involved in simulating class-based inheritance behind the scenes for you.
my
Tiger
Lion
Liger
my.Tiger
my.Lion
my.Liger
In each class, _name and _species denote properties, while constructor denotes one of Dojo's built-in methods that provides an explicit place to handle some aspects of custom initialization—providing a name in this case. The talk() method is a user-defined method that uses the Firebug console to log a message if the browser is Firefox and has it installed. Otherwise, it uses Firebug Lite (bundled with Dojo) to log the message. Finally, note that you create an object instance of your class just like you would with any other object by using the new operator with a constructor function.
_name
_species
constructor
talk()
new
While this example just begins to scrape the surface of dojo.declare, hopefully it conveys the general idea of how you can reduce a lot of boilerplate and produce readable, maintainable code with it.
Base provides a lot of really handy AJAX functions for you to use, and like dojo.declare, these functions save you from a lot of boilerplate and let you concentrate on more important facets of your project than how you should implement a mechanism for failing gracefully when an asynchronous request fails or how you should handle the various content types that may be returned to you. To illustrate Dojo putting JavaScript's XMLHttpRequest (XHR) object to work, the following code snippet shows a typical GET request that uses the data returned to perform a simple update on the page:
<body>
<script type="text/javascript">
dojo.xhrGet({
url : "./foo.json", //Returns /*{'bar':'baz'}*/
handleAs : "json-comment-filtered", //MIME type
sync : false, //Explicit asynchronous request
//Run this function if the request is successful
load : function(response, ioArgs) {
console.log("successful xhrGet");
console.log(response);
//Our handleAs value, tells Dojo to strip
dojo.byId("foo").innerHTML= response.bar;
return response;
},
//Run this function if the request is not successful
error : function(response, ioArgs) {
console.log("failed xhrGet");
return response;
}
});
</script>
<div id="foo"></div>
</body>
Now, wasn't that easy? We indicated that we'd like to asynchronously GET some comment-filtered (to avoid JavaScript hijacking) JSON data from a particular URL and provided functions for handling the success and failure cases. You can further customize the dojo.xhrGet function by providing additional parameters for timing out requests, preventing the browser from caching GET requests, automatically yanking form data to send to the server, and more. Dojo also includes similar XHR methods for other RESTful operations like POST, PUT, and DELETE.
dojo.xhrGet
No overview of Dojo would be complete without including a synopsis of widgets—or dijits in Dojo lingo. The following dijit is among the ranks of the simplest one possible. Its substance consists of a single JavaScript file that includes an inline template string and no custom theme that would normally be provided via a CSS stylesheet. Although the method stubs contain no functionality, hopefully, you'll find the commenting instructive.
First, take a look at the widget itself:
// A Very Simple Widget
dojo.provide("my.FooWidget");
// Dynamically pull in these resources
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare(
// Declare a FooWidget associated with the my namespace.
"my.FooWidget",
// Any superclass(es) the widget descends from.
// _Widget and _Templated from dijit are the usual
// suspects for most widgets.
[dijit._Widget, dijit._Templated],
{
// This is the template for the widget as it will exist in the
// DOM. We could have specified it in a separate file and used
// the templatePath property to find it instead.
templateString : "<span>Foo Widget</span>",
// Any custom properties you need can be defined like so...
someCustomProperty : "",
// The following four methods are called in this particular order
// as part of the widget's initialization...
constructor : function() {
/*
This stub provides a way for you to perform any other custom
initialization on your widget, including the management
of inheritance relationships. Application developers
might also handle any custom parameters that have been
passed to a widget in here without having to dig into any
source code.
*/
console.log("constructor");
},
postMixInProperties : function() {
/*
This method is a stub provided by _Widget and is called
after all superclass properties, if any, have been mixed
into the widget. In this example, _Templated is providing
some properties that get mixed in, including the templateString
property you see above. A very common operation to perform
here is manipulation of the template.
*/
console.log("postMixInProperties");
},
postCreate : function() {
/*
This stub is also provided by _Widget, and once it has been
called, the widget has been placed in the DOM and is
available on screen. You might override it to perform any
additional initialization actions that require the widget
to first be visible on the screen.
*/
console.log("postCreate");
},
startup : function() {
/*
Here in startup, you can be assured that all of the
widget's children, if there are any, have been initialized
and are available. It is not uncommon (at all) for a good
design to consist of a sophisticated widget that is broken
down into a number of simpler child widgets.
*/
console.log("startup");
},
// Any custom methods...
fooMethod : function() {
}
});
As you now know, there's not much more to creating a widget than using dojo.declare to provide a class definition along with overriding some inherited methods and writing some methods of your own. While this example included a templateString property inside of the JavaScript file, each widget can trivially house its template string in its own separate HTML file during the development cycle--an especially great thing if you need to divide the labor and divvy some work out to designers or layout artists.
templateString
Styling your widgets is just as easy; you simply include a CSS reference in your top level page that displays all of the widgets with the necessary classes to style your widgets in a thematic sort of way. Speaking of which, here's the page that includes the previous my.FooWidget via a simple reference with the dojoType tag:
my.FooWidget
<html>
<head>
<title>Simple Widget Example</title>
<!-- You could include any CSS here with some LINK tags -->
<script type="text/javascript">
// Parse the page for widgets once it loads. Explicitly
// indicate that console.* methods are being used for
//debugging, and point to custom modules that are local
djConfig={
parseOnLoad: true,
isDebug: true,
baseUrl: "./",
modulePaths: {my: "relative/path/to/local/dijits"}
};
</script>
<!-- Bootstrap Dojo From AOL's CDN-->
<script
type="text/javascript"
src="">
</script>
<script type="text/javascript">
// Explicitly require the parser for swapping in your widgets
// on page load.
dojo.require("dojo.parser");
// Require the widget being used in the page.
dojo.require("my.FooWidget");
</script>
</head>
<body>
<!--
By the time the page loads, Dojo will have replaced this stub
with a my.FooWidget. Any custom parameters could be passed in
here for custom initialization by including inline tags in the
HTML element.
-->
<span dojoType="my.FooWidget"></span>
</body>
</html>
While the previous example was quite simple, it conveys the general approach to creating any Dojo widget. If you don't take anything else away from this example, just make sure and remember all of the boilerplate that you don't have to write and maintain anymore, and imagine the time you'll save by letting Dojo handle the messy details of resolving dependencies, simulating class-based inheritance, and encapsulating the various facets of a widget into a single collective unit. That's a lot of time you can invest in your application and concentrate on far more interesting things.
While you can use Dojo to create your own highly-sophisticated widgets, Dojo offers a wide array of very useful dijits that "just work." As you observed in the previous example, the effort required in using a well-designed dijit is minimal: you simply bootstrap Dojo, use dojo.require statements to specify your page's dependencies, and then use dojoType tags in placeholder elements so that the parser can swap in your widgets on page load. It's just that easy.
The mothership over at dojotoolkit.org, is constantly being updated to include a wealth of Dijit examples, and Dojo releases contain some demo applications in the dijit/demos/directory. Out-of-the-box dijits are a dream come true for web designers, because you get access to snazzy UI controls without having to delve into the low level design and implementation details that used to be the norm.
dijit/demos/
Dojo is an incredibly sophisticated toolkit, and this short article could only cover so much. Hopefully, you've seen enough Dojo to be exicted about it, so head on over and download the lastest release and get your hands dirty. Our new Short Cut on this topic, Get Up And Running With Dojo, provides a much more in-depth primer to OOP with Dojo, so be sure to check it out when you're ready to work through some of the nitty-gritty.
Matthew Russell
is a computer scientist from middle Tennessee; and serves Digital Reasoning Systems as the Director of Advanced Technology. Hacking and writing are two activities essential to his renaissance man regimen.
Return to ONLamp.
Sponsored by:
© 2016, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://archive.oreilly.com/pub/a/onlamp/2007/11/01/the-mojo-of-dojo.html?page=last&x-maxdepth=0 | CC-MAIN-2016-36 | refinedweb | 3,153 | 53 |
1142/how-to-use-a-build-arg-parameter-before-from-in-a-dockerfile
I'm working on AWS ECR for hosting my project images. I'm using the FROM parameter to dynamically set the Dockerfile according to --build-arg input in the CLI.
$ docker build --build-args region=eu-north-1 .
// Dockerfile
FROM aws.ecr.huge.url.${region}/repo:php-apache
WORKDIR /var/www
RUN echo "@@@"
Here I want to replace the ${region} but that never happens and an error show up. But, when I run echo ${region} it works leading me to believe the problem is in FROM instruction
Can someone please help??
In the earlier docker version this wasn't possible, but now after the introdiction of multi-stage builds, the user can provide an argument before FROM. SOmething like this:
# default to eu-north-1
ARG region=eu-north-1
FROM aws.ecr.huge.url.${region}/repo:php-apache
Also, the arguments are namespaced. Therefore, when you define them before a FROM line, they're available to FROM until the end of stage. To use args in multiple namespaces, you'll have to define it every time.
Here is what you have to do.
Try ...READ MORE
You can pass other arguments to docker build ...READ MORE
Hey guys,
I was trying to execute few ...READ MORE
Hi,
If you want to clone your repo ...READ MORE
It can work if you try to put ...READ MORE
Check if the FTP ports are enabled ...READ MORE
To connect to EC2 instance using Filezilla, ...READ MORE
I had a similar problem with trying ...READ MORE
From the official docs:
To configure Docker ...READ MORE
There was no public API for managing ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/1142/how-to-use-a-build-arg-parameter-before-from-in-a-dockerfile | CC-MAIN-2020-40 | refinedweb | 292 | 68.47 |
Hello everyone,
Auto_ptr is convenient because of it saves our work and provides a framework to auto-management life cycle to reduce potential resource leak.
But why do we sometimes need to call release method on auto_ptr to go back to the style of manual management? Remember, when we call release, we need to delete the object instance manually later.
(here is a sample I modified from MSDN auto_ptr sample code)
Code:// auto_ptr_release.cpp // compile with: /EHsc #include <memory> #include <iostream> #include <vector> using namespace std; class Int { public: Int( int i ) { x = i; cout << "Constructing " << ( void* )this << " Value: " << x << endl; }; ~Int( ) { cout << "Destructing " << ( void* )this << " Value: " << x << endl; }; int x; }; int main( ) { auto_ptr<Int> pi ( new Int( 5 ) ); Int* pi3 = pi.release (); delete pi3; }
thanks in advance,
George | http://cboard.cprogramming.com/cplusplus-programming/99242-when-call-auto_ptr-release.html | CC-MAIN-2014-41 | refinedweb | 129 | 58.82 |
Caché eXTreme for .NET - direct access to globals from C#. Documentation says:
Caché eXTreme is a set of technologies that enable Caché to be leveraged as a high performance persistence storage engine optimized for XTP (Extreme Transaction Processing) applications.
Unlike the standard .NET binding, the eXTreme APIs do not use TCP/IP to communicate with Caché. Instead, they use a fast in-memory connection (implemented via standard .NET and the Caché Callin API), and run in the same process as the Caché instance. Although the Caché server and the .NET application must be on the same machine, the application can still use Caché ECP to access data on remote machines.
So how can it be used?
First of all, you have to set / check environmental variables of Windows:
- The variable GLOBALS_HOME should contain the full path to the directory where you put the DBMS. In my case, this is C:\InterSystems\Cache\
- The PATH variable must contain the full path to the Bin directory. In my case, this is C:\InterSystems\Cache\Bin
Beware, if you have several versions of Caché on the same machine, the one that occurs in this variable first will be used in Caché eXTreme.
Secondly, you have to add references to two libraries to your project:
- InterSystems.CacheExtreme.dll
- InterSystems.Data.CacheClient.dll
Both libraries can be found in the folder C:\InterSystems\Cache\dev\dotnet\bin\vXXX , where vXXX – version of .NET you want to use.
Naturally, in the corresponding module in the using section you need to add:
using InterSystems.Globals;
using InterSystems.Data.CacheClient;
After all the preliminary work is done, you can start actual programming.
Since Caché eXTreme allows you to record as subscripts four data types: int, double, string, long, and six data types as values: int, double, long, string, bytes [], ValueList, I tried to come up with a structure for the global, in which there will be as many types as possible. I took the data on bank card transactions as a subject area.
In Studio we can create a global with such structure:
set ^CardInfo(111111111111) = "Smith,John" set ^CardInfo(111111111111, "DBO546") = "Some bank 1" set ^CardInfo(111111111111, "DBO546", 29244825509100) = 28741.35 set ^CardInfo(111111111111, "DBO546", 29244825509100, 2145632596588547) = "Smith,John/1965" set ^CardInfo(111111111111, "DBO546", 29244825509100, 2145632596588547, 1) = $lb(0, 29244225564111, "John Doe", 500.26, "Payment for goods from ToysRUs") set ^CardInfo(111111111111, "DBO546", 29244825509100, 2145632596588547, 2) = $lb(0, 26032009100100, "John Smith", 115.54, "Transfer to own account in different bank") set ^CardInfo(111111111111, "DXO987") = "Some bank 2" set ^CardInfo(111111111111, "DXO987", 26032009100100) = 65241.24 set ^CardInfo(111111111111, "DXO987", 26032009100100, 6541963285249512) = "Smith John||1965" set ^CardInfo(111111111111, "DXO987", 26032009100100, 6541963285249512, 1) = $lb(1, 29242664509184, "Jane Doe", 500.26, "Recurring payment to Amazon") set ^CardInfo(111111111111, "DXO987", 26032009100100, 6541963285249512, 2) = $lb(0, 26548962495545, "John Doe", 1015.10, "Payment for delivery") set ^CardInfo(111111111111, "DXJ342") = "Some bank 3" set ^CardInfo(111111111111, "DXJ342", 26008962495545) = 126.32 set ^CardInfo(111111111111, "DXJ342", 26008962495545, 4567098712347654) = "John Smith 1965" set ^CardInfo(111111111111, "DXJ342", 26008962495545, 4567098712347654, 1) = $lb(0, 29244825509100, "John Smith", 115.54, "Transfer to own account in different bank") set ^CardInfo(111111111111, "DXJ342", 26008962495545, 4567098712347654, 2) = $lb(1, 26032009100100, "John Smith", 1015.54, "Transfer to own account in different bank")
So John Smith has accounts in 3 different banks with 1 card linked to each account and 2 operations done from each account.
To begin working with data, you need to connect to the DB first.
It was mentioned earlier that the application runs in the same stream as the database. So in the process there can only be one connection and all C# objects use this particular connection. To get it, use the
ConnectionContext.GetConnection() method. To check whether the connection is open or not, the
IsConnected() method is used. To open a connection, use the
Connect() method, to close -
The program will look like this:
class Program { static Connection Connect() { //getting conection Connection myConn = ConnectionContext.GetConnection(); //check if the connection is opened if (!myConn.IsConnected()) { Console.WriteLine("Connectiong..."); //if connection is not opened, then connect myConn.Connect("User", "_SYSTEM", "SYS"); } if (myConn.IsConnected()) { Console.WriteLine("Successfully connected"); //if OK then return opened connection return myConn; } else { return null; } } static void Disconnect(Connection myConn) { if (myConn.IsConnected()) myConn.Close(); } static void Main(string[] args) { try { Connection myConn1 = Connect(); //ToDo: work with globals Disconnect(myConn1); } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadKey(); } }
After the connection to DB is established there are several ways to save info to DB.
The first way is building a tree by adding subscripts (deepening from the root).
In order to start building a tree, you need to fix its root. In our case, this is the ^CardInfo value. This operation is performed using the
CreateNodeReference() method:
NodeReference nodeRef = myConn1.CreateNodeReference("CardInfo");
Once you have fixed the pointer to the root of the tree, you can begin to build it. The
nodeRef variable will always store a pointer to the node in the tree that is currently active.
To add a new subscript to a variable, use the
AppendSubscript() method , in which you can pass a double, int, long, or string value. To insert a value in the global node, use the
Set() method. It can accept values of types byte [], double, int, long, string, ValueList as the first parameter. The second parameter will be considered further, now it is not needed yet. If everything is clear with byte [], double, int, long, string, this is a standard byte array, a real value, an integer, long integer value and a string, then the last data type is a special data type for working with Caché system lists in COS using the $ListBuild function (also known as $lb ).
In general, until the
Set() method is executed, the data will not be written to the database.
node.AppendSubscript("111111111111"); node.Set("Smith,John"); node.AppendSubscript("DBO546"); node.Set("Some bank 1"); node.AppendSubscript(29244825509100); node.Set(28741.35); node.AppendSubscript(2145632596588547); string slip = "Smith,John/1965"; byte[] bytes = System.Text.Encoding.GetEncoding(1251).GetBytes(slip); node.Set(bytes); node.AppendSubscript(1); ValueList myList = myConn.CreateList(); myList.Append(0, 29244225564111, "John Doe", 500.26, "Payment for goods from ToysRUs"); node.Set(myList); myList.Close();
With each “step” the pointer to the current node will move to the newly added subscript.
However, we have another transaction. To add it in the same way, you need to go up a level. In order to do this (and generally to jump to any other level), the
SetSubscriptCount() method is used, to which the number of node subscripts (level number) is passed where the transition should be made.
node.SetSubscriptCount(4); node.AppendSubscript(2); myList = myConn.CreateList(); myList.Append(0, 26032009100100, "John Smith", 115.54, "Transfer to own account in different bank"); node.Set(myList); myList.Close();
Second way to write data is to set the values explicitly.
The previous section mentioned that the
Set() method can take two parameters. If only one is transmitted, then the value is inserted into the current global node. The second parameter is intended for a list of subscripts relative to the current node (to which the reference is stored in a variable of NodeReference type) where the value should be inserted.
Thus, to add account data in the next bank, you must first return to the level of a single index. To do this, use the
SetSubscriptCount() method with parameter 1. And further, using the
Set() method, simply add subscripts. In this case the pointer in
nodeRef after each operation will still be at the first level.
node.SetSubscriptCount(1); node.Set("Some bank 2", "DXO987"); node.Set(65241.24, "DXO987", 26032009100100); string slip = "Smith John||1965"; byte[] bytes = System.Text.Encoding.GetEncoding(1251).GetBytes(slip); node.Set(bytes, "DXO987", 26032009100100, 6541963285249512); ValueList myList = myConn.CreateList(); myList.Append(1, 29242664509184, "Jane Doe", 500.26, "Recurring payment to Amazon"); node.Set(myList, "DXO987", 26032009100100, 6541963285249512, 1); myList.Close(); myList = myConn.CreateList(); myList.Append(0, 26548962495545, "John Doe", 1015.10, "Payment for delivery"); node.Set(myList, "DXO987", 26032009100100, 6541963285249512, 2); myList.Close();
You may notice that this approach closely resembles COS code for creating globals. In the same way, every time we write all the subscripts relative to some base one and add its value to be saved in the database.
The third way to write data is to explicitly set the number of indexes to create a value at this level of the hierarchy.
The last approach to creating nodes is to explicitly set the level at which you want to add a new value. At the same time, unlike the previous approach, the pointer moves through the tree.
To indicate the level of the tree, the
SetSubscript() method is used, to which we pass two parameters: the required number of subscripts and the value of the new subscript. To insert values, the
Set() method is used, in which only one parameter is passed - the value of the node.
Apart from writing data into DB one needs to also be able to read existing data from the DB. Since globals are similar to trees and in the example we did not skip indexes, we can safely recursively go around the whole global and output its values.
To get all the values we will use the familiar methods SetSubscript() and AppendSubscript() . In addition to them, we will use the methods:
NextSubscript()- returns the value of the next index at the same level, similar to the $Next and $Order functions in COS.
GetSubscriptCount()- returns the number of indexes at the current tree level.
HasData()- checks if there is a value in this node, i.e. does it exist.
HasSubnodes()- checks if the current index has sub-indices.
node.SetSubscriptCount(0); node.AppendSubscript(""); string subscr = node.NextSubscript(); while (!subscr.Equals("")) { node.SetSubscript(node.GetSubscriptCount(), subscr); if (node.HasData()) { Console.WriteLine(" ".PadLeft(node.GetSubscriptCount() * 4, '-') + subscr); //ToDo: print node value } if (node.HasSubnodes()) { ReadData(node); } subscr = node.NextSubscript(); }
We see that all our indexes are beautifully displayed. Now you need to add the node values instead of ToDo.
Considering that all data is stored in Caché as strings, the programmer will either need to know at which level of subscripts what type of data is stored or check each chunk of data and make conversions. The
GetInt(),
GetDouble(),
GetLong(),
GetString(),
GetBytes(),
GetList() and
GetObject() functions are used to get global node values when you already know the type of data that is stored in this particular node. They return a value of type string and immediately convert it to type int, double, longInt, string, bytes [], ValueList, respectively. Last
GetObject() function returns an object whose type can be checked and converted to the value of the desired type.
As already noted, all data is returned as a string. If, in fact, the data type is numeric, the system can determine this. But the system always defines lists, arrays of bytes and the strings themselves as strings. Therefore, the processing of such data must take into account at what level what type of data is stored. This is the reason why it is considered a good idea to store the same type of data on the same level. Moreover, the system does not return an error when trying to display a list using the method of working with strings. Instead, a beautiful (but incomprehensible) text will be displayed:
So instead of ToDo in the previous code we can add the lines which will return the value of the node.
Object value = node.GetObject(); if (value is string) { if ((node.GetSubscriptCount() == 1) || (node.GetSubscriptCount() == 2)) { Console.WriteLine(value.ToString()); } else if (node.GetSubscriptCount() == 5) { ValueList outList = node.GetList(); outList.ResetToFirst(); for (int i = 0; i < outList.Length - 1; i++) { Console.Write(outList.GetNextObject() + ", "); } Console.WriteLine(outList.GetNextObject()); outList.Close(); } else if (node.GetSubscriptCount() == 4) { string tempString = Encoding.GetEncoding(1251).GetString(node.GetBytes()); Console.WriteLine(tempString); } } else if (value is double) { Console.WriteLine(value.ToString()); } else if (value is int) { Console.WriteLine(value.ToString()); }
After we compose all these parts of code into one program, we will get the result:
The whole .NET project is on GitHub.
If you have comments or questions please don't hesitate to ask.
The direct access to globals from .net is quite interesting but, as of right now, it has a major drawback: the Connect() method only allows the access to the cache database that is on the same machine.
If the server has at the same time the application and the database is fine. But otherwise, as usually the application server is different as the database server, you cannot use it.
We have checked the documentation and we haven’t found a way to connect to a database in another server using Caché eXTreme. There is any way to do it?
As stated in the 2nd paragraph:
Unlike the standard .NET binding, the eXTreme APIs do not use TCP/IP to communicate with Caché.
Instead, they use a fast in-memory connection
So by definition, it can't be on a different server. It acts like COS but in the .NET based language of your choice.
To separate physical storage from applications you may do this inside Caché using ECP
Yes, it is possible to use ECP to access another machine
I didn't test it yet. But should this works with .Net Core?
In theory it should work with .NEt Core, it depends on what InterSystems is using from core libraries. When you try it, please tell.
I can confirm that it works with .NET Core.
Thanks @Marc Francois!
Also note:
Is it possible to execute an equivalent to the merge command?
Doing this manual using recursive iteration and setting of single global entries would be much slower I guess?
There is no Merge in the Native API. Maybe in a future release?
As a workaround, you could create a class with classmethod Merge on ObjectScript which does the merge and call it via API.
Yes sure and using indirection I could create a generic method but it just feels as if this functionality is missing in the global api itself.
You are right, it is. Good enhancement request, thank you.
byte[] myByte....
node.Set(myByte)
if I set data from Image (or Bitmap) in byte[] array , it will be set correctly in : node.Set(myByte) ?
got error, in C# project :
InterSystems.Globals.GlobalsException: 'NodeReference.setBytesImpl: Array exceeds maximum length 3641144
3641144 - is a max length of a string in Caché/IRIS. So maybe the developers just used it to work with arrays in C# as well. I guess it's more a question for them, because I don't have access to the source code to see what's going on "under the hood".
extreme types , C# .net project <-> cache :
1. stream ,
can I use C# stream and setting it in Cache stream , any doc about or code example ?
2.C# ArraySegment to cache (2018.4) "array" or ^global ?
3. C# byte[] , as I mentioned above, is not working Cache as byte stream, maybe it's implemented as string settings.
4. from C# , call cache procedure , working ok,
but I did not found, how to get back an argument(or more than one) byRef ?
something like :
XTPcon.CallMyProc(proc,method,arg1, arg2, .BackVal1, .BackVal2)
no docs about
Social networks
InterSystems resources
To leave a comment or answer to post please log in
Please log in
To leave a post please log in | https://community.intersystems.com/post/cach%C3%A9-extreme-net-direct-access-globals-c | CC-MAIN-2021-04 | refinedweb | 2,573 | 66.13 |
12 February 2013 23:41 [Source: ICIS news]
Correction: In the ICIS story headlined "US Axiall reports large jumps in Q4, 2012 year-on-year net income" dated 12 February 2013, please read in the first paragraph …and a $35m year-on-year jump … instead of … and almost a 1,080% year-on-year jump …. A corrected story follows.
HOUSTON (ICIS)--Axiall posted a nearly 109% year-on-year rise in net income for 2012 and a $35m year-on-year jump in Q4 net income, thanks to increased sales volume and decreased full-year cost of sales, the company said on Tuesday.
Net income for 2012 was about $120.6m (€90.5m), up from the previous year’s $57.8m.
Net income for the fourth quarter of 2012 was $32.3m, up from Q4 2011’s loss of $3.3m.
Axiall reported net sales of $3.3bn for 2012, up about 3% from $3.2bn in 2011. Q4 2012 net sales were $784.7m, compared with $673.6m in Q4 2011.
“Our results exceeded our expectations for 2012, in large part due to the most profitable fourth quarter we have had in decades,” said Paul Carrico, president and CEO.
In the chlorovinyls segment, Q4 2012 net sales were $346.4m compared with $321.5m in Q4 2011. Operating income jumped to $77.0m in Q4 2012, compared with operating income of $21.5m in Q4 2011.
The $55.5m increase in operating income was primarily due to lower feedstock costs, higher vinyl resin sales volumes and higher caustic sales prices, Axiall said.
In the aromatics segment, net sales increased to $247.4m for Q4 2012 from $162.4m in 2011, due primarily to higher sales prices and higher sales volumes for all products. The segment recorded operating income of $18.3m in Q4 2012, compared with an operating loss of $3.7m during the same quarter in 2011.
The increase in operating income was primarily due to an inventory holding gain in the fourth quarter of 2012 compared with a large inventory holding loss in the fourth quarter of 2011, as well as higher volumes and sales prices in the fourth quarter of 2012, the company said.
In the building products segment, net sales were $190.8m for Q4 2012, compared with $189.7m for Q4 2011. The net sales increase was driven by increased Canadian sales volume and partially offset by lower sales volume in the ?xml:namespace>
US-based chlor-alkali producer PPG Industries announced on 28 January that its commodity chemicals business merger with US-based
Under the arrangement, PPG separated its wholly-owned commodity chemicals business, Eagle Spinco, and merged it with a subsidiary of
Axiall is expected to be the third-largest chlor-alkali producer and the second-largest vinyl chloride monomer (VCM) producer in
Additional reporting by Ken Fountain
( | http://www.icis.com/Articles/2013/02/12/9640380/corrected-us-axiall-reports-large-jumps-in-q4-2012-year-on-year-net-income.html | CC-MAIN-2015-22 | refinedweb | 476 | 66.64 |
On Wed, Jul 11, 2018 at 03:40:23PM +0300, Paul Irofti wrote: > > This is my original diff with some twaeks from visa@. > > While I think this is a step in the right direction I don't think is the > proper solution to the problem.
Advertising
It is not intended as final solution. My problem is that posixtestsuite does not finish during regress. Signals are not processes resulting in hangs. Then it is aborted by an overall timeout. > I don't think this handles pthread_kill() signals and I agree with mpi@ > that the path should be split between thread signals and process signals. The NetBSD approach seem correct. We need a pending signal list per thread and per process. This is just a bunch of work. > I will try to come up with something better in the following days. > In the meantime if you guys want to commit this bit, I will not > object. I am happy that pirofti@ jumps in for the correct fix. I would prefer if I could get oks for my version now. Then we would finish posixtestsuite during regress in time and see daily results here again. This would also help to visualize the effects of pirofti@'s fix. bluhm > > Index: kern/kern_sig.c > > =================================================================== > > RCS file: /data/mirror/openbsd/cvs/src/sys/kern/kern_sig.c,v > > retrieving revision 1.220 > > diff -u -p -r1.220 kern_sig.c > > --- kern/kern_sig.c 28 Apr 2018 03:13:04 -0000 1.220 > > +++ kern/kern_sig.c 9 Jul 2018 20:36:07 -0000 > > @@ -1155,14 +1155,17 @@ issignal(struct proc *p) > > int s; > > > > for (;;) { > > - mask = p->p_siglist & ~p->p_sigmask; > > + mask = SIGPENDING(p); > > if (pr->ps_flags & PS_PPWAIT) > > mask &= ~stopsigmask; > > if (mask == 0) /* no signal to send */ > > return (0); > > signum = ffs((long)mask); > > mask = sigmask(signum); > > - atomic_clearbits_int(&p->p_siglist, mask); > > + if (p->p_siglist & mask) > > + atomic_clearbits_int(&p->p_siglist, mask); > > + else > > + atomic_clearbits_int(&pr->ps_mainproc->p_siglist, mask); > > > > /* > > * We should see pending but ignored signals > > @@ -1840,7 +1843,7 @@ userret(struct proc *p) > > KERNEL_UNLOCK(); > > } > > > > - if (SIGPENDING(p)) { > > + if (SIGPENDING(p) != 0) { > > KERNEL_LOCK(); > > while ((signum = CURSIG(p)) != 0) > > postsig(p, signum); > > Index: sys/signalvar.h > > =================================================================== > > RCS file: /data/mirror/openbsd/cvs/src/sys/sys/signalvar.h,v > > retrieving revision 1.30 > > diff -u -p -r1.30 signalvar.h > > --- sys/signalvar.h 24 Mar 2018 04:13:59 -0000 1.30 > > +++ sys/signalvar.h 9 Jul 2018 20:52:50 -0000 > > @@ -68,7 +68,9 @@ struct sigacts { > > /* > > * Check if process p has an unmasked signal pending. > > */ > > -#define SIGPENDING(p) (((p)->p_siglist & ~(p)->p_sigmask) != 0) > > +#define SIGPENDING(p) > > \ > > + (((p)->p_siglist | (p)->p_p->ps_mainproc->p_siglist) & \ > > + ~(p)->p_sigmask) > > > > /* > > * Determine signal that should be delivered to process p, the current > > @@ -76,10 +78,9 @@ struct sigacts { > > * action, the process stops in issignal(). > > */ > > #define CURSIG(p) > > \ > > - (((p)->p_siglist == 0 || \ > > - (((p)->p_p->ps_flags & PS_TRACED) == 0 && \ > > - ((p)->p_siglist & ~(p)->p_sigmask) == 0)) ? \ > > - 0 : issignal(p)) > > + (((((p)->p_siglist | (p)->p_p->ps_mainproc->p_siglist) == 0) || \ > > + (((p)->p_p->ps_flags & PS_TRACED) == 0 && SIGPENDING(p) == 0)) \ > > + ? 0 : issignal(p)) > > > > /* > > * Clear a pending signal from a process. | https://www.mail-archive.com/tech@openbsd.org/msg46794.html | CC-MAIN-2018-30 | refinedweb | 495 | 68.26 |
The ultimate String Super Skills you must have: REGEX. Get out of trouble when it comes to text-string processing issues in Python with this super easy intro.
When working with data, there is always the possibility of having to deal with text. Be prepared for when the time arrives, you will be finding, processing and dealing pretty well with alphanumeric strings, with the help of a powerful friend inside Python.
I am talking about REGEX. Regex stands for Regular Expression and it describes a special sequence of characters used to search and manipulate words, digits, or other characters in text strings.
This introductory piece of content aims to give you a nice approach to the subject and to provide you with some (more) preliminary knowledge thought as essential to get you familiarized with Regex.
Because Regex is so powerful, vast, and complex, I bet you will be also sharing the same perspective that an infinite number of pythonic-possibilities open up before us. Let’s take a look at some basic commands.
To begin with, besides Pandas, let’s import the re module, unlocking everything related to Regex in python.
import pandas as pd import re
We also need to define a text on which we will be working on some examples throughout this article.
I selected a sentence written by Mat Velloso in a very curious attempt to distinguish between Machine Learning and Artificial Intelligence, in simple terms.
regex nlp python text data-science.
In this Python regex tutorial, learn how to use regular expressions and the pandas library to manage large data sets during data analysis. | https://morioh.com/p/d546d86369c2 | CC-MAIN-2020-50 | refinedweb | 269 | 60.75 |
Hope everybody already know that Java 8 is out. It brings a lot of interesting features to make Java easier and more comfortable to use. I will try to talk through some of those features in a nutshell.
Lets start with Optional class. As with all Java 8 features, Optional existed before the release, for example in Guava libraries. Optional class allows you to handle null checks in really nice way. Let’s look at the code. Say we have a User which can have a cat and lets say we have a map of two users Alice and Bob and Alice has a cat:
public static final String BOB = "Bob"; public static final String ALICE = "Alice"; public static final String FLUFFY = "Fluffy"; public class User { public final Cat cat; public final String name; public User(Cat cat, String name) { this.cat = cat; this.name = name; } public Cat getCat() { return cat; } } public class Cat { public final String name; public Cat(String name) { this.name = name; } public String getName() { return name; } } private Map<String, User> createMap() { Map<String, User> result = new HashMap<>(); User bob = new User(null, BOB); User alice = new User(new Cat(FLUFFY), ALICE); result.put(BOB, bob); result.put(ALICE, alice); return result; }
Now image all you have is a map and you want to get person’s cat name:
@Test(expected = NullPointerException.class) public void oldNpe() { Map<String, User> map = createMap(); assertEquals(map.get(ALICE).getCat().getName(), FLUFFY); // OK String catName = map.get(INVALID_KEY).getCat().getName(); // NPE // Have to do: User user = map.get(INVALID_KEY); if (user != null) { Cat cat = user.getCat(); if (cat != null) { catName = cat.getName(); } } }
You can just lookup key in the map, get User object and get it’s cat and here you go. Unfortunately, couple of calls in this line can return null:
- Map.get() can return null
- User.getCat() can return null
To overcome that you will have to write two nested if statements as shown on lines 10-16. Quite a lot of code for such simple tasks, right? Imagine if Cat would also have it’s favourite food as well, which can have a brand and you need to get it. Then you will be doomed to add another if and spend end of your life trying to understand how to format in sensible way 4 closing brackets.
Fear not fellow Java developer! Optionals to the rescue! Lets create helper method which will get person’s cat name in NPE-safe way:
private Optional<String> getCatName(String key, Map<String, User> map) { return Optional.ofNullable(map.get(key)) .map(User::getCat) .map(Cat::getName); }
Now, let me explain what is happening here:
On line 2 we are wrapping result of map.get() function to Optional object. Optional class is class used to potentially hold some object. It has 3 methods which we touch here indirectly:
isPresent()— returns true if Optional is not empty
get()— returns object which Optional object holds or throws
NoSuchElementExceptionif
Optionalis empty
map()— function which accepts a function which transforms
Optional<T>to another
Optional<Y>. The magic here is that map will call function *only if* original Optional will hold some value, otherwise it will just return empty optional, effectively doing Null check. Try looking at this code how map can work to convert
Optional<String>to
Optional<T>:
private <T> Optional<T> map(Optional<String> optional, Function<String, T> func) { if (optional.isPresent()) { return Optional.ofNullable(func.apply(optional.get())); } else { return Optional.empty(); } }
Now, lets get back to getCatName function. Once we got first
Optional<User> we apply map function using lambda expression. I will cover them in another blog post, for now you need to understand that it is basically tells to call
User::getCat() method BUT on User instance object if
Optional<User> is not empty. Line 3 will return
Optional<Cat> and we use same trick again to get
Cat name, which is returning result as
Optional<String>.
Now, we can demonstrate how to use this method:
@Test public void optionalSavesNullCheck() { Map<String, User> map = createMap(); Optional<String> aliceCatName = getCatName(ALICE, map); assertTrue(aliceCatName.isPresent()); // Alice has a cat assertEquals(aliceCatName.get(), FLUFFY); Optional<String> bobCatName = getCatName(BOB, map); assertFalse(bobCatName.isPresent()); // Bob does not have a cat assertFalse(getCatName(INVALID_KEY, map).isPresent()); // non-existent user does not have cat either }
As you can see, final code is much more clear than original if madness and it deliver same functionality and no NPE.
The “trick” here is that we never return null, we always return Optional object which holds information about previous operation results and allows itself to be used in subsequent operations.
I hope this blog post helped you understand hew Optional class in Java 8. If you have any questions, please use comment form below. | https://binarybuffer.com/post/2014-03-25-java-8-features-in-a-nutshell-optionals/ | CC-MAIN-2019-09 | refinedweb | 797 | 57.06 |
Answered by::
//AFX_STDAFX_H__38F261C7_B9D0_11D1_94AA_444553540000__INCLUDED_
#if_MSC_VER >= 1000
#pragmaonce
#endif// _MSC_VER >= 1000
#defineVC_)
Question
Answers
All replies
- What are your project settings? Specifcally what is INCLUDE set to? Does it include the location of the ATL headers? With a default install of Visual Studio 2005 they should be located at:
C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\include
- I found same error as follows;
------ Rebuild All started: Project: MkRich, Configuration: Debug Win32 ------
Deleting intermediate and output files for project 'MkRich', configuration 'Debug|Win32'
Compiling...
stdafx.cpp
c:\mkrich\mkrich\stdafx.h(21) : fatal error C1083: Cannot open include file: 'afxwin.h': No such file or directory
Build log was saved at ":\MkRich\MkRich\Debug\BuildLog.htm"
MkRich - 1 error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
// AFX_STDAFX_H__38F261C7_B9D0_11D1_94AA_444553540000__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#define VC
#include <afxdisp.h> // MFC class
#include <afxdtctl.h> // Internet Explorer 4
_)
- Hi Nikola, the default include path is:
Include="$(VCInstallDir)include;$(VCInstallDir)PlatformSDK\include;$(FrameworkSDKDir)include"
Can you show us the EXACT modified path?
e.g.
Include="$(ProgramFiles)include;xxxx
or
Include="C:\Program Files\xxx
Thanks in advance.
- Ermmm... but i thought the additional microsoft platform SDK that we can download has mfc and atl? I mean i can find afxwin.h in my microsoft platform SDK folder under "C:\Program Files\Microsoft Platform SDK\Include\mfc", its just that i have no idea how to modify the VCProjectEngine.Dll.Express.dll file to link it.
- Starting with VC 2005, you can no longer develop for MFC and ATL for free. You have to purchase a paid version of VC 2005 (i.e. Standard or better) to develop for MFC and ATL.
The files you see in the Platform SDK related to MFC are only for 64 bit development. 32 Bit development of MFC only comes with paid versions of VC 2005.
Ted.
- This thread describes how to update the directories in the Visual C++ Express Beta
- I get this error as well. Shame that as a learning tool it should be loud and clear what it can and can't do. If it's not allowed, how about a "You can't do that with ths tool" instead of some cryptic message you have to spend hours figuring out.
To me, this is disappointing as an evaluation tool. Coming over from another world I thought what better way to evaluate the tool than to download some code and try it out - alas, I can't do that becuase I guess the code I'm using can't be compiled. What I wantd to do is try out the code, change a couple of things and see what I get.
I have no problem paying but I want to see the tool is easy to use, helps me day to day, and doesn't hinder me to earn my company some dollars. Looks like I'm going to have to invest serious time as well as the dollars - just to figure out if this will be good for my company?
Too bad, I thought this was going to be a good thing....
....I would think that if MFC and ATL were more past experiences for developers that evaluation support would be a natural. Ya know, kind of a "learn from the past but look at what you get in the future". Instead I get an evalation tool that is - look, you got to learn it to use it no learning from the past is allowed. Sorry, not going to help me.
Too bad, I was excited to think that MS tools had finally 'got it'. Mmmmm, guess I'll go use my other tool .......
- I get the same error and I have net. 2005 professional edition with an MSDN subscription. I made a simple nfc dialog application and i get the fatal eeor c1083. If I created any mfc application I get that error. And if I start including reference to the include file then I get other errors that can not find other files are error complainng about crt library.
Am I missing something?
If anyone has a solution you can email me directly at sun_Water_snow@hotmail.com
thanks
I have the same problem.
Try this:
"Using Visual C++ 2005 Express Edition with the Microsoft Platform SDK
"By.Visual C++ 2005 Express Edition with the Microsoft Platform SDK"
Im not sure if it will work. I would try it but the file is to big for me to download.
- I don't mean to intrude, but I noticed following the link provided did not take me to the correct location. However, I was able to find it at
At least, this article has the exact same title and author.
Thanks
Hi all !
I have the SAME problem when using Visual Studio Express 2008 C++ edition : Error at compilation time, so I look at microsoft page.
Since 1/2/2008, there is a new SDK available :
Microsoft® Windows® Software Development Kit (SDK) for Windows Server® 2008 and .NET Framework 3.5
note:
This SDK is compatible with the RTM release of Microsoft® Visual Studio® 2005 Service Pack 1; including Microsoft® Visual Studio® Express Editions, which are available, free of charge. Pre-release editions of the next version of Microsoft® Visual Studio® are available from Microsoft® Visual Studio® 2008 Beta2 and can also be used with this SDK.
link =
I try to install it on my workstation, so dont know If it will fix my problem.....
pascal
-!!!
I couldn't find the IgnoreStandardIncludePath in vcproj. the file was created using MS VS .NET 2003 Pro.
Should I remove MS VS 2008 .net express edition, and reinstall MS VS .net 2003 pro?
- Proposed as answer by saber naderi Tuesday, January 18, 2011 9:33 AM
i have a some problem
i resolved with
project properties/c/c++ tab/command line delete /X
or
Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages .
Click the C/C++ folder.
Click the Preprocessor property page.
Modify the Ignore Standard Include Path property.
- I troubleshooted this for one day. It is an coding error that has existed in Visual Studio from at least 2003 to at least 2010. If in Windows Form application mode, if you add the stdafx.h include alone - it will work. But if you include it with additional include files which you add - you'll get that "no such file or directory" problem. For a Windows 32 project, it is there to begin with, and the program will work with those other includes. Pretty amazing that it has been there all these years - and that no one here has picked up on it. Probably no one else either.
- Proposed as answer by Jonathan Caraballo Wednesday, September 19, 2012 3:00 AM
Any "can't find stdafx.h"s encountered are a result of a programming error with Visual Studio. They're supposed to be in the project automatically. I got the same error when doing a Win32 application too. You can't include the StdAfx.h file without encountering this programming error in Visual Studio, if you include it with other files initially. What you must do is create the win32 application (which has stdafx.h), compile it, then add those other include files and compile it. Then it will work without that error.Finally, the age-old "can't find stdafx.h" error exposed! It only seems to appear sporadically. Not everyone encounters it.
- Edited by Jonathan Caraballo Thursday, October 04, 2012 4:52 PM | https://social.msdn.microsoft.com/Forums/vstudio/en-US/fcbb3f81-b6d0-48c5-b37c-ff0cf7fa7e88/stdafxh15-fatal-error-c1083-cannot-open-include-file-afxwinh-no-such-file-or-directory?forum=vcgeneral | CC-MAIN-2015-48 | refinedweb | 1,265 | 74.59 |
- <<
Code Tracing
Last updated Mar 14, 2003.
Before we dive into instrumenting the bytecode of classes we load into the JVM to perform code tracing, we need to review how we're going to perform the tracing in the first place. It may seem easy on the surface: set some kind of timer when a method starts, add another when the next method starts, etc. But that gets complicated because not only do we want to record the response time of individual methods but we also want to record the method traces, or the order in which methods call each other. We can solve this by maintaining some sort of “trace manager” that keeps track of all of this information for us, for example, we tell the trace manager when a method starts and ends, but chances are that we are eventually going to want to run this in some sort of complicated multi-threaded environment such as a servlet container.
What we would like to do is find some area of memory that we could use on a per-thread basis where we could store the start times and end times of methods. The solution to this problem is the ThreadLocal class. The Javadoc describes it as follows:
).”
To easily implement a tracing solution we're going to employ two core classes:
- Trace: maintains a list of “actions”, such as the start of a method, the end of a method, or the exceptional exit of a method, as well as the timestamp when the action occurred.
- Tracer: a class that extends ThreadLocal and exposes the Trace element for the current thread.
And we're going to need two helper classes:
- MethodAction: as described above, a method action denotes the start, end, or exceptional exit of a method and maintains the timestamp in which the action occurred
- TraceManager: when a trace ends, the trace is sent to the TraceManager, which maintains all traces for the threads running in the JVM.
Listing 1 starts with the simplest of these classes, the MethodAction class.
Listing 1. MethodAction.java
package com.geekcap.openapm.trace; import java.io.Serializable; /** * Defines a method action, which is either the start or end of a method. It records * the timestamp of the action as well as the id, which is the fully qualified method name. * * @author shaines */ public class MethodAction implements Serializable { private static final long serialVersionUID = 1L; /** * Is the method starting, ending, or did it throw an exception? */ public enum Action { START, END, EXCEPTION }; /** * The action for this event: START, END, or EXCEPTION */ private Action action; /** * The id for this event, which should be the fully qualified method name */ private String id; /** * The timestamp when this event occurred */ private long timestamp; /** * Creates a new MethodAction * * @param action The method action: START, END, or EXCEPTION * @param id The id/fully qualified name of the method */ public MethodAction( Action action, String id ) { timestamp = System.currentTimeMillis(); this.action = action; this.id = id; } public MethodAction( long timestamp, Action action, String id ) { this.timestamp = timestamp; this.action = action; this.id = id; } public Action getAction() { return action; } public void setAction( Action action ) { this.action = action; } public String getId() { return id; } public void setId( String id ) { this.id = id; } public long getTimestamp() { return timestamp; } public void setTimestamp( long timestamp ) { this.timestamp = timestamp; } @Override public String toString() { return timestamp + ": [" + action + "]\t" + id; } }
As you can see, the MethodAction class maintains an action (the Action enumeration is defined as a public enumeration inside the MethodAction class and defines the actions START, END, and EXCEPTION), an identifier, which will typically be the name of the method, and a timestamp. The idea is that you can create a new MethodAction of the form:
new MethodAction( MethodAction.Action.START, “MyMethod” );
MethodActions are maintained inside a Trace, shown in listing 2.
Listing 2. Trace.java
package com.geekcap.openapm.trace; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; /** * A Trace is a collection of method actions * * @author shaines */ public class Trace implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger( Trace.class ); /** * The trace key, which will be assigned by the TraceManager */ private String traceKey; /** * The ID of the head of the trace, which is used to identify the end of the trace */ private String headId; /** * The list of MethodActions (START, END, or EXCEPTION) that participated in this trace */ private List<MethodAction> actions = new LinkedList<MethodAction>(); /** * Creates a new Trace */ public Trace() { } /** * Adds a MethodAction to this trace, where a MethodAction may identify the * start of a method call, the end of a method call, or an exceptional exit of * a method call * * @param action The type of action: START, END, or EXCEPTION * @param id The method id, which is the fully-qualified method name */ public void addAction( MethodAction.Action action, String id ) { if( logger.isTraceEnabled() ) { logger.trace( "Add action: [" + action + "] " + id ); } if( actions.size() == 0 ) { // Save the head id of this trace headId = id; // Start the trace in the TraceManager and save the key traceKey = TraceManager.getInstance().startTrace( this ); } // Add the trace to the actions.add( new MethodAction( action, id ) ); if( action == MethodAction.Action.END && id.equals( headId ) ) { // Mark this trace as complete TraceManager.getInstance().endTrace( traceKey ); } } /** * Returns the list of method actions for this trace * * @return The list of method starts, ends, and exceptions */ public List<MethodAction> getActions() { return actions; } /** * Setter method, used for trace file reading * * @param actions The actions to set in this Trace */ public void setActions( List<MethodAction> actions ) { this.actions = actions; } public String getTraceKey() { return traceKey; } public void setTraceKey( String traceKey ) { this.traceKey = traceKey; } }
At its core, the Trace class only really maintains a list of MethodAction instances. It has some code logic to determine when a new trace is starting (the MethodAction list is empty) and when the trace is ending (the END action has been received for the method that started the Trace.) When a new Trace is started, the Trace obtains a trace key, or a unique identifier for the Trace, from the TraceManager so that traces can stay unique. When a Trace ends, it notifies the TraceManager that the Trace is complete and passes it that unique key. Because the Trace maintains a linked list of method actions, you could expect a trace internally to look like the following:
ParentMethod is starting (timestamp=...) ChildMethod1 is starting (timestamp=...) GrandChildMethod1 is starting (timestamp=...) GrandChildMethod1 is ending (timestamp=...) ChildMethod1 is ending (timestamp=...) ChildMethod2 is starting (timestamp=...) ChildMethod2 is ending (timestamp=...) ParentMethod is ending (timestamp=...)
And this would translate to a trace tree like the following:
ParentMethod ChildMethod1 GrandChildMethod1 ChildMethod2
And for each node we could compute the cumulative response time for each method (end time – start time) as well as the time spent exclusively in each method (end time – start time – (the sum of cumulative times for each child method)).
Next, listing 3 shows the source code for the Tracer, which is the class that extends ThreadLocal.
Listing 3. Tracer.java
package com.geekcap.openapm.trace; public class Tracer extends ThreadLocal<Trace> { private static final long serialVersionUID = 1L; private static Tracer instance = new Tracer(); public static Tracer getInstance() { return instance; } private Tracer() { } @Override public Trace initialValue() { return new Trace(); } }
The Tracer class is probably the simplest looking, in terms of code, but let's take it apart to see how it works. First, it extends ThreadLocal, which uses Java generics to define the specific type of variable that it is maintaining, and in this case the variable that the Tracer is maintaining is of type Trace. The Tracer class is a singleton, meaning that there is only one instance of the class for the thread (typically singletons mean that there is one instance for the JVM, but the fact that we extend ThreadLocal means that there is one instance for each thread.) To make a variable a singleton, you typically define an instance of it as a static member variable, define a private constructor so that no one can create an instance, and then define an accessor method such as getInstance() to control access to that single instance. In this case I opted to define the instance in the static initializer so that it is created as soon as the Tracer is created for the current thread; the alternative is to create the instance in the getInstance() method to “lazily” create the instance and then synchronize the getInstance() method to prevent multiple threads inadvertently creating multiple instances. Because this is ThreadLocal, the multithreaded concerns are gone so if you want to lazily create your Tracer, go for it.
ThreadLocal variables are accessed externally by the get() and set() methods, but internally ThreadLocal calls your class's initialValue() method to cause you to create an instance of the variable that should be “thread local” (a static instance for the current thread) and then it manages the get() and set() methods. Thus we extend initialValue() and return a new Trace instance, but when we use the Tracer we will use it through its get() method. This is how we'll add a new method action to the trace:
Tracer.getInstance().get().addAction( Action.START, "TestApp.method1" ); Tracer.getInstance().get().addAction( Action.END, "TestApp.method1" );
The getInstance() method returns the thread-scoped singleton instance of the Tracer method and then the get() method returns the Trace instance.
Finally listing 4 shows the source code for the TraceManager.
Listing 4. TraceManager.java
package com.geekcap.openapm.trace; import com.geekcap.openapm.trace.io.TraceWriter; import java.io.FileOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; /** * Manages all traces * * @author shaines */ public class TraceManager implements Serializable, Runnable { private static final Logger logger = Logger.getLogger( TraceManager.class ); private static final long serialVersionUID = 1L; /** * The instance of the TraceManager */ private static TraceManager instance = new TraceManager(); /** * Maintains all active traces */ private Map<String, Trace> activeTraces = new HashMap<String, Trace>(); /** * Maintains all traces that have been completed */ private Map<String, Trace> completedTraces = new HashMap<String, Trace>(); /** * True if the TraceManager thread is running false otherwise */ private boolean running = false; private boolean started = false; /** * Counter used for ensuring that trace ids are unique */ private long counter = 0; /** * Singleton accessor method * * @return Returns the instance of the TraceManager */ public static TraceManager getInstance() { return instance; } /** * Called by the Trace class when a trace is started * * @param trace A reference to the Trace that is starting * * @return A unique identifier for this trace */ public synchronized String startTrace( Trace trace ) { // Generate a key String key = Long.toString( System.currentTimeMillis() ) + "-" + counter++; // Put the trace in the active traces map activeTraces.put( key, trace ); // We've received a trace so put the TraceManager into a started state if( !started ) { started = true; } // Return the key to the caller return key; } /** * Signals the end of this trace * * @param key The key identifying the trace that is ending */ public void endTrace( String key ) { if( activeTraces.containsKey( key ) ) { // Move the trace to the completed trace map completedTraces.put( key, activeTraces.remove( key ) ); } } /** * Persists all traces gathered by the TraceManager */ private void saveTraces() { if( logger.isInfoEnabled() ) { logger.info( "Saving traces" ); } try { TraceWriter.write( completedTraces, new FileOutputStream( "trace-file.xml" ) ); } catch( Exception e ) { logger.error( "An error occurred while saving trace file: " + e.getMessage(), e ); } for( String key : completedTraces.keySet() ) { Trace trace = completedTraces.get( key ); StringBuilder sb = new StringBuilder( "Trace[" ).append( key ).append( "]:\n" ); for( MethodAction ma : trace.getActions() ) { sb.append( "\t" + ma + "\n" ); } System.out.println( sb.toString() ); } } /** * Starts the trace manager */ public void startTraceManager() { if( logger.isInfoEnabled() ) { logger.info( "Starting TraceManager" ); } // Set out state variables running = true; started = false; // Start the TraceManager in its own thread Thread thread = new Thread( this ); thread.start(); } /** * The TraceManager is configured to run in its own thread */ @Override public void run() { if( logger.isInfoEnabled() ) { logger.info( "TraceManager started" ); } // Run while running is true (control to be able to manually stop the TraceManager) // and while he have active traces (and we have received at least one so far) while( ( !started || activeTraces.size() > 0 ) && running ) { try { // 100ms sleep Thread.sleep( 100 ); } catch( Exception e ) { } } // Save our traces saveTraces(); if( logger.isInfoEnabled() ) { logger.info( "TraceManager shutting down" ); } } /** * Private constructor to ensure singleton pattern */ private TraceManager() { } }
We will probably modify the TraceManager as it is adapted to work in an integration environment, but for now it maintains all active traces and once the active trace list is depleted it saves the traces to a file using a helper class called TraceWriter. Listing 5 shows the source code for the TraceWriter, but note that it is sure to change before this article series is complete.
Listing 5. TraceWriter.java
package com.geekcap.openapm.trace.io; import com.geekcap.openapm.trace.MethodAction; import com.geekcap.openapm.trace.Trace; import java.io.OutputStream; import java.util.Map; import org.apache.log4j.Logger; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * Utility class that writes trace files * * @author shaines */ public class TraceWriter { private static final Logger logger = Logger.getLogger( TraceWriter.class ); /** * Writes the specified trace map to the specified output stream * * @param traces The trace map to write * @param os The output stream to which to write the trace map */ public static void write( Map<String,Trace> traces, OutputStream os ) { Element root = new Element( "trace-file" ); for( String key : traces.keySet() ) { // Load the trace Trace trace = traces.get( key ); // Build the trace element Element traceElement = new Element( "trace" ); traceElement.setAttribute( "key", key ); // Build the content of the node StringBuilder sb = new StringBuilder(); for( MethodAction ma : trace.getActions() ) { sb.append( ma.getTimestamp() + "," + ma.getAction() + "," + ma.getId() + "|" ); } sb.deleteCharAt( sb.length() - 1 ); traceElement.addContent( sb.toString() ); // Add the trace element to the document root.addContent( traceElement ); } try { // Write the trace file to the output stream using JDOM XMLOutputter out = new XMLOutputter( Format.getPrettyFormat() ); out.output( root, os ); } catch( Exception e ) { logger.error( "An error occurred while saving trace file: " + e.getMessage(), e ); } } }
The TraceManager class maintains its own thread so that it is assured to complete its task even after the main execution thread for your traced application completes. You can review the resultant XML file to see the details of each trace. | http://www.informit.com/guides/content.aspx?g=java&seqNum=586 | CC-MAIN-2015-06 | refinedweb | 2,358 | 53.41 |
- backtrader administrators last edited by backtrader
- Curtis Miller last edited by.
Would that be possible to have the renko block values in table instead of a plot? (I apologize if the answer is obvious as I'm a beginner with python)
It's not as difficult as it would seem
- Add a
Writerto your
Cerebroand the values of the data feed (your Renko bricks) will be printed as csv (i.e.: a table suitable for import in Excel for example)
See: Docs - Writer
Thank you it works with this : cerebro.addwriter(bt.WriterFile,csv=True). That produces a csv table along with the cerebro stats at the end in the console. Does the backtrader package as a command to write only the data in a actual csv file or should I use another package like csv? Thanks again for helping a newbie.
If you look in the docs, you can pass an
out=xxxparameter to the call
cerebro.addwriter, which is described as:
out(default: sys.stdout): output stream to write to
If a string is passed a filename with the content of the parameter will be used
Pass the name of a file or an open file.
That works thank you. Although with the
csv=Trueor
FalseI can't remove the cerebro stats at the end of the file. I'll add some code to delete those lines because my goal is to add data to this csv file in real time and generate trading signals from it. Thanks again.
If you want to do it real-time you will then have to read the values from the data feed (
highand
loware enough) and write them out yourself.
This is something you can easily do at the beginning of each
nextcycle before you do anything else
I'm having problems generating buy and sell signal after a certain amount of up or down renko ticks. I tried to couple those renko signals with 2 moving averages and 1 ADX indicators. The problem I face is I want those indicators to be run on the renko values and not the original data values. I had no luck so far to use 2 data feed, one to generate the renko and the other to run indicators on that first data feed.
@rchausse said in Renko Bricks:
The problem I face is I want those indicators to be run on the renko values and not the original data values
Emphasis on: "on the renko values"
@rchausse said in Renko Bricks:
I had no luck so far to use 2 data feed, one to generate the renko and the other to run indicators on that first data feed
Here you seem to do the opposite of what you said above (hence the emphasis, to make it clear), because you run the indicators "and the other to run indicators ..."
This may simply be that I misread your intentions.
The best thing would be a simple sample of what you try to achieve. It would really clarify things as to what's not working.
Sorry I wasn't clear at the end of the paragraph. I have a data file
.../dj.csvfor data feed
- I run the renko code above adding a buy order after 3 upticks and a sell order after 3 downticks
- Now I want those buy/sell signals to execute only if the third tick is above (for buy) or below (for sell) a simple moving average
- I don't know how to compute that simple moving average on the renko results instead of the
.../dj.csv
- I'm just a the pseudo code step for now and blocked on how to handle 2 data feeds
.../dj.csvand renko results for sma
The RSI in the
def __init__(self):just does that. I wrongly assumed the indicator was doing its math on the csv data source. I did the math ant it computes on the Renko output data. Basically, this question was on a wrong assumption.
- deepak singh negi last edited by
Hi, I noticed that Renko adds 1 brick for each input candle. However i would like to add multiple bricks if the closing price differs by that much. I looked into making a custom renko filter and was able to change the closing price, but it gives bricks of uneven sizes. How can i generate multiple bricks of same size.
@deepak-singh-negi said in Renko Bricks:
Hi, I noticed that Renko adds 1 brick for each input candle.
No. If they did, they wouldn't be Renko Bricks. The post clearly shows a comparison of the original data feed and the one with the Renko bricks which has less points across time.
@deepak-singh-negi said in Renko Bricks:
However i would like to add multiple bricks if the closing price differs by that much
You probably need to elaborate a bit more, because that's exactly the definition of the Renko briks: add a brick if the closing price differs by that much (where that has to be defined by you and is provided as the
sizeparameter to the filter)
- deepak singh negi last edited by
Renko adds a maximum of 1 brick for each input candle.
Lets say the brick size is 50 pips, and the next candle closes at a difference of 230. Currently "next" would generate 1 brick, I want to generate 4 bricks, to cover the difference of 200.
The problem is that the bricks need to be placed at a timestamp. At each timestamp you only have one output value for the lines of the data feed (in general these will be
OHLC)
In summary: you cannot therefore generate multiple bricks. Generating bricks of dissimilar sizes, what you apparently have already achieved, is your only possibility.
- Chia-Yu Chien last edited by
I.
For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: | https://community.backtrader.com/topic/511/renko-bricks/1 | CC-MAIN-2022-33 | refinedweb | 990 | 66.88 |
On 08/30/2011 07:45 AM, Josh Stratton wrote: > Oh,. I don't really understand what you mean; if you want to use code that was defined in another Python module, you always have to import it. It's just that in this case the module happens to be written in C++. >. This is another case where you probably want to use something other than a custom converter (and if you did use a custom converter, you'd want a from-python lvalue converter, not a to-python converter, anyways, and those are defined differently). What you probably want to do is tell Boost.Python that QSharedPointer is a smart pointer, and tell it to wrap your Scene objects inside one (at least if you're going to have to deal with them a lot). To do that, you'll want to specialize boost::python::pointee and provide a get_pointer function: namespace boost { namespace python { template <typename T> struct pointee< QSharedPointer<T> > { typedef T type; }; }} // in some namespace where ADL will find it... template <typename T*> inline Scene * get_pointer(QSharedPointer<T> const & p) { return p.get(); // or whatever } Then, when you define the class, use: class_< Scene, QSharedPointer<Scene> >(...) You can find more information in the reference documentation: Good Luck! Jim | https://mail.python.org/pipermail/cplusplus-sig/2011-August/016120.html | CC-MAIN-2016-40 | refinedweb | 212 | 68.7 |
This is a discussion on Re: Against the system:/, media:/ and home:/ namespaces - KDE ;=
th
> > kio_devices that we are trying hard to solve.
>
> Yes, that's what I wrote that a 'smart' solution needs here. But I think
> that inventing a new naming scheme just because the 'up' button does not
> work a bit of over-engineering.
Isn't this where the concept of a "back" button should be learned?
I was into writing something that looks like KDirStat for windows some year=
s =
ago.
Not having the definition of the relations between "This Computer", "Deskto=
p", =
"My Documents" completely clear (you know, they differ in reaction to your =
locale/language) it was a PITA to support as a programmer.
I would like to raise a loud warning about going where relations between pa=
ths =
are so virtual that "up" jumps between different locations on different =
depths within the real unix path. It is a pain to program for, and I guess =
people like it arranged differently as well. So perhaps the KDE devs would =
like to allow for *customized relations* as well (!!!). =
Now, how fun would it be to discuss bugs in such a system?
It isn't very broke as it is, right?
Please, stick to the back button instead of connecting "Up" from root of a =
removable device to something else than just the directory above.
There is one other view on this matter, namely to already be at the top of =
a =
protocol that doesn't have a local unix path representation, e.g. =
s
From there, it is far more logical that "Up" leads to system:/ or whatever =
instead of being disabled.
Please don't get too deep into complex virtualities about the filesystem.
Regards,
-- =
Jonas Widarsson
tel: +46 271 152 00 - tel: +46 271 121 42 (hemma/home) - gsm: +46 70 539 64=
79
MSN: jonaswidarsson@hotmail.com ICQ: 72016688 jabber: jonas@widarsson.com
=
>> Visit to unsubscrib=
e << | http://fixunix.com/kde/147546-re-against-system-media-home-namespaces.html | CC-MAIN-2014-41 | refinedweb | 324 | 70.84 |
Modules, Packages, and all that
One of the key features of Python is that the actual core language is fairly small. This is an intentional design feature to maintain simplicity. Much of the powerful functionality comes through external modules and packages.
The main work of installation so far has been to supplement the core Python with useful modules for science analysis.
Module
A module is simply a file containing Python definitions, functions, and statements. Putting code into modules is useful because of the ability to import the module functionality into your script or IPython session, for instance:
import atpy data = atpy.Table('my_table.fits')
You’ll see import in virtually every Python script and soon it will be second nature.
Question:
Importing modules and putting the module name in front is such a bother, why do I need to do this?
Answer:
It keeps everything modular and separate. For instance many modules have a read() function since this is a common thing to do. Without using the <module>.<function>(…) syntax there would be no way to know which one to call.
Sometimes it is convenient to make an end-run around the <module>. prefixing. For instance when you run ipython –pylab the interpreter does some startup processing so that a number of functions from the numpy and matplotlib modules are available without using the prefix.
Python allows this with this syntax:
from <module> import *
That means to import every function and definition from the module into the current namespace (in other words make them available without prefixing). For instance you could do:
from atpy import * data = Table('my_table.fits')
A general rule of thumb is that from <module> import * is OK for interactive analysis within IPython but you should avoid using it within scripts.
Package
A package is just a way of collecting related modules together within a single tree-like hierarchy. Very complex packages like NumPy or SciPy have hundreds of individual modules so putting them into a directory-like structure keeps things organized and avoids name collisions. For example here is a partial list of sub-packages available within SciPy
Finding and installing other packages
If you’ve gotten this far you have a working scientific Python environment that has most of what you will ever need. Nevertheless it is almost certain that you will eventually find a need that is not met within your current installation. Here we learn where to find other useful packages and how to install them. Package resources
Good vs. bad resources
When you find some package on the web, look for a few things:
- Good modern-looking documentation with examples
- Installs easily without lots of dependencies (or has detailed installation instructions)
- Actively developed
Search engines
Enter some keywords into your favorite search engine: “python blah blah” or “python seismology blah blah”
PyPI
The Python Package Index is the main repository for 3rd party Python packages (about 14000 packages and growing).
The advantage of being on PyPI is the ease of installation using
pip install <package_name>.
Package installation
There are two standard methods for installing a package.
pip install
The
pip install script is available within our scientific Python installation and is very easy to use (when it works). During the installation process you already saw many examples of
pip install in action.
Features include:
- If supplied with a package name then it will query the PyPI site to find out about that package. Assuming the package is there then
pip installwill automatically download and install the package.
- Will accept a local tar file (assuming it contains an installable Python package) or a URL pointing to a tar file.
- Can install in the user package area via
pip install <package or URL> –user(see discussion further down)
python setup.py install
Some packages may fail to install via
pip install. Most often there will be some obvious (or not) error message about compilation or missing dependency. If there are troubles with compilation, most likely the development package (usually marked with <dependency>-dev in the Linux package repository) of the missing dependency is not install. If installing the development packages doesn't solve the problem, the likely next step is to download the installation tar file and untar it. Go into the package directory and look for files like:
INSTALL README setup.py setup.cfg
If there is an
INSTALL or
README file then hopefully you will find useful installation instructions. Most well-behaved python packages do the installation via a standard
setup.py script. This is used as follows:
python setup.py --help # get options python setup.py install # install in the python area (root / admin req'd) python setup.py install --user # install to user's package area
More information is available in the Installing Python Modules page.
Where do packages get installed?
An important option in the installation process is where to put the package files. We’ve seen the
–user option in
pip install and
python setup.py install. What’s up with that? In general, if you don’t have to you should not use
–user, but see the discussion in Multiple Pythons on your computer for a reason you might.
WITH ''--user''
Packages get installed in a local user-owned directory when you do something like either of the following:
pip install --user asciitable python setup.py install --user
This puts the packages into:
On Mac if you did not use the EPD Python Framework then you may see user packages within
~/.local/lib as for linux. This depends on whether Python is installed as a MacOS Framework or not.
WITHOUT --user
This option may require root or admin privilege because the package will be installed in the system area instead of your own local directories. For most astronomers running on a single-user machine this is a good option.
Installing this way has the benefit of making the package available for all users of the Python installation, but has the downside that it is a bit more difficult to back out changes if required. How do I find a package once installed?
Finding the file associated with a package or module is simple, just use the help command in IPython:
import scipy help(scipy) This gives something like: NAME scipy FILE /usr/local/lib/python2.6/site-packages/scipy/__init__.py DESCRIPTION SciPy: A scientific computing package for Python ================================================ Documentation is available in the docstrings and online at. ...
Uninstalling packages
There is no simple and fully consistent way to do this. The Python community is working on this one. In most simple cases, however, you can just delete the module file or directory that is revealed by the technique shown above.
You can also use
pip uninstall <packagename> to uninstall the package. But make shure to check if all the files are really deleted.
Getting help on package installation
If you attempt to install a package but it does not work, your basic options are:
- Dig in your heels and start reading the error messages to see why it is unhappy. Often when you find a specific message it’s time to start googling by pasting in the relevant parts of the message.
- Send a message containing a detailed description of the installation error to a dedicated mailing list.
Where does Python look for modules?
The official reference on Modifying Python’s Search Path gives all the details. In summary:
When the Python interpreter executes an import statement, it looks for modules on'] >>>
Within a script it is possible to adjust the search path by modify
sys.path which is just a Python list. Generally speaking you will want to put your path at the front of the list using insert:
import sys sys.path.insert(0, '/my/path/python/packages')
You can also add paths to the search path using the PYTHONPATH environment variable.
This text is based on a chapter form the Practical Python for Astronomers by Tom Aldcroft, Tom Robitaille, Brian Refsdal and Gus Muench at the 2011 Smithsonian Astrophysical Observatory | http://psysmon.mertl-research.at/doku.php?id=install:understanding_packages_and_pip | CC-MAIN-2019-04 | refinedweb | 1,337 | 53.61 |
Hi everyone,
I am facing a problem when building a Seam enabled web application upon a
pure EJB module.
Simply put, I'd like to employ SMPC and manual flushing when the EJBs are used in the web tier while leave them as standard EJBs when accessed by other parts of the system (e.g. MDBs).
I have some of the EJBs defined as Seam components for web tier use, but as described above I was expecting those beans injected by @EJB to be managed by EJB containers rather than Seam. However, this is not the case:
@Name("seamEJB") // This is the EJB the web tier will have access to. @Stateless public class SeamEJB implements SeamEJBLocal { @PersistenceContext @In // I am expecting Seam to ignore this when the EJB is injected to other beans using @EJB EntityManager entityManager; public void someMethod(SomeEntity someEntity) { .... } }
// This is a standard EJB used in the back-end only @Stateless public class ClientEJB impelments ClientEJBLocal, ClientEJBRemote { @EJB SeamEJBLocal seamEJB; // Shouldn't seamEJB be managed by EJB container rather than Seam? (thus entityManager is injected by @PersistenceContext) public void clientMethod() { seamEJB.someMethod(entity); // This call may cause detached entity exception, since SMPC is injected in seamEJB } }
I think is a fairly logical expectation since I can always inject seamEJB as Seam component using:
@In SeamEJBLocal seamEJB;
So my question is:
Is this behaviour a bug in Seam? If not, then what would be the best way to share Seam components with a pure EJB module without suffering
detached entity exceptions/LIEs ?
Any suggestion is appreciated! Thanks in advance!
Hi,
When you use the name annotation you hand the management of the bean over to seam. For this seam uses its interceptors. I am not 100% sure , but I can imagine that the container is not able to decide which annotation to pick, when Seam is active. Annotations are not intrusive, so when you don't us seam the beans will work as expected.
Leo | https://developer.jboss.org/thread/192987 | CC-MAIN-2018-39 | refinedweb | 327 | 50.06 |
Closed Bug 909514 Opened 7 years ago Closed 7 years ago
Include <new> before mozilla::Maybe (and move Maybe into mfbt/Maybe
.h)
Categories
(Core :: MFBT, defect)
Tracking
()
mozilla26
People
(Reporter: justin.lebar+bug, Assigned: justin.lebar+bug)
References
Details
Attachments
(1 file, 1 obsolete file)
mozilla::Maybe uses placement new, so it should include <new>. In order to fix this, I need to move Maybe into its own file, because some random C++ test includes Util.h, and the compiler complains about infallible new when I use <new> in that file. I figure we want to do this anyway.
Whoops, forgot to include the removal of Maybe from Util.h in the previous patch.
Attachment #795654 - Attachment is obsolete: true
Attachment #795670 - Flags: review?(jwalden+bmo)
Comment on attachment 795670 [details] [diff] [review] Patch, v2 Review of attachment 795670 [details] [diff] [review]: ----------------------------------------------------------------- ::: js/src/jsproxy.h @@ +8,5 @@ > #define jsproxy_h > > #include "jsapi.h" > #include "jsfriendapi.h" > +#include "mozilla/Maybe.h" This should move up above the jsapi.h include, into its own include-section. ::: mfbt/Maybe.h @@ +3,5 @@ > +/* This Source Code Form is subject to the terms of the Mozilla Public > + * License, v. 2.0. If a copy of the MPL was not distributed with this > + * file, You can obtain one at. */ > + > +/* XXX */ /* A class for lazily constructing an object with stack-based lifetime. */ ? (although I'm not 100% certain Maybe is only used for stacked stuff, in practice -- probably this is something we should clarify with MOZ_STACK_CLASS if so) @@ +7,5 @@ > +/* XXX */ > + > +#ifndef mozilla_Maybe_h > +#define mozilla_Maybe_h > +#ifdef __cplusplus Get rid of this, this header's only useful in C++. (The same in Util.h dates back a really long time, to when JSAPI was C.) @@ +160,5 @@ > +}; > + > +} // namespace mozilla > +#endif /* __cplusplus */ > +#endif /* mozilla_Maybe_h */ A little breathing space: } // namespace mozilla #endif /* mozilla_Maybe_h */
Attachment #795670 - Flags: review?(jwalden+bmo) → review+
> ? (although I'm not 100% certain Maybe is only used for stacked stuff, in practice -- > probably this is something we should clarify with MOZ_STACK_CLASS if so) It's used inside a bunch of apparently non-stack classes. Without any deleterious effects, afaict. > +/* XXX */ Sorry I missed that!
I went with > /* A class for lazily constructing an object without sticking it on the heap. */
Let's make sure this builds everywhere:
Assignee: nobody → justin.lebar+bug
Status: NEW → RESOLVED
Closed: 7 years ago
Resolution: --- → FIXED
Target Milestone: --- → mozilla26
Fun fact: adding jsapi.h to BindingDeclarations increased the number of built files that depend on jsapi.h from 1563 to 2157. It appears to be entirely unnecessary. I'll land a follow-up to remove it once I confirm that it builds everywhere.
> Fun fact: adding jsapi.h to BindingDeclarations increased the number of built files > that depend on jsapi.h from 1563 to 2157. Okay, but I didn't do that in this patch!
> Okay, but I didn't do that in this patch! You sure about that?
Huh. It was in my original patch as context, but you're right, I added it back. I must have screwed up the merge. Sorry about that! | https://bugzilla.mozilla.org/show_bug.cgi?id=909514 | CC-MAIN-2020-05 | refinedweb | 515 | 68.67 |
did we get core
did we exit the process
did we get a signal
Detach
Do not detach
The prototype for APR child errfn functions. (See the description of apr_procattr_child_errfn_set() for more information.) It is passed the following parameters:
Opaque record of child process.
The APR process type
Opaque Process attributes structure.
Opaque control variable for one-time atomic variables.
The prototype for any APR thread worker functions.
Opaque Thread structure.
Opaque Thread attributes structure.
Opaque thread private address space.
Register a process to be killed when a pool dies.
Create a new process and execute a new program within that process.
Detach the process from the controlling terminal.
This is currently the only non-portable call in APR. This executes a standard unix fork.
Terminate a process.
Notify the maintenance callback of a registered other child process that application has detected an event, such as death.
rv = apr_proc_wait_all_procs(&proc, &exitcode, &status, APR_WAIT, p); if (APR_STATUS_IS_CHILD_DONE(rv)) { #if APR_HAS_OTHER_CHILD if (apr_proc_other_child_alert(&proc, APR_OC_REASON_DEATH, status) == APR_SUCCESS) { ; (already handled) } else #endif [... handling non-otherchild processes death ...]
Test one specific other child processes and invoke the maintenance callback with the appropriate reason code, if still running, or the appropriate reason code if the process is no longer healthy.
Test all registered other child processes and invoke the maintenance callback with the appropriate reason code, if still running, or the appropriate reason code if the process is no longer healthy.
Register an other_child -- a child associated to its registered maintence callback. This callback is invoked when the process dies, is disconnected or disappears.
write_fd duplicates the proc->out stream, it's really redundant and should be replaced in the APR 1.0 API with a bitflag of which proc->in/out/err handles should be health checked.
no platform currently tests the pipes health.
Stop watching the specified other child.
Wait for a child process to die
APR_CHILD_DONE -- child is no longer running. APR_CHILD_NOTDONE -- child is still running.
Determine if the child should start in its own address space or using the current one from its parent
Set the child_err and parent_err values to existing apr_file_t values.
Specify an error function to be called in the child process if APR encounters an error in the child prior to running the specified program.
Set the child_in and/or parent_in values to existing apr_file_t values.
Set the child_out and parent_out values to existing apr_file_t values.
Set what type of command the child process will call.
Create and initialize a new procattr variable
Determine if the child should start in detached state.
Set which directory the child process should start executing in.
Specify that apr_proc_create() should do whatever it can to report failures to the caller of apr_proc_create(), rather than find out in the child.
Set the group used for running process
Determine if any of stdin, stdout, or stderr should be linked to pipes when starting a child process.
Set the Resource Utilization limits when starting a new process.
Set the username used for running process
Setup the process for a single thread to be used for all signal handling.
Make the current thread listen for signals. This thread will loop forever, calling a provided function whenever it receives a signal. That functions should return 1 if the signal has been handled, 0 otherwise.
Create a new thread of execution
Return the pool associated with the current thread.
Return the pool associated with the current thread.
detach a thread
stop the current thread
block until the desired thread stops executing.
Run the specified function one time, regardless of how many threads call it.
Initialize the control variable for apr_thread_once. If this isn't called, apr_initialize won't work.
Get the child-pool used by the thread from the thread info.
force the current thread to yield the processor
Create and initialize a new threadattr variable
Get the detach state for this threadattr.
Set if newly created threads should be created in detached state.
Set the stack guard area size of newly created threads.
Set the stack size of newly created threads.
Return the pool associated with the current threadkey.
Return the pool associated with the current threadkey.
Create and initialize a new thread private address space
Free the thread private memory
Get a pointer to the thread private memory
Set the data to be stored in thread private memory | http://apr.apache.org/docs/apr/1.4/group__apr__thread__proc.html | CC-MAIN-2017-26 | refinedweb | 723 | 67.15 |
US5448442A - Motor controller with instantaneous trip protection - Google PatentsMotor controller with instantaneous trip protection Download PDF
Info
- Publication number
- US5448442AUS5448442A US08240196 US24019694A US5448442A US 5448442 A US5448442 A US 5448442A US 08240196 US08240196 US 08240196 US 24019694 A US24019694 A US 24019694A US 5448442 A US5448442 A US 5448442A
- Authority
- US
- Grant status
- Grant
- Patent type
-
- Prior art keywords
- motor
- current
- step
- routine
-/26—Arrangements for starting electric motors or dynamo-electric converters for starting dynamo-electric motors or dynamo-electric converters for starting an individual polyphase induction motor
-
Abstract
Description
This is a continuation of Ser. No. 07/714,293 filed Jun. 12, 1991, now abandoned which is a continuation-in-part of application Ser. No. 07/462,934 now U.S. Pat. No. 5,206,572 filed on Jan. 3, 1990 for Motor Controller, which is a continuation of application Ser. No. 07/209,803 filed on Jun. 22, 1988, now abandoned. This patent application is also related to patent application docket no. 203 244 filed with The United States Patent and Trademark Office concurrently herewith, and incorporates the full disclosure of patent application docket no. 203 244 by reference.
The invention generally relates to the protection and control of electric motors and, more particularly, to a motor control device which provides overload and short circuit protection for an electric motor.
When operating as a motor starter, a motor device functions to start, accelerate, and stop an electric motor by causing the various windings of the motor to be connected to, or disconnected from, a source of electric power in response to manual or automatic commands. To provide a desired sequence motor function based upon external inputs, motor starter logic can be implemented in conjunction with the motor starter. In addition to controlling the connection of power to the motor with contactors, the starter typically provides annunciator functions, such as visible status indication in the form of pilot lights. Each input and output, is generally binary in nature.
Motor starter logic can be implemented with electromechanical relays wired together according to a particular application. Relays, however, are large and relatively expensive. Consequently, logic circuitry using solid-state components have replaced wired-relay logic in some applications. Both of these techniques are still widely used, but are relatively inflexible. In the case of wired-relay logic, different applications may require expensive labor-intensive operations, such as rewiring and repositioning the relays. In the case of solid-state logic, different applications may require either modification of a circuit or a change in logic. In both cases, the lack of flexibility forces the manufacturer of the starter to build and stock different versions of starters for different applications. Each version may differ from another in the quantity, layout, and interconnection of components. Different manufacturing requirements for each version frequently result in problems of quality control. It is inconvenient, difficult, and costly to control the quality of many different versions of a motor starter.
The problem of inflexibility has been approached with the use of programmable devices. Programmable logic controllers (PLCs) are devices, usually containing a digital processor and a program memory, designed to make decisions based on successive single-bit information. The program steps stored in memory replace the combinatorial logic of solid-state and the wired logic of relay-type starters. Each input and output may be programmed to perform a particular control function. As the application changes, the generic inputs and outputs can be reassigned and the sequential steps reprogrammed. One problem with PLCs, as applied to the function of motor starting, its that the cost of a PLC is difficult to justify in simple starter applications requiring only a few inputs and outputs.
In addition to PLCs, relatively low-cost programmable integrated circuits designed for use in simple starter applications are available. One problem with these circuits is that the necessary supporting circuitry elevates the cost to unattractive levels relative to the cost of wired-relay solutions. The same can be said for any application using general-purpose programmable devices, such as microcomputers. If, however, a device could combine the function of motor starting with the function of overload protection such a device would prove useful and cost effective in many applications.
Overload relays are dedicated circuit protection devices designed to interrupt the flow of current in an electric circuit upon the detection of undesirable current levels over a period of time. Such current levels can lead to serious damage to a motor through the excessive heating of the motor windings. Upon detection of an overload condition, the overload relay outputs a trip command to a circuit opening mechanism such as a contactor, which disconnects the load from its power source. Many applications using motor starters also require motor overload protection. For such applications, an overload relay is typically connected into the motor starter circuit and housed in the same control unit enclosure containing the starter.
The most common overload relays are of the thermal type, which include a heater element through which the load current flows and a bimetallic strip that deforms as it is heated by the heater. If heated sufficiently, the bimetallic strip deforms to such an extent that it forces a contact open, which commands the contactor to open the motor circuit. One problem with thermal overload relays is that a supply of different heating elements must be maintained to adjust the relays for different load conditions. In practice, few, if any, extra heater elements are available when needed. Furthermore, any adjustments made are in discrete steps that depend on the ratings of the available heaters.
Electronic overload relays containing microcomputers, which measure the load current by means of current transformers and calculate the heating therefrom, avoid the adjustment problem of thermal devices, but at a greater cost. Even the low cost electronic overload relays, however, allow only a few parameters to be adjusted. Furthermore, the tripping characteristics of the electronic devices are designed to emulate the tripping characteristics of a thermal relay, instead of being designed to more accurately control the motor. To keep the cost of simple electronic overload relays competitive with the cost of thermal devices, inexpensive, low-performance microcomputers have been used. The cost of overload devices using higher-performance microcomputers cannot be justified for simple applications, therefor it would be desirable to combine the overload function with other needed functions.
In addition to providing a device for motor control it would be advantageous to avoid nuisance tripping during motor start times due to high starting current such as those found in high efficiency motors.
Nuisance tripping typically occurs during the first half cycle of motor starting if the starting currents rise above the magnetic trip limit of the circuit breaker protecting the motor. Additionally, nuisance tripping has become a bigger problem with the advent of high efficiency electric motors.
In the field, electricians improperly "solve" the nuisance tripping problem by raising the tripping threshold of the circuit breaker, which increases the possibility that the contactor can be destroyed due to a gap in protection. More specifically, a contactor arrangement will typically provide circuit interruption up to 10 the motor full load current, while the tripping threshold of the circuit breaker can typically be adjusted between 7 and 13 times the motor full load current. Thus, where an electrician increases the tripping limit to 13 times the full load current the motor will not be protected for motor currents between 10 and 13 times the motor's full load current.
Accordingly, it would be advantageous to provide a system which eliminates nuisance tripping caused by high transient starting currents which occur during motor starting.
The invention provides a motor control for sensing unacceptable current levels in a motor control system having a motor coupled to at least two phases including means for generating a first signal indicative of the current level in a first phase, means for generating a second signal indicative of the current level in a second phase, means for determining the greater of the first and second signals, means for comparing the greater signal to a designated trip limit, and means for generating a trip signal upon the greater signal exceeding the trip limit. The motor control.
The present invention still further provides a motor control for sensing unacceptable current limits in a motor control system having a motor coupled to at least three phases including means for generating a first signal indicative of the current level in a first phase, means for generating a second signal indicative of the current level in a second phase, means for generating a third signal indicative of the current level in a third phase, and means for determining the greatest of the first, second and third signals. The motor control further includes means for comparing the greatest signal to a designated trip limit, means for generating a trip signal upon the greatest signal exceeding the trip limit, limit.
The invention still further provides an apparatus for sensing ground fault and unacceptable current levels in a motor control system having a motor coupled to at least two phases, wherein the apparatus includes means for generating a first unrectified signal indicative of the current level in a first phase, means for generating a second unrectified signal indicative of the current level in a second phase, means for generating, from the first and second unrectified signals, an unrectified sum signal indicative of the sum of the current levels, means for rectifying the sum signal, first means for comparing the rectified sum signal to a designated limit, and first means for generating a trip signal upon the rectified sum signal exceeding the limit for more than a predetermined time period. The apparatus further includes means for rectifying the first and second unrectified signals, means for determining the greater of the rectified first and second signals, second means for comparing the greater signal to a designated trip limit, and second means for generating a trip signal upon the greater signal exceeding the trip limit. The apparatus level.
The present invention still further provides an apparatus for sensing ground fault and unacceptable current levels in a motor control system having a motor coupled to at least three phases. The apparatus includes a first current transformer disposed to generate an unrectified first voltage substantially proportional to the current level in the first phase, a second current transformer disposed to generate an unrectified second voltage substantially proportional to the current level in the second phase, and a third current transformer disposed to generate an unrectified third voltage proportional to the current level in the third phase. The apparatus further includes first means for generating, from the first, second and third voltages, an unrectified sum signal indicative of the sum of the current levels, first means for rectifying the sum signal, means for comparing the rectified sum signal to a designated limit, second means for generating a trip signal upon the rectified-sum signal exceeding the limit for more than a predetermined period, and second means for rectifying the first, second and third voltages. The apparatus further includes means for determining the greatest of the rectified first, second and third signals, means for comparing the greatest signal to a designated trip limit, and third means for generating a trip signal upon the greatest signal exceeding the trip limit. The apparatus further includes first means for disengaging the motor from the phases in response to the generation of a trip signal for a first designated period of time, and second means for disengaging the motor from the phases in response to the current level in one of the phases exceeding a predetermined current limit within a second designated period of time which is shorter than the first designated period of time, wherein the trip limit corresponds to a current level lower than the predetermined current limit.
The invention also provides a method for sensing unacceptable current levels in a motor control system having a motor coupled to at least two phases. The method-includes the steps of generating a first signal indicative of the current level in a first phase, generating a second signal indicative of the current level in a second phase, determining the greater of the first and second signals, and comparing the greater signal to a designated trip limit. The method further includes the steps of generating a trip signal upon the greater signal exceeding the trip limit, disengaging the motor from the phases in response to the generation of a trip signal within a first designated period of time,.
A preferred exemplary embodiment of a motor controller in accordance with the present invention will hereinafter be described in conjunction with the appended drawings wherein like designations denote like elements, and wherein:
FIG. 1 is a block diagram of a preferred embodiment of a motor controller;
FIG. 2 is a block diagram of a current detector for detecting the level of a single phase current for current-sensing management;
FIGS. 3A-3D when taken together as illustrated in FIG. 3 are a circuit diagram of the preferred embodiment of FIG. 1, excluding the parameter set/display device, the external communications device, the remote inputs, the transformers, and the motor circuit;
FIG. 4 is a circuit diagram of a preferred embodiment of a set/display device;
FIG. 5 is a flow chart giving an overview of the structure of the operating program for the microcomputer;
FIGS. 6A-6D are flow charts showing the sequence of program steps in the background tasks of FIG. 5;
FIGS. 7-13 and 14A-14B are flow charts of the interrupt service routines of FIG. 5;
FIGS. 15 and 19 are representations of the motor model;
FIGS. 16 and 17 are graphical representations of motor test data;
FIG. 18A-18E are flow charts illustrating the implementation of the motor model;
FIG. 20 is a block diagram representing a power distributing management including a motor control system;
FIG. 21 is a block diagram of the phase current summing and rectifying circuit;
FIG. 22A is a flow chart illustrating a first implementation of the ground fault protection scheme; and
FIG. 22B is a flow chart illustrating a second implementation of the ground fault protection scheme.
The motor controller performs two main functions: motor control (eg. starting, stopping, sequences of starting and stopping); and motor protection (eg. overload, ground fault, short circuit.)
Motor control is customized for particular applications by storing program steps representing control logic peculiar to the given application in a non-volatile programmable memory cell. Each set of program steps, which the microcomputer executes, includes an expandable library of program sets representing the different motor circuit applications available for configuring a starter to match its particular application. A configuration can be changed by simply loading into memory the appropriate set of program steps from the library and changing the labels of the inputs (signals from input buffer 117) and outputs (eg. signals to coil driver 113) to match the new application.
The detection of an overload, a ground fault, a motor jam, or a loss of load is realized in the code of the microcomputer and is based upon the root-mean-square (RMS), or effective, value of the motor current and changes in the current.
The method of measuring the RMS values of the load current includes sensing: the instantaneous current in at least one phase of a single or multi-phase electric circuit; and the sum of the load and neutral currents (single phase) or the sum of the phase currents (multi-phase). The method rates each current to a range suitable for electronic processing, converts each rated value to a digital representation, squares each digital representation, or sample, and digitally filters the squares of the samples to produce a digital word representing the DC value of the square of the load current. (Each word is also the square of the RMS value of the load current.) Subsequently, the square root of the resulting word yields the RMS value of the load current. As will be discussed below, the method described actually combines the filter and square-root procedures into a single procedure, obviating the need for a separate, time-consuming square-root procedure.
The functional schematic diagram of FIG. 1 shows an embodiment of the invention connected as an across-the-line motor starter with an electric motor 101 protected and controlled by a circuit opening and closing mechanism, such as a contactor 130 comprising contacts 103 and an actuating coil 104. Actuating coil 104 is energized by a coil driver stage 113. Coil driver stage 113 can also independently control up to two more contactors comprising contacts 105 and 107, and actuating coils 106 and 108, respectively. (Other motor starting applications, such as reversing, two-speed, and reduced-voltage, require the connection of more than one contractor to the motor circuit.)
In the across-the-line starting application shown in FIG. 1, current supplied to actuating coil 104 by coil driver stage 113 causes contacts 103 to close, connecting motor 101, via electrical current carrying conductors 102, directly to an AC power source 124, which supplies the power necessary to start and run motor 101. When coil driver stage 113 interrupts the supply of current to actuating coil 104, contacts 103 open, disconnecting motor 101 from the source of AC power. The decision to energize or de-energize the motor 101 is made by a microcomputer 123. Microcomputer 123, as directed by the operating program stored in its memory, controls the application of power to motor 101 by means of coil driver stage 113. Microcomputer 123, according to its program, translates input commands and conditions into output actions. Furthermore, by monitoring the current in motor 101, microcomputer 123 can protect motor 101 from damage due to excessive heating.
By way of example, the preferred embodiment of the motor controller can use a Motorola model MC68HC11 microcomputer. Details of the structure and operation of the MC68HC11 can be found in Motorola's published documentation on this microcomputer.
By way of further example, the contacts 103 and actuating coil 104 are embodied in contactor unit 130 which is appropriately sized to safely carry the motor current. Based upon NEMA (National Electrical Manufacturers Association) requirements, the contactor is typically of the type rated to interrupt over 15 times the motor full load current (IFLC).
The motor control system is subject to three types of input data. This data includes up to seven local commands entered via push buttons PB101-107; up to four remote commands entered via push buttons or contacts 109-112; and control data supplied from an external communications device 125. The control data can include programming data transmitted over an asynchronous serial communications link 127.
The seven local push button commands and the four remote contact commands are read by the microcomputer over an eight-bit bidirectional data bus 116, which is an extension of PORT C of the microcomputer. The local and remote input commands are buffered by an input buffer 117, which permits microcomputer 123 to read input commands or conditions by enabling buffer 117 with an enabling logic level on the appropriate output line of PORT B 126. By complementing the logic level to disable buffer 117, microcomputer 123 causes buffer 117 to isolate the inputs electrically from data bus 116, so that output commands can be issued over bus 116. In practice, buffer 117, shown schematically in FIG. 1, may comprise a plurality of physical buffers, each requiring its own dedicated enable line 126 from PORT B.
Both remote and local inputs are binary in nature, with a low logic level indicating an open contact (relaxed push button) and a high logic level indicating a closed contact (depressed push button). Microcomputer 123 reads the inputs periodically at a rate empirically determined to ensure detection of normal push button depressions. Microcomputer 123 also collects any input commands sent over asynchronous serial communications link 127.
A sequence of logic equations that translate input commands and conditions into output actions is stored in the memory of the microcomputer 123. PORT C is configured as an output and output actions are sent out over bus 116 to an output latch 115. The output actions are realized as binary logic levels on bus 116. The logic levels are latched into the output latch by a logic level transition sent to the output latch's clock input over one of output enable lines 126. In practice, output latch 115 may comprise a plurality of physical latches, each requiring its own dedicated enable line 126 coupled to PORT B. The logic levels latched to the output of output latch 115 are a coil driver stage 113 and a status indicator driver stage 114. Coil driver stage 113 performs control action by energizing or de-energizing actuating coils 104, 106, 108. Status indicator driver stage 114 independently controls up to thirteen discrete status indicators, such as light-emitting diodes (LEDs) LED101-114.
The following example illustrates a motor controller configuration along with the assignment of input and output functions for a typical application. References are to FIG. 1.
PB101--STOP (stop the motor)
PB102--START (start the motor)
PB103--Not used
PB104--HAND (hand, or local, control)
PB105--OFF (control disabled)
PB106--AUTO (automatic, or remote, control)
PB107--Reserved for a special function
Remote input 109--closed (start the motor) open (stop the motor)
Remote input 110--Not used
Remote input 111--Not used
Remote input 112--Not used
Coil 104--energized (start the motor) de-energized (stop the motor)
Coil 106--Not used
Coil 108--Not used
LED101--Overload/Instantaneous trip
LED102--Ground Fault Interrupt
LED103--Reserved for a special use
LED104--Reserved for a special use
LED105--Reserved for a special use
LED106--Reserved for a special use
LED107--Reserved for a special use
LED108--AUTO (control in automatic, or remote, control mode)
LED109--OFF (control disabled)
LED110--HAND (control in hand, or local, control mode)
LED111--Reserved for a special use
LED112--Not used
LED113--RUN (motor energized)
LED114--STOPPED (motor de-energized)
All of the defined inputs and outputs are binary, i.e., either off or on, "0" or "1", false or true, low or high. Consequently, each output is determined by solving a Bolean logic equation whose terms may include both inputs and outputs. For the example, six Boolean equations are required--one for each output assignment. The program code implementing the set of Boolean equations typically differs from one motor starter type to another, just as the function assignments of the inputs and outputs differ from one application to another.
In addition to providing motor control, the motor controller also protects motor 101, conductors 102, and any in-line devices, such as contacts 103, from damage due to unacceptably high currents. Alternating, the load currents IA, IB and IC, in respective phases of the three-phase motor circuit shown in FIG. 1, are sensed by current transformers CT101-CT103. The secondary currents in the current transformers CT101-CT103 are processed by a signal conditioning circuit 118, which converts the current signals to voltage signals proportional to the secondary currents in the transformers CT101-CT103.
Signal conditioning circuit 118 rectifies the voltage signals, thereby providing at its output rectified AC voltage signals proportional to the magnitudes of the secondary currents in the current transformers and, consequently, to the magnitudes of the load currents IA, IB and IC.
Each of the three rectified voltage signals is applied to one of the four individual PORTS E0-3 of microcomputer 123. Each input is connected internally to a different channel of the microcomputer's A/D converter 207 (FIG. 2). A/D converter 207 periodically samples and converts each of the three signals at its input channels, producing digital representations of the instantaneous magnitudes of the load current in each phase. Program code in microcomputer 123 uses the digital representations of the three load currents to determine whether protective action, such as interrupting the flow of power to motor 101 by opening contacts 103, is required.
In its function as a motor controller capable of being connected and programmed to handle many applications, the system in FIG. 1 may control, among other parameters, the starting, stopping, direction, and speed of a motor in response to operating conditions, manual commands, automated commands, local commands, or remote commands. By sensing the load currents (IA, IB and IC), microcomputer 123 can determine whether or not a contactor responded correctly to an open or close command. In its protective function as an overload sensing device, the system detects overload and unbalanced conditions by measuring the load currents. The motor thermal model (discussed below) implemented in the operating program uses the representations of the load currents and the percentage of current unbalance to compute the housing and winding temperatures of the motor and to trip the motor off before the temperatures reach damaging levels. Like the main functions of motor starting and overload protection, the further features of motor jam protection and loss of load protection (discussed below) rely on an accurate measurement of load current for correct operation.
FIG. 2 is a schematic block diagram of a current detector for detecting the level of one phase current of a three-phase current. The level of the other two current phases is detected similarly. Alternating load current IA in motor line 102 induces a proportional current in current transformer CT101. The constant of proportionality is determined by the number of turns in the secondary winding of current transformer CT101. The secondary current is applied to a burden resistor 203. The current produces a voltage across burden resistor 203 proportional to the secondary current and, thus, to the load current. The voltage across burden resistor 203 is rectified in a full-wave rectifier 204, or an absolute value circuit, producing an output voltage waveform 205 having a magnitude proportional to the absolute value of the load current.
The rectified voltage from rectifier 204 is applied to a sample-and-hold circuit 206 and an A/D converter 207. Sample-and-hold circuit 206 and A/D converter 207 are integrated into microcomputer 213. Sample-and-hold circuit 206 samples waveform 205 at the sampling frequency fs. The analog sample is then digitized by A/D converter 207 into eight bits covering a range from OV to the reference voltage level (2.5v or 5v). The eight-bit digital output of the A/D conversion ranges from 0 (decimal), or 00000000 (binary), for an OV input to 255 (decimal), or 11111111 (binary), for an input voltage equal to the reference level. The digital output of A/D converter 207 is the digital sample value used in the program's computation. The program requests another sample value every 1/fs seconds by sending a start conversion command to sample-and-hold circuit 206 and A/D converter 207 at a rate of fs (171 Hz).
The digitized sample value out of A/D converter 207 is squared in a multiplier 208 and applied to a digital lowpass filter 209. The output of digital lowpass filter 209, Ims, is a digital value proportional to the mean-square (MS) value of the load current. A square-root operation 210 produces the root-mean-square (RMS) value, Irms, from the mean-square value. It is the RMS value of the load current that is used by the program in its current-dependent computations (ground fault interrupt routine, intermediate motor protection routine, and motor model simulation routine discussed below).
Although sampling by A/D converter 207 precedes squaring in the actual current measuring sequence, the analysis can be performed such that squaring precedes sampling. (The two steps commute in theory.) In accordance with one embodiment, squaring is done in software to avoid the added cost of providing hardware to perform the squaring process.
In another embodiment of lowpass filter 209 operation, 60 consecutive squared samples are accumulated to produce an averaged mean-square current value Ims. For a sampling frequency of 171 Hz, a new Ims value is generated about every 350 ms. The square root of Ims is taken as discussed above in reference to block 210, and provides a new Irms value every 350 ms.
The purpose of digital lowpass filter 209 is to isolate the DC value of the squares of the load currents by blocking all of the higher order even harmonics and passing only the DC component of the load current. Under normal conditions, the load current comprises a fundamental frequency component (50 Hz [European] or 60 Hz [U.S.]) and a number of components at odd harmonics of the fundamental. The load current waveform depends on the relative amplitudes and phase relationships of the fundamental and its harmonics. When the signal representative of load current is squared by multiplier 208, another series of sinusoidal waveforms result having frequencies which are the sums and differences of all the frequencies in the original signal representative of load current. The relative amplitudes and phases of the frequency components in the original signal determine the relative amplitudes and phases of the components in the output, squared signal.
In the case of a series containing a fundamental and odd harmonics, the resulting squared series contains only even harmonics. Furthermore, the DC value (i.e., the 0th harmonic--a degenerate even harmonic) of the output series of multiplier 208 is the mean-square value of the original series. The sampling frequency (Fs) is an important parameter in the design of digital lowpass filter 208. Several criteria may be used in selecting the sampling frequency:
1. The sampling frequency should be as low as possible to minimize processing time;
2. The sampling frequency should result in a filter having a response time fast enough to handle the fastest specified trip time;
3. The sampling frequency should result in a filter that adequately attenuates the even harmonics in the square of the load current;
4. The sampling frequency should result in samples at many different relative points on the waveform from cycle to cycle to minimize the effects of A/D quantization levels; and
5. The sampling frequency should result in a filter that works well for both 50 Hz and 60 Hz systems.
A single-pole digital lowpass filter is represented by the iterative difference equation
Y.sub.k =aY.sub.k-1 +(1-a)X.sub.k,
where Xk is the kth sample input to the filter, Yk is the output of the filter computed using the kth input, Yk-1 is the previous output of the filter, and a is a filter coefficient between 0 and 1 related to the bandwidth. In a filter for the square of the load current, Xk is the square of the most recent sample of the current. The careful selection of the sampling frequency and the filter coefficient results in a filter that substantially satisfies the listed criteria, and the computed output Yk represents the mean-square value of the load current, and the square root of Yk represents the RMS value of the load current. The difference equation can be rewritten in terms of the RMS value (RMS) and the load current sample (I) as follows:
RMS.sub.k .sup.2 =aRMS.sub.k-1 .sup.2 +(1-a)I.sub.k .sup.2.
If the RMS value does not change significantly from sample to sample, as is typically the case, (i.e., RMSk is approximately equal to RMSk-1), the previous difference equation can be rewritten, after each term is divided by RMSk-1 as follows:
RMS.sub.k =aRMS.sub.k-1 +(1-a)I.sub.k .sup.2 /RMS.sub.k-1.
Thus, the RMS value can be computed from the input current sample and the previous RMS value without evoking a time-consuming square-root routine. Each time a new sample of the load current is made, a new RMS value is computed. In accordance with the preferred embodiment, a sampling frequency of 171 Hz and a filter coefficient of 1-2-4 (0.9375) give the desired results.
As will be shown and discussed below, microcomputer 123 uses the digital representations of the RMS values of the load currents in the three phases to: control the motor; provide overload protection; evaluate the performance of the motor; and provide short circuit protection to effect protective and control action as required. These digital representations are applied to a motor model for purposes of motor control.
In addition to providing the above listed functions, the motor controller also provides ground fault protection. For the three phase motor arrangement illustrated in FIG. 1, a ground fault measuring circuit 190 sums the secondary currents associated with the phase currents (IA, IB, IC) to determine whether or not their sum is substantially equal to zero. (For a single phase motor, circuit 190 (FIG. 1) functions to sum the secondary currents associated with phase current (IA) and the neutral phase current (IN) to determine if their sum is substantially equal to zero).
A feature of ground fault circuit 190 is its ability to sum the secondary currents sensed by current transformers CT101-103 and then rectify the sum without severely attenuating the secondary currents provided to burden resistors 203 (FIG. 2). Another feature of circuit 190 is its ability to sum the secondary currents before rectifying these currents. An advantage of performing the summing function before the rectification function is the ability to sum both the magnitude components and phase angle components of the phase currents. For many ground fault detection schemes, the secondary currents are rectified before being summed, and the polarity information associated with the secondary currents is truncated. Under certain circumstances, this truncation may provide a sum of zero (ground fault condition does not exist) when in fact the sum would not be zero (ground fault condition exists) if the polarity information would not have occurred.
Referring to FIG. 21, circuit 190 includes a load resistor 1902 associated with each current transformer CT101-103, a dropping resistor 1904, and a pair of operational amplifiers 1906, 1907. Each load resistor 1902 is coupled between the first terminal of one of current transformers CT101-103 and ground 1908. Dropping resistor 1904 is coupled between the second terminal of all current transformers CT101-103 and ground 1908. The second terminals of all current transformers CT101-103 are also coupled to a pair of resistors 1910 and 1912. Resistor 1910 is coupled to the noninverting input of operational amplifier 1906 and resistor 1912 is coupled to the inverting input of operational amplifier 1907.
The inverting input of operational amplifier 1906 and noninverting input of operational amplifier 1907 are each coupled to ground by a resistor 1916. The inverting inputs of operational amplifiers 1906, 1907 are connected to output 1920 of ground fault circuit 190 by feedback resistors 1918 and 1919. The outputs of operational amplifiers 1906, 1907 are each coupled to a diode 1914 which is coupled to output 1920 of ground fault circuit 190.
By way of example only, values can be assigned to the resistors as follows: resistor 1902--20 ohms; resistor 1904--10 ohms; resistors 1910, 1912, and 1916--1K ohms; resistor 1918--20K ohms; and resistor 1919--19K ohms. Using the referenced resistor values, operational amplifiers 1906, 1907 are provided with a gain of 20.
The arrangement of load resistors 1902, dropping resistor 1902, ground 1908 and current transformers CT101-103 provides the ability to sum each of the secondary currents, while simultaneously preserving the individual secondary currents for other functions such as overload and short circuit protection further discussed below. The sum of the secondary currents is provided to operational amplifiers 1906, 1907 which operate to rectify and amplify the sum, wherein the rectified sum is provided to output 1920.
Output 1920 is coupled to PORT E3 of microprocessor 123 and the voltage at output 1920 is converted to a digital signal by A/D converter 207 in the same manner as discussed above for waveform 205. The digital signal derived from PORT E3 is sampled at a rate of 171 Hz along with the other three PORTS E0-2.
When the motor controller is enabled to check for ground fault, a subroutine is called upon to analyze the digital signal derived from PORT E3. FIGS. 3A-3D illustrate, in further detail, the preferred embodiment of the invention in which the Motorola model MC68HC11 microcomputer is operated in the single-chip mode. Although microcomputer 123 can also be operated in the expanded, multiplexed mode in which the program may be stored in external memory, such as ultraviolet-erasable programmable ROM (EEPROM), it is anticipated that, for large-volume production, significant cost savings may be realized by using the microcomputer's built-in memory, with the program stored in the masked ROM and the Boolean logic equations stored in the EEPROM.
Microcomputer 123 uses the external clock 122 (FIG. 3D) as recommended by the manufacturer. A crystal X1 with a resonant frequency of 8 MHz, capacitors C2 and C3, and a resistor R5 are connected to the microcomputer's EXTAL and XTAL inputs as shown. The external 8 MHz crystal results in an internal 2 MHz E-clock and 500 ns instruction cycle times. A power supply circuit, 120 in FIG. 1, couples 5 Vdc power to microcomputer 123 through its VDD and Vss inputs. Capacitor C1 reduces noise on the power input to microcomputer 123. The single-chip mode of operation is selected when the MOD4 pin of microcomputer 123 is pulled low to ground potential through one resistor of resistor network RN5, and the MOD2 pin is pulled high to 5 Vdc through another resistor of RN5, selecting the single-chip mode of operation. The microcomputer's XIRQ pin is pulled high through yet another resistor of RN5, disabling the XIRQ interrupt. The following pins are unused and unconnected in the preferred embodiment: PA1; PA2; PA4; PA5; PA6; PA7; R/W; AS; PB0; PB1; PB2; PB7; PE3; and E.
Power supply circuit 120 provides unregulated 12 VDC and regulated 5 VDC sources of power. The unregulated 12 Vdc voltage powers driver chips U5, U7, and U11, LEDs (LED1-14), opto-triac drivers U12-14, and any remote alarm connected to a terminal block TB1 across terminals labeled REMOTE ALARM and +12V. Operational amplifiers in signal conditioning and powerfail/reset circuits are powered from VANALOG, which is derived from 12 Vdc through a blocking diode D19. During a power failure, a capacitor C44 maintains the VANALOG voltage long enough for powerfail/reset circuit 121 to operate properly before power is lost. The regulated 5 Vdc level powers the rest of the circuits, including digital integrated circuit elements U6 and U8-10 and set/display device 119, when connected.
A control power transformer, not shown in FIG. 3, supplies the power supply circuit with 12VAC isolated from the motor circuit. Chokes Z1-4, metal-oxide varistors MN1-3, and capacitors C302-306 provide noise filtering and overvoltage protection to the power supply circuit, while a fuse F1 protects the circuit from damaging current levels. Diodes D15-18 provide a full-wave rectifier with an unregulated output of 12 VDC. Capacitors C9 and C10 are filter capacitors, with C9 shunting most of the AC ripple to ground. The unregulated 12 VDC is connected to the input of a linear voltage regulator VR1, which produces the 5 Vdc level used to power the microcomputer and many of the logic circuits. A diode D21 prevents the 5 VDC level maintained by a capacitor C12 from discharging into the regulator in the event of a loss of input power. Another diode D20 compensates for the voltage drop across diode D21. Capacitor C12 is a ride through capacitor that maintains the 5 Vdc logic voltage for at least 200 ms when input AC power is lost, giving microcomputer 123 enough time to save certain variables into EEPROM. A capacitor C11 provides further noise reduction on the 5 Vdc logic level.
Powerfail/reset circuit 121 in FIG. 3C includes operational amplifiers U3D and U4D, resistors R9-10, R83-87, and R12, three resistors from resistor network RN5, capacitors C32-36, and PNP transistor Q2. Circuit 121 has two purposes:
1. to warn microcomputer 123 that the unregulated 12 VDC has dropped below 9V, so that an orderly shutdown sequence can be started, and
2. to reset the processor with a sharp reset pulse.
When the 12 VDC supply voltage drops below about 9V, the output of operational amplifier U3D, used as a comparator, drops low. Positive feedback produced by resistor R9 ensures a rapid, non-oscillatory low-going transition at the output. The falling edge on the IRQ pin of microcomputer 123 generates an interrupt, which vectors program execution to a routine that begins an orderly powerfail shutdown (isr-powerfail, discussed below). Capacitors C33-35 prevent noise or ripple from affecting the detection of a powerfail condition. The output of comparator U3D is also connected to input PRO. By reading PRO after saving certain variables in EEPROM, the program checks the status of the power supply. If the power supply has recovered by the time the saving procedure has finished, microcomputer 123 continues normal program execution. If the power supply has not recovered, the shutdown sequence runs to completion.
Transistor Q2 drives microcomputer's 123 RESET pin low about 200 ms after IRQ first goes low. Operational amplifier comparator U4D and its associated resistors R85-88 and capacitor C36 determine the delay. Resistor R86 ensures that a start edge necessary for a solid reset occurs. (A low-going transition on the RESET pin that tracks the MC68HC11's VSS voltage as it collapses can cause faulty program execution, which could result in the inadvertent erasure of portions of EEPROM.) During power-up, powerfail/reset circuit 121 clears the outputs of latches U6 and U8, thereby turning off status indicator driver 114 and coil driver 113.
The secondary windings of the current transformers CT101-103 in the motor circuit are connected to a signal conditioning circuit 118 (illustrated schematically in FIGS. 1 and 2) and ground fault detection circuit 190 (FIG. 19). Referring to FIG. 3C, circuit 118 includes operational amplifiers U4A-C and U3A-C, zener diodes ZD1-3, diodes D5-10, capacitors C7-8 and C29-30, burden resistors RB1-3, discrete resistors R15, R23, and R31, and twelve resistors from resistor networks RN1 and RN2, by a terminal block TB1.
The secondary of each of one of current transformers CT101-103 is connected between the terminal points labeled CT#1-3, respectively, and CT GND by resistor 1904 (FIG. 3B). The three current signals are applied to three similar absolute value circuits. Each circuit contains two operational amplifiers U3A, U3B, U3C, U4A, U4B, U4C--one for the positive half-cycle and the other for the negative half-cycle of the signal waveform. The values of the burden resistors are chosen to give the appropriate voltage range for the application. Zener diodes ZD1-3 provide some protection from voltage spikes of either polarity. Positive spikes are clipped at just over 5V by the forward-biased diodes; negative spikes are clipped at about -7V by the zener action of the 12V zener diodes. The gain of the full-wave rectifier circuit 204 is unity, as determined by the input and feedback resistors of operational amplifiers U3A-C, U4A-C (FIG. 3C).
Referring to the operation of the circuit for one current signal, the secondary current of the current transformer connected between terminal CT#1 and CT GND produces a proportional voltage across burden resistor RB1. When the voltage is positive with respect to ground reference potential, unity-gain, non-inverting operational amplifier U3B produces a positive output that forward biases signal diode D6. The feedback path from the cathode of D6 to the inverting input(-) of U3B maintains the voltage at the cathode at the level of the output voltage. The output of complementary unity-gain, inverting operational amplifier U3A is driven to the ground rail by the positive input voltage. Diode D5 is reverse-biased and does not conduct. Therefore the output at the cathodes equals the input. For a negative voltage across burden resistor RB1, the situation is reversed. The output of non-inverting amplifier U3B is driven to ground, preventing D6 from conducting, while the output of inverting amplifier U3A maintains the voltage at the cathode of D5 at the level of the input, but with the opposite (positive) polarity.
The output of the full-wave rectifier circuits 204 are connected directly to the microcomputer's 123 analog input channels PED-2. Capacitors C37-39 help filter the microcomputer's analog inputs for improved conversion results. Capacitors C7-9 filter the Vanalog supply of power to the operational amplifiers. The actual sampling and A/D conversion are performed by the microcomputer 123 internally.
Reference-switching voltage circuit 302 includes divider resistors RN5 and R92, capacitor C31 and field-effect transistor (FET) Q1. Microcomputer 123 PORT A bit 3 pin PA3 selects the reference voltage to be applied to the Vss pin (voltage reference high). When PA3 is low, the FET is turned off, preventing current from flowing through RN5, thereby applying a reference voltage of 5V at Vss. When PA3 goes high, turning Q1 on, a voltage divider is formed by resistors RN5, R92. The 1:1 resistance ratio results in a voltage of 2.5V at Vss. The voltage at the Vss pin is the maximum analog voltage that the A/D converter 207 will convert. The value of the least significant bit (LSB) of an A/D conversion is Vss /256. For Vss =5V, the LSB is worth 19.5 mV; for Vss =2.5V, the LSB is worth 9.76 mV. Thus, by switching the reference, more accurate conversions are possible at lower input current levels.
Local and remote input commands and conditions are read by microcomputer 123 over its PORT C pins PC0-7. Before inputs are read, bidirectional PORT C is configured as an input port and enables one of two tri-state inverting buffers U9 and U10 via PORT B lines PB6 and PB5. Buffer U10 buffers all but one of the local input commands. In the preferred embodiment, the local commands are entered by means of push buttons PB1-7 situated on the front of the physical package containing microcomputer 123. Push buttons PB1-6 are connected electrically between the ground reference and the inputs of buffer U10, so that when a push button is depressed, its associated input of buffer U10 is connected to ground through one of push buttons PB1-6. The inputs are pulled high to 5V through resistor network RN4, so that a relaxed push button results in a logic high at the input of the buffer. A logic low on pins OS1-2 from PB5 activates the outputs of buffer U10, allowing it to drive the PORT C bus. Because the buffer inverts its inputs, a depressed push button causes a logic high at the appropriate PORT C input. A logic high on OS1-2 from PB5 disables the outputs of the buffer, making them high-impedance outputs. Capacitors C18-24 help debounce the push buttons by shunting the high frequencies results from switch bounce to ground.
Buffer U9 handles the PB7 push button and four remote AC inputs. Remote AC inputs are generally contacts or push buttons connected between a source of AC power and terminals labeled AC INPUT1-4 on terminal block TB1. When a remote contact is closed or a remote push button depressed, an alternating current flows through the associated input of four-channel optocoupler U15. Resistors R74, R76, R78, and R80, connected in series with the inputs, limit the input current. Diodes D11-14 provide current paths during the negative half-cycles of the AC input current. Each section of optocoupler U15 is effectively an isolated half-wave rectifier. The output of each for a closed contact or push button is a zero-to-five-volt square wave at the line frequency (50 Hz or 60 Hz). The output for an open contact or push button is an open collector pulled high to 5V by its output pull-up resistor--one of the four resistors from resistor network RN4 connected from the 5V supply voltage and the open collector outputs of the optocoupler U15. Each of the four outputs is applied to an input of buffer U9. A spare input to the six-input buffer U9 is provided by the pull-up resistor from network RN6 connected between the 5V potential and input pin 12. Push button PB7 is connected to buffer U9 just as PB1 is connected to buffer U10. Microcomputer 123 reads the remote AC inputs and the TEST/RESET push button by enabling the tri-state outputs of U9 with a logic low at pins OE1-2 from PB6. The outputs of buffer U9 are disabled with a logic high at pins OE1-2.
To prevent contention on the PORT C bus, the program makes sure that no more than one buffer is active on the PORT C bus at any time and that PORT C is configured as an input while any buffer's output is active. The command input circuit is expandable to more inputs by connecting more buffers to the PORT C bus and unused PORT B lines to the enable pins OS1-2 of the additional buffers.
In addition to reading the local and remote inputs, bidirectional PORT C also controls coil drivers and status indicators. When PORT C is configured as an output, data written to it can be latched into one of two eight-bit latches U6 and U8 by a rising edge on the respective CK input of the latch. A rising edge on PB3, which is connected to the CK input of U6, latches the data on PORT C into U6. A rising edge on PB4 performs the same function for latch U8. The outputs of the latches control seven-channel driver chips U5, U7, and U11. A high logic level at a driver input causes the driver to conduct, turning on the device connected to it. The output of each driver channel is the collector of an NPN transistor with its emitter grounded. The circuit is expandable to more outputs by connecting more output latches to the PORT C bus and unused PORT B lines to the clock inputs CK of the additional latches.
Status indicators, such as light-emitting diodes LED1-14, are driven by drivers U5 and U7. Each LED, except LED7, is driven by an individual driver channel. LED7, serving in the preferred embodiment as a general fault indicator is connected so that it turns on if LED1, LED2, LED4, or LED5 turns on. To turn on LED1, for example, the microcomputer latches a logic high on PORT C pin PC2 into input D6 of latch U6 with a rising edge on PB3. The high logic level latched to the output of U6 turns on the associated driver channel of driver U5, causing its output transistor to sink current from the source of 12 VDC through a current limiting resistor R34. As a result, LED1 and LED7 are illuminated.
The operation of LED2, LED4, and LED5 is similar. LED3, LED6, and LED11 are also driven by driver U5, but are not connected to LED7. Current limiting resistors R50, R51, and R53 limit the currents in LED3, LED6, and LED11, respectively. Three LED12-14 are driven in a manner similar to LED11, except by means of driver U7, latch U8, and a latching signal from PB4. Resistors R55-57 are the associated current limiting resistors. Three LEDs LED8-10 share a common current limiting resistor R52, because, in the preferred embodiment, only one of the three LEDs is typically on at a time. Provisions for a remote alarm indication in the event LED4 is turned on are made by connecting the output of the driver channel in U5 that drives LED4 to the TB1 terminal labeled REMOTE ALARM. A remote DC coil connected between REMOTE ALARM and the TB1 terminal labeled +12V will be actuated whenever LED4 is turned on. A diode D19 and a metal-oxide varistor MN4 protect the driver from high voltage transients generated remotely, such as by inductive kick from the coil.
Microcomputer 123 can also drive remote contractor coils 104, 106 and 108 with latches U6 and U8, drivers U5, U7, and U11, and a coil driver circuit comprising optically-isolated triac drivers U12-14, triacs TR1-3, resistors R65-73, and capacitors C25-27. The coil driver circuit comprises three identical sections capable of independently actuating motor contractor coils 104, 106 and 108 connected to the circuit between TB1 terminals OUT1-3 and RETURN.
Consider the operation of the coil driver driving the coil connected to OUT1. Microcomputer 123 energizes remote coil 104 by latching a logic high at the output of latch U8 with a rising edge on PB4 and a logic high on PC1. The high at the output of the latch turns on the associated channel of driver U5, forward-biasing the LED in triac driver U14, which causes its internal triac to conduct and provide gate current to output triac TR3. The gate drive triggers TR3 which energizes motor contractor coil 104. Resistor R72 limits the triac driver's ON current. Resistor R71 and capacitor C27 form a snubber network for the output triac to suppress-high transient voltages that may occur upon switching.
The RxD and TxD pins PD0 and PD1 of microcomputer 123 are the input and output pins of the serial communications interface (SCI). The two lines are routed to external communications devices over a connector J1. The RxD and TxD lines, along with the +5V and ground connections on connector J1, constitute a minimum configuration for one end of asynchronous serial communications link 127 (FIG. 1). For those applications requiring devices such as line drivers and receivers or optical isolators due to physical demands, such as long distance transmission or noisy environment, the requisite circuitry can be added external to the unit containing microcomputer 123, thereby eliminating unnecessary cost in those applications not requiring the additional circuitry.
The other end of communications link 127 is a similar RxD and TxD pair of serial outputs and inputs from an external communications device 125. The two ends are typically connected through a multiple-conductor cable via J1. Data is transmitted serially from microcomputer 123 to external communications device 125 from PD1 (TxD); and serial data is received by microcomputer 123 from external communications device 125 through PD0 (RxD). The rate of serial data transfer (baud rate) is set by the operating program.
External communications device 125 can send control commands to the motor control and protection system. Besides sending commands, external communications device 125, like the set/display device 119 (discussed below), may set motor control and protection parameters. Furthermore, external communications device 125 may read various operating conditions transmitted by the microcomputer 123 over communications link 127. In addition to the display quantities and the settings of Table 1, the status of the indicator LEDs is transmitted by microcomputer 123 over the communications link 127. External device 125 must be programmed to communicate using the communications protocol programmed in microcomputer 123 and to translate the received data from the transmitted format into a format meaningful to the user of the data.
Another function of external communications device 125 is sending the code representing the Boolean motor starter equations to microcomputer 123. The MC68HC11 was chosen as the preferred embodiment of microcomputer 123 due to its 512 bytes of on-board EEPROM. Memory of the EEPROM type has the special characteristics of non-volatility (i.e., the contents of EEPROM do not change when power is removed, eliminating the need for expensive batter backup schemes) and electrical erasability and programmability (i.e., contents of EEPROM can be altered in-circuit, without using external erasing devices, such as ultraviolet lamps). Further advantages of the particular EEPROM cell in the MC68HC11 are that program code can be executed out of the cell and that the cell's size (512 bytes) can hold the required amount of code.
Program code and constants common to all applications are stored permanently in the masked ROM portion of microcomputer 123 memory. Program code implementing the set of Boolean equations developed for a given motor starter type is stored in the microcomputer's EEPROM. It is the EEPROM that gives the preferred embodiment its versatility. A single hardware configuration can operate as any one of many motor starter types. Serial communications link 127 permits transfer of the program code implementing the Boolean equations peculiar to the application to the EEPROM. The step of transferring the code, while usually performed by the manufacturer of the motor control and protection system at his own factory, may also be performed by a user outfitted with external communications device 125 programmed for the task.
Certain variables frequently updated by the operating program must be saved in the event of a loss of power to microcomputer 123. Examples of such variables are the elapsed running time on motor 101, the number of motor starts, and the number of overload trips. A powerfail detection and reset circuit 121 anticipates a power failure, notifying the microcomputer by driving its IRQ pin to a logic low level. The low-going transition at IRQ generates a microcomputer interrupt that vectors program execution to a routine that begins saving the variables in EEPROM. If the power failure persists, the circuit eventually applies a logic low level at the RESET pin of microcomputer 123, causing it to reset.
Microcomputer pins PD2-5 are the serial peripheral interface (SPI) through which parameter set/display device 119 is controlled. Electrical connection between microcomputer 123 and the set/display device 119 is made through connector J1 in FIG. 3D and associated connector J1 (FIG. 4). The SPI is an asynchronous serial communications interface with microcomputer 123 as the master controller and set/display device 119 as the slave. Data is transferred bit by bit between the master and the slave in eight-bit chunks. As one bit is shifted out of the master into the slave, one bit is shifted out of the slave into the master. During the shifting of bits, microcomputer 123 outputs the SPI shift clock signal SCK from PD4.
Referring again to FIG. 1, various motor and starter parameters may be entered manually and various status data displayed using a parameter set/display device 119. Device 119 can take the form of a hand held unit. In the preferred embodiment, device 119 is a passive device external to the physical package containing the microcomputer 123. Because device 119 includes no power source and no inherent intelligence, it must be connected to the microcomputer unit via connector J1 (FIGS. 3D & 4) to operate. The microcomputer unit serves as a master controller for device 119. Because device 119 is portable, it may be used with any master controller. Thus, in an application requiring a number of motor control and protection systems, only one device 119 is needed, resulting in a cost savings. Furthermore, such a device is a convenient means of permitting a user to change motor protection parameters and to monitor certain operating conditions. As illustrated in FIG. 4, device 119 includes a four-character liquid crystal display (LCD) 401 and a five-button keypad PB1-PB5 in a small hand-held enclosure (not shown). Device 119 is controlled by microcomputer 123 over its serial peripheral interface, a synchronous data transfer PORT D, pins 2-5.
Referring to FIG. 4, push buttons PB1-5 are connected between ground potential and individual inputs of an eight-bit parallel-in-serial-out shift register U2. All of the inputs are pulled high to +5V through individual resistors in a resistor network RN1. The status of the push buttons is latched into U2 by a logic high at the S/L input from microcomputer's 123 SS pin PD5. A depressed push button causes a logic low at the input, while a relaxed push button results in a logic high. Extra inputs F, G, and H, are pulled high. The eight input logic levels latched into U2, representing the status of the push buttons, are shifted out of pin Qn by raising S/L high and activating the shift clock SCK. Eight clock cycles shift the contents of the output shift register of U2 into the microcomputer's 123 SPI data register. The bits are shifted starting with input H and ending with input A. Thus, the first three bits shifted in are always high as long as the set/display device is connected. Because microcomputer's 123 MISO input, PD2 in FIG. 3D, is pulled low through a resistor from resistor network RN5 in FIG. 3D, eight consecutive low bits are read if device 119 is not connected. Microcomputer 123 can tell whether or not device 119 is connected from the states of the first three bits received.
While the push button status is shifted into the SPI data register through the MISO input, display data are shifted out to a liquid-crystal display (LCD) driver U1 through the MOS1 output, PD3 in FIG. 3D. The LCD driver contains a 35-bit input shift register. The first bit shifted in is always a logic high--the start bit. When the 36th bit is shifted in, the start bit is shifted out of the input shift register, loading the following 33 bits into the display latch of U1 to display the selected characters and clearing the shift register. The outputs of the LCD driver are connected to individual segments of a four-character, seven-segment LCD (LCD1). The 35 output bits include four characters by seven segments, three decimal point bits, and four trailing null bits. The LCD's backplane is driven from the driver's BP OUT pin. A resistor R1 and a capacitor C2 determine the frequency of the backplane oscillator internal to the LDC driver.
Power to drive the components on set/display device 119 is derived from pins 1 and 2, labeled +5V and GND on connector J1. A capacitor C1 reduces noise that may appear on the 5V power lines. A capacitor C3 is a by-pass capacitor for U2.
Table 1 lists function inputs, the description of each function input and the setting range for each function input.
TABLE 1______________________________________FUNC- SETTINGTION DESCRIPTION RANGE______________________________________F1 DISPLAY CONTROL 0-9999 CIRCUIT NUMBERF2 DISPLAY NEMA 1.sub.A, 1.sub.B, 1.sub.C, 2, SIZE 2.sub.A, 2.sub.B, 3, 4, 5, 6F3 DISPLAY NEMA SIZE FOR 1.sub.A, 1.sub.B, 1.sub.C, 2, LOW SPEED FOR A 2-SPEED 3, 4, 5, 6 MOTORF4 FULL LOAD CURRENT FOR 0.3-540 amperes OVERLOAD RELAY #1F5 FULL LOAD CURRENT FOR 0.3-540 amperes OVERLOAD RELAY #2F6 SERVICE FACTOR 1.0 or 1.15F7 OVERLOAD TRIP CLASS 2-23, with 1 second incrementsF8 AUTO RESET ON/OFFF9 PHASE UNBALANCE ON/OFF PROTECTIONF10 DISPLAY TIME TO RESET Variable accord- ing to motor sizeF11 ALLOW EMERGENCY RE- ON/OFF STARTF12 GROUND FAULT INTERRUPT ON/OFF ground (GFI) fault interruptF13 TIMER #1 0-200, with 1 second incrementsF14 TIMER #2 0-200 with 1 second incrementsF15 DISPLAY LOAD CURRENT .3-540 amperesF16 DISPLAY LAST TRIP .3-5400 amperes CURRENTF17 DISPLAY PERCENTAGE Percentage CURRENT UNBALANCEF18 DISPLAY MOTOR ELAPSED Up to 65535 hours TIMEF19 DISPLAY # OF Up to 6553 MOTOR STARTSF20 DISPLAY # OF OVERLOAD Up to 6553 TRIPSF21 RESET MOTOR DATA TO ON/OFF ZERO (F17, F18, F19)F22 SET PROCESS CURRENT Up to 100% of WARNING fully load currentF23 JAM PROTECTION ON/OFFF24 LOSS OF LOAD Warning/ ProtectionF25 DISPLAY ACCUMULATED Up to 250% of the THERMAL MEMORY temperature of the winding at full load current increments______________________________________
Microcomputer 123 carries out its designated functions by executing instructions from the operating program, stored in its memory. The program is illustrated in block diagram form in FIG. 5, and can be written in the assembly language of the MC68HC11. Alternatively, only portions of the program can be written in the assembly language, with the remainder being written in the high-level `C` language to minimize software development time.
The operating program comprises nine interrupt service routines, one background routine, and two short routines that run on reset. Five of the interrupt routines run at regular intervals, as scheduled using the MC68HC11's programmable timer, a 16-bit timer that permits the timing of events from 0.008 ms to 524.288 ms. Interrupts, for example, are scheduled using the timer in conjunction with output compare registers TOC1-5. The five timed interrupt routines, in order of priority, are:
1. isr-- ad (A/D conversion routine for the load currents)
2. isr-- inputs (Input scan routine)
3. isr-- hand (Set/display device input/output routine)
4. isr-- save (EEPROM update during powerfail)
5. isr-- timer (Long-term timer routine)
A sixth interrupt routine (isr-- eeupdate) compares the parameter setpoint images in EEPROM with the actual values in RAM and updates the EEPROM as required. The routine is bid by the realtime clock interrupt.
A seventh interrupt routine (isr-- shutdown) attempts an orderly shutdown in the event of a fault in the microcomputer, or central processing unit (CPU). An interrupt is generated, which vectors program execution to the shutdown routine, under any of the following conditions.
1. CPU watchdog timeout.
2. CPU clock failure.
3. Illegal opcode trap.
The routine sets the CPU and FAULT flag bits for the background task's fault logic.
An eighth interrupt routine (isr-- powerfail) is bid by an external interrupt generated whenever the 12 Vdc power supply voltage drops below about 9V. The powerfail routine starts the EEPROM update routine (isr-- eesave). If, after the EEPROM is updated, the control voltage remains below 9V, isr-- eesave sets the FAULT bit for the background task's fault logic. If the control voltage has recovered, standard program execution continues uninterrupted.
A ninth interrupt routine (isr-- sci) handles asynchronous serial communications with external devices. The routine is bid by interrupts generated by the SCI system upon various transmit and receive conditions.
Unless explicitly unmasked in one of the interrupt routines, neither the timed interrupt sources, the SCI interrupt, nor the external powerfail interrupt will interrupt the execution of the executing interrupt routine, regardless of the priority of the executing interrupt routine or of the interrupting source.
The background routine (main) continuously loops approximately once every 50 ms, processing data passed to it by the interrupt routines and responding appropriately. Whenever an interrupt routine is not being serviced, main is actively being executed. Upon a power-up reset, main initializes the stack pointer and configures the ports and registers of microcomputer 123 before activating the background loop. The loop handles the following:
1. Initialization upon reset (initializes the internal registers and variables, configures the CPU timers, kicks off the timed interrupt system, primes the SPI, starts the A/D conversion process, and turns the READY LED on) (step 502).
2. Logic solution (handles fault conditions and translates the push button and remote inputs into appropriate outputs) (step 504).
3. Set/display device (changes and retrieves data as requested or needed by the isr-- hand interrupt service routine) (step 506).
4. Serial communications messages (processes setpoint changes received over the serial communications link and formats for transmission messages bid regularly by isr-- timer) (step 508).
5. Motor protection calculations (solution of the motor model, ground fault protection and intermediate protection (step 510).
Each of the background tasks is usually bid by an interrupt service routine, which sets a calling flag upon detection of an appropriate calling condition. The flag is usually cleared by the background task upon completion of this execution or disappearance of the calling condition.
After a power-up reset, the first routine to run after the two brief reset routines is main (step 514). This routine first takes care of some housekeeping chores before execution reaches the background loop. The loop is a circular sequence of tasks. Each task is executed in order as long as its calling bit is set. If a task's calling bit is not set, the task is skipped and the next task's calling bit is checked. After the last task is executed or skipped, the first task's calling bit is checked, completing the loop. All the background tasks may normally be interrupted by any source. Maskable interrupts can be held off only if interrupts are explicitly disabled in the background program. The most important housekeeping chore performed by main prior to executing the background loop is setting the INITIAL flag bit (step 512) to bid the initialization task to run.
There are two reset routines: .reset (step 516) and startup (step 518). The `C` startup routine (.startup) is always inserted in the program by the `C` linker during program development. The stack pointer is initialized in startup. The routine .main is called as a subroutine from the startup routine. Because main includes the continuous background loop, execution does not return to the startup routine from .main. Some of the registers in the MC68HC11 must be written to within the first 64 E-clock cycles after power-up or not at all. The code to do this, written in assembly language and labeled .reset, is vectored to upon power-up reset. After initializing (step 520) the appropriate registers as required, the routine causes execution to jump to the `C` startup routine.
The routine main includes the background loop, as shown in the flowchart of FIG. 5. Main is entered upon a power-up reset by being called from the `C` startup routine. Main first sets the INITIAL flag to bid the initialization task, shown in the flowchart of FIG. 6A, to run. After setting the INITIAL flag, execution proceeds to the background loop.
First, the background loop checks the INITIAL flag (step 522). If the INITIAL flag is set, which occurs after a power-up reset, the initialization task runs. After first disabling the outputs (step 650) of the hardware input buffers U9 and U10 in FIG. 3D, the task initializes certain variables in RAM (step 652) either to constants stored in ROM, to zero, or to values saved in EEPROM. Examples of variables initialized to values saved in EEPROM include the setpoints, the elapsed run time of the motor, the number of motor starts, and the number of overload trips. By way of a more specific example, the values used in the motor model simulation routine (discussed in detail below) are initialized as follows:
To =1° C.
to =1 sec
Io =1 A.
Ro =1° C./W
Co =1 Wsec/°C.
Po =1 W
t=O
Tw=O
Th=O
P1 =O
P2 =O
P=36 Po
Tw restart=80 To
Th trip=60 To
Th flc=50 To
Rw =30 Ro
Rh =50 Ro
Cw =5.14 Co
Ch =Co /R.sub. * 7+53 (1-e.sup..01 (Iflc /Io))
Tw flc =80 To
Tw max =140 To
The task also sends out over the SCI a message requesting an external communications device to transmit logic equation code to reconfigure the application. If the external device does not respond, the configuration remains as it is. If the device responds by transmitting new logic equation code, the task reads the new code and programs it into EEPROM (step 654). The task then configures the microcomputer's 123 internal registers (step 656) for the desired operation. Examples include enabling the SPI and setting its shift clock rate, setting the realtime clock rate, unmasking the programmable timer and realtime clock interrupt flags, and turning on the READY LED, LED11, indicating microcomputer 123 is running. Then the A/D conversion 207 system is activated (step 658) and its interrupt routine scheduled (step 662). Before clearing the calling flag INITIAL (step 664) and enabling the timed interrupt system (step 666), the task primes the SPI that controls set/display device 119 (step 660). The initialization task is then executed.
After a new set of readings of input commands is made, interrupt service routine isr-- inputs sets the calling flag SOLVE to bid the logic solution task to run. If the SOLVE flag bit is set (step 524), the logic solution translates local push button, remote contact, and input commands received over the communications link into LED indicator and coil driver outputs.
The program code for all inputs and outputs that are not common to all motor starter applications contemplated is stored in the microcomputer's EEPROM. Code common to all applications is stored in ROM. The code stored in EEPROM is executable code implementing the Boolean logic equations for the particular application and written in assembly language to conserve memory space.
The message processing task (step 508), as shown in FIG. 6B, allows setpoints to be changed using device 119 or device 125, and data to be transferred. When a setpoint change is to be made (step 668), microprocessor 123 memory is revised with the new setpoint data (step 670). If a message flag is set (step 523), the appropriate message is selected (step 672), and transmitted byte-by-byte (steps 674 and 676). After transmission of a complete message, the message flag bit is cleared (step 678).
The logic solution task (step 504), as shown in FIG. 6C, first checks the FAULT and POWERFAIL flags (step 600) to see whether a fault or an imminent powerfail condition exists. If so, the LEDs and coil drivers are turned off (step 602) and the STOPPED LED turned on (step 604), and execution proceeds to the TEST/RESET push button logic (step 606). If not, the Boolean logic equations for the particular application are solved (step 608). The logic equation code, stored in EEPROM, is executed as a subroutine called from the logic solution task. The subroutine does most of the translation from inputs to outputs. The triggering of certain timing functions (step 610), such as a transition timer and an incomplete sequence timer for reduced-voltage starters, externally settable timer #1, and externally settable timer #2, is handled by the logic equation code. Because all four timers mentioned are started by control commands or motor events, the logic equation program decides when the timers should start and what action to take when they time out. The program sets a flag bit corresponding to the timer to be started. Execution returns from the logic equation code in EEPROM to the common logic solution code in ROM.
The flag bits to start the timers are checked. If any is set, the program starts the timer (step 612) by setting the appropriate timer active flag bit and the timeout time. The long-term timer interrupt routine isr-- timer handles the timing. The logic solution task then checks to make sure that motor start and stop commands were executed correctly (step 614). If a stopped motor is commanded to start, load current should be detected within one second. If motor current is not detected, the program sets the incomplete sequence IS flag bit (step 616). If motor current is detected, the number of starts, which is an important factor of the life related to contacts 103, is incremented. The number of starts is available for monitoring through function F18 (see Table 1) of set/display device 119. On the other hand, if a running motor is commanded to stop and load current does not drop to zero within one second, the IS flag bit is set. After checking for these start/stop faults, the task checks for the occurrence of incomplete sequences or external trips by testing the IS and EXT flag bits (step 618). The IS flag may be set by the logic equation code upon unsuccessful completion of the transition in reduced-voltage starter applications or as just described for start/stop faults. The EXT flag bit is set by the logic equation code for those applications having an external trip input as one of the remote input assignments. If either flag bit is set, the FAULT flag bit is set (step 620), which causes the program to bypass certain normal operations.
The logic solution task next executes the TEST/RESET push button logic (step 606). In the preferred embodiment, push button PB7 is dedicated as the TEST/RESET button. The program uses one of the long-term timers controlled by isr-- timer to determine whether the button has been depressed for the class time set in memory, initiating an overload test by setting the OLTEST flag bit. If the TEST/RESET button is released before the timer times out or if the motor is running, the LAMPTST flag bit is set, bidding the lamp test. Another long-term timer is used to time the lamp test, which turns on all the LEDs for two seconds.
The next function performed by the logic solution task is latching the output actions to the LED and coil drivers. The computed outputs are sent via PORT C. To avoid conflicts with the reading of the inputs over bidirectional PORT C, interrupts are first disabled (step 622), which suspends isr-- inputs, the routine that reads the inputs. Then PORT C is configured as an output (step 624), and the first output group is written to PORT C and latched into latch U6 with a rising edge on PB3. The procedure is repeated for the second output group with PB4. If the LAMPTST flag bit is set (step 626), the LEDs are turned on (step 628). Interrupts are then re-enabled (step 630) and the calling flag bit SOLVE cleared (step 632).
The set/display task (step 506), shown in the flowchart of FIG. 6D, is bid to run by the set/display interrupt routine isr-- hand. Besides setting the calling flag bit HAND, the interrupt routine sends the background task the latest keystroke entered from set/display device 119 (step 634). The background task detects the set HAND flag bit, decides what action the keystroke requires, and sends to the interrupt routine four bytes representing the four characters to be sent to the set/display device's liquid crystal display.
When the HAND bit is set (step 526), the set/display task controls the sequences displayed on the LCD, makes sure that proper commands are entered, selects the value or message to be displayed on the LCD,and makes setpoint changes as required (steps 636-644). Upon completion, the task clears the calling flag bit HAND.
To make the design of set/display device 119 simple and inexpensive, only five push buttons, labeled FUNCTION, DISPLAY, DOWN, UP, and ENTER, are used. The set/display task controls what is displayed. The use of each push button is best understood from an example, such as enabling or disabling ground fault interrupt (GFI). When connected to microcomputer 123, set/display device 119 displays either a function number from Table 1 or a display or setpoint value for one of the functions. If, for example, the LCD is displaying "F22", meaning that function 22 (loss of load) is ready to be operated on, one of the scroll buttons (UP or DOWN) must be used to scroll to the desired function, F12 (GFI). Scrolling in either direction is possible. If the UP button is pressed, the display changes from "F22" to "F23". If the UP button is held in, the display will change to "F24", then to "F1", then "F2", and so on, scrolling consecutively through the functions. When the displayed function is "F12" the UP button should be released Depressing the DISPLAY button causes the existing setpoint value to be displayed, in this case it may be ON which represents that GFI is disabled. The displayed value may be incremented or decremented through the possible choices for the particular function (F12) by depressing the UP or DOWN push button, respectively (ON or OFF). For F12, depressing either the UP or DOWN button once will switch GFI from On (existing setpoint) to OFF. At this point the new setpoint can be entered by pressing the ENTER button. If the DISPLAY button is pressed instead, the existing setpoint, "ON" is redisplayed. If the FUNCTION button is pressed, the function, "F12", is displayed Only if the ENTER button is pressed with a setpoint value in the display is the setpoint changed. For those functions that merely display some quantity, such as load current, pressing the ENTER push button has no effect. To speed up the process of changing setpoint values, provisions are made for fast scrolling. If the UP or DOWN button is held in, the function or the setpoint selections will be scrolled through at a faster rate. The example shows how the set/display background task controls the setting of various motor parameters and the display of various measured quantities with a minimum of hardware in the set/display device.
At the completion of the set/display task, the background routine calls the motor model simulation routine (FIGS. 18A-E), the intermediate motor protection routine, and the ground fault interrupt routine (FIG. 22). These routines are run about every 50 ms. These three routines are illustrated and described as separate routines, but could be all combined into one routine such as the motor model simulation routine. At the completion of these three routines, the background routine checks the status of the INITIAL calling bit, restarting the loop.
The A-D conversion routine (isr-- ad) (step 702) (FIG. 7) runs at a rate of 171 Hz, the sampling frequency selected based on the criteria previously discussed. The MC68HC11's converter is configured for single-channel, non-continuous operation by clearing the SCAN and MULT bits in the A-D control/status register ADCTL. Consequently, upon the completion of each conversion cycle, which is indicated by the microcomputer's setting of the conversion complete flag bit (CCF) in ADCTL, the eight-bit results of the conversions on the selected channel are stored in the A-D result registers ADR1-ADR4.
The routine reschedules itself by means of output compare timer TOC1 to run four times every 1/171 Hz, or every 1.46 ms. Each time the routine runs, one of either voltages representative of the three load currents or the voltage representative of the sum of the three load currents is converted. In other words, each waveform representative of one load current and the waveform representative of the sum is sampled (step 704) at a rate of 171 Hz.
Range switching has been implemented to yield greater accuracy. By switching the reference voltage from 5V to 2.5V by means of the range-switching circuit described earlier, greater accuracy is achieved. For a V reference, the LSB is worth 19.5 mV; for a 2.5V reference, the LSB is worth 9.76 mV. To scale the readings correctly, all readings made with the reference at 5V (step 706) are multiplied by two (step 708, shifted left once) before being combined with the readings for a 2.5V reference in the calculation of the RMS values of the load currents and the sum of the load currents. The criterion for range switching is based on the highest calculated RMS value of the three load currents. If the highest value is greater than 255 binary counts (step 710), which corresponds to a voltage of 2.5V at the input to the A/D converter, a 5V reference voltage is needed to prevent saturation of the converter. In such a situation, the routine selects the 5V reference (step 714) with a logic low at PA3. Otherwise, a 2.5V reference voltage is selected (step 712) with a logic high.
The A/D converter does not generate an interrupt upon completion of a conversion. The microcomputer marks the completion of a conversion cycle by setting the CCF flag bit in ADCTL. Because a conversion cycle takes about 0.06 ms, it is reasonable to expect the conversion to be complete by the time the isr-- ad routine runs again about 1.95 ms later. After reading the-converted value, selecting the reference setting, scheduling the next interrupt (step 716), incrementing the channel by 1 (step 718), checking the channel (steps 720 and 722), and starting the next conversion (step 724), isr-- ad computes the RMS value for each of the voltages representative of the load currents (IA, IB, IC) and the sum of these currents (step 726). The RMS values are computed according to the difference equation described previously.
Isr-- ad is set up to take 60 samples of each channel (240 samples total) before returning (step 738). A counter is set up and incremented every cycle (step 728) until 240 total samples are taken (step 730).
The input scan routine (isr-- inputs), whose flowchart is shown in FIG. 8, reads over bidirectional PORT C the local push button and remote contact inputs. Input GROUP 1, which includes the four remote AC inputs and the front panel TEST/RESET push button input, is read by enabling the input buffer, U9, with a logic low on PB6. Input GROUP 2, which comprises the remaining local push button inputs, is read by enabling U10 with a low on PB5. The scan routine alternates between the two groups (step 812), reading one each interrupt. The routine reschedules itself to run with output compare timer TOC2 (step 800), configures PORT C as an input port (step 802), reads one of the two groups on each pass (steps 804-806), deselects the buffers (i.e., returns them to tri-state with a logic high on PB5 and PB6) (step 808), and sets the SOLVE calling flag bit (step 810) to bid the logic solution task to run. The logic solution task is bid to run in the background every other TOC2 interrupt. Thus, the logic equations are solved every time a new reading of all the inputs is completed.
The rate at which isr-- inputs runs is determined by two factors. First, the push buttons should be read often enough so that a typical button depression is detected by at least two consecutive readings. Second, the AC inputs must be detectable at both 50 Hz and 60 Hz. The difficulty in detecting an AC input is that the signal out of the optoisolator, U15 in FIG. 3, is a zero-to-five-volt square wave at 50 Hz or 60 Hz when the remote contact or push button is closed. Analysis of 50 Hz and 60 Hz square waves shows that, if sampled every 27.5 ms, at least one of every three consecutive samples is from the zero-volt section of the waveform. The presence of a zero-volt section distinguishes the closed condition from the open condition. Consequently, the interrupt rate for isr-- inputs was chosen to be half that, or 13.75 ms.
While the background loop processes inputs from and determines outputs to the set/display device 119, the interrupt service routine isr-- hand actually reads in the inputs and sends out the outputs. FIG. 9 is the flowchart of isr-- hand. Each time it reads the set/display push buttons, isr-- hand simultaneously outputs eight bits to the LCD driver chip, U1 in FIG. 4. The routine reschedules itself to run every 30 ms by means of output compare timer TOC3. The rate is fast enough to update the LCD at a pleasing rate and to scan the push buttons often enough so no depressions are missed.
Set/display device 119 is controlled by the MC68HC11's serial peripheral interface (SPI) with microcomputer 123 as the master and device 119 the slave. Data are shifted out serially over the MOSI line to the LCD driver and shifted in over MISO from the push button's parallel-in-serial-out shift register. A group of eight bits is shifted out at each transfer. Upon completion of the transfer, the eight bits written to the LCD are replaced in the SPI data register by the eight bits shifted in from the push button's shift register.
When the routine begins after a TOC3 interrupt, the SPI data register contains the most recent reading of the push buttons. The interrupt routine first unlatches the shift register (step 900) with a logic low on the S/L input, then schedules the next TOC3 interrupt (step 902). To clear the SPI transfer complete flag bit in the SPI status register SPSR, the SPSR register must first be read. The flag bit is then cleared when the data register SPDR is read (step 904). The contents of the data register represent the set/display push buttons. Furthermore, the three most significant bits of the push button shift register are pulled high. The routine determines whether or not device 119 is connected by checking those three bits (step 906). If they are not read as high, device 119 is presumed to be disconnected, the HAND flag bit is cleared (step 908) and no processing is required. If device 119 is determined to be connected and a button depressed, the calling flag HAND is set (step 910), bidding the background task to process the push button data. The buttons are prioritized in the following order: FUNCTION, DISPLAY, DOWN, UP, ENTER. If more than one button is depressed, only the one with highest priority is processed (step 912).
After reading the input, isr-- hand initiates the next data transfer. First, the push buttons are latched into the shift register with a logic high at the S/L input (step 914). The next eight bits to be transferred to the LCD driver are written to the SPI data register (step 916), automatically starting the transfer. The SPI system in microcomputer 123 takes over and shifts out eight bits to the LCD, while shifting in eight bits from the push button shift register (steps 918 and 920). The shifting process is completed long before isr-- hand runs again.
One complete output to the LCD driver is five bytes long. The first four bytes comprise a start bit (a logic high), three decimal point bits (high for on), and the four seven-segment character bits. The fifth and final byte is a null byte used to complete the shift in the LCD driver's shift register. The background task formats the first four bytes to be transferred according to the characters to be displayed. The interrupt routine isr-- hand adds the start bit and outputs the null byte.
To permit the convenient timing of events that take much longer than the overflow times of the programmable timers inherent in the MC68HC11, the isr-- timer interrupt service routine was written. The routine, as shown in the flowchart of FIG. 10, reschedules itself to run every 0.1 s with output timer TOC5 (step 1000). The routine increments a 16-bit programmable timer (rtc-- counter) every time it runs (step 1006), i.e., every 0.1 s. Eight compare values (time [0]-time[7]) analogous in operation to the built-in programmable timer and the output compare registers, are available to time eight different events from 0.1 s to 6553.6 s in duration.
To activate a timing sequence, one of the routines sets the timer active bit for the appropriate time value to be compared and sets the time value to the appropriate compare value. If, for example, a two-second event is to be timed using the time[7] compare value, the routine starting the timing sets the timer active bit for timer 7 and loads the timeout time into time[7] by adding the offset time to the current time given by the contents of the timer rtc-- counter. In this example, time[7] is set to value of rtc-- counter plus 20. The value of 20 is used because two seconds is 20 tenths of a second. Every time the isr-- timer runs, every 0.1 s, the rtc-- counter is incremented by one (step 1006). If the timer active bit for time[7] is set (step 1008), isr-- timer compares the value in time[7] with the value in rtc-- counter (step 1010). When the values are equal, the isr-- timer routine clears the active bit (step 1014) and sets the timeout bit (step 1012), which can be used by any routine relying on the timeout.
As previously mentioned, eight timers are programmed in accordance With the preferred embodiment. The assignments of the timers are as follows:
time[O]: set/display timer #1
time[1]: set/display timer #2
time[2]: TEST/RESET button timer (used to determine whether the button is depressed for the overload class time)
time[3]: lamp test timer (set for two seconds to time the duration of the lamp test)
time[4]: start/stop fault timer (set for one second to wait before checking the current after the motor is started or stopped); incomplete sequence timer (set for one second after the transition output command is given in reduced-voltage starter applications to make sure the seal-in contact closure indicating a successful transition is made)
time [5]: transition timer for reduced-voltage applications (set after a start command for the time the transition is to be made)
time [6]: motor spin down timer (set to 60 s, the minimum time that must elapse after a motor is stopped before it may be restarted)
time[7]: unassigned
The motor elapsed running time is also incremented by isr-- timer. As long as the motor is energized (step 1002), the run time is incremented every 0.1 s (step 1004). The elapsed run time can be displayed on device 119 through request function F16 of Table 1. Data messages transmitted over the SCI to an external communications device 125 are scheduled by isr-- timer. Each time the routine runs, it sets the calling bit MESSAGE (step 1018), which bids the background task to format another data message for transmission. Finally, the long-term timer routine writes the byte $55, followed by $AA, to the MC68HC11's watchdog timer register COPRST to prevent it from timing out and generating a watchdog timeout interrupt (step 1016). The watchdog is initialized to time out in 262 ms if not reset as described.
The shutdown routine, shown in the flowchart of FIG. 11, runs in the event of any of three interrupt sources: (a) watchdog timeout, (b) clock failure; and (c) illegal opcode trap. Upon the occurrence of any of these events, program execution is vectored to the shutdown routine isr-- shutdown, which sets the CPU FAULT bit (step 1100) to turn on the CPU FAULT LED and the FAULT flag bit (step 1102) to bid the background task to stop the motor.
The shutdown routine initiates an orderly shutdown after a CPU malfunction. A watchdog timeout occurs if the isr-- timer routine does not reset the watchdog within 262 ms, as it should under normal operating conditions. An illegal opcode trap occurs if program execution gets lost somehow. A clock failure occurs if the crystal clock frequency drops too low. All of these events are unusual and generally indicate a hardware failure in microcomputer 123 or associated circuitry.
Whenever the control voltage drops below about 9V, the powerfail/reset circuit drives the IRQ pin on microcomputer 123 low, the falling edge generating an interrupt. The IRQ interrupt is serviced by vectoring execution to isr-- powerfail, whose flowchart is shown in FIG. 12A. When the powerfail flag bit is set (step 1200), the routine initiates the procedure of saving certain variables in EEPROM in case a loss of power actually ensues by first initializing RAM and EEPROM pointers (step 1202) to the first variable to be saved. The RAM and EEPROM save areas are equal-sized blocks of memory with the variables saved in the same order in each. After initializing the pointers, the routine erases the row (16 bytes) of EEPROM (step 1214) containing the block of variables and schedules, interrupt routine isr-- eesave (step 1206), using output compare timer TOC4 to execute 10 ms later. Finally, isr-- powerfail sets the PWRFAIL (step 1208) flag bit, indicating to other routines that a loss of power is imminent.
The first time it executes after being scheduled by the powerfail routine, isr-- eesave (FIG. 12B) turns off the EEPROM ERASE VOLTAGE AND LATCH (steps 1210 and 1212), copies the byte in RAM pointed to by the RAM pointer into the corresponding EEPROM location pointed to by the EEPROM pointer. Because the EEPROM programming procedure takes 10ms to program each byte, isr-- eesave reschedules itself with TOC4 to run again in 10 ms (step 1220). Each time a byte is programmed from RAM into EEPROM (step 1218), the pointers are incremented so that they point to the next byte to be saved (step 1216). After the last byte is saved (step 1214), PORT A bit 0, which is connected directly to the IRQ pin, is read. If the logic level is still low, indicating that the power supply voltage is still below 9V (step 1224), isr-- eesave sets the CPU FAULT bit (step 1226) and the FAULT flag bit (step 1228) to bid the background fault logic. If the voltage has recovered at the completion of the updating of the EEPROM, the powerfail flag bit is cleared (step 1230) and program execution continues normally. In either case, once the last byte to be saved is programmed into the EEPROM, isr-- eesave does not reschedule itself to run.
An image of the motor protection setpoints in RAM is stored in EEPROM. All computations made with the setpoints use the values in RAM. All changes are made to the values in RAM. A special interrupt routine isr-- eeupdate, shown in the flowchart of FIG. 13, running independently from the other routines, updates the setpoint image in EEPROM. The routine runs every 16 ms as bid by the realtime clock interrupt and alternates (step 1302) between comparing RAM and EEPROM (step 1304), and programming data from RAM to EEPROM (step 1310). Only in the event of a powerfail condition (step 1300) does the routine dismiss itself from performing operations, deferring instead to the isr-- eesave routine. Otherwise, isr-- eeupdate compares a setpoint value in RAM with its image in EEPROM (step 1304). If the values are identical, the routine increments pointers (step 1316) to the setpoint to be checked the next time the routine runs. If the values differ, the routine erases the byte in EEPROM (step 1306) and, before exiting, sets the PGM-CYC flagbit (step 1308). The next time the routine executes, 16 ms later, it checks the PGM-CYC bit and programs the setpoint byte in RAM into EEPROM (step 1310). The pointers are incremented (step 1312) and the PGM-CYC flag bit cleared (step 1314) before the routine ends. In this way the setpoint image in EEPROM is kept up-to-date.
Serial communication between microcomputer 123 and external communications device 125 is controlled by the SCI interrupt routine isr-- sci. The routine, shown in the flowchart in FIG. 14, handles both incoming and outgoing transmissions. An interrupt is generated, vectoring execution to isr-- sci, under the following conditions: transmit data register empty (step 1422), receive data register full (swtep 1408), or if the receiver line is idle (step 1409). The SCI routine determines which source caused the interrupt and responds accordingly. The routine first reads and saves the status of the SCI status register SCSR (step 1400), which contains the source of the interrupt, and the contents of the SCI data register SCDR (step 1402), which contains the most recent byte received.
After saving the status and the data, isr-- sci checks to see if the interrupt source is the receiver (step 1404). Sources of receiver interrupts are receive data register full, indicating a byte has been received, and receiver idle, a logic high on the receive line for at least ten bit times. If a byte has been received, isr-- sci processes the byte to see if it forms part of a valid message (step 1416). If so, the byte is combined with other consecutively received bytes to form a message (step 1418). When an error (step 1406) or an invalid message byte is received, the error flag bit is set (step 1419). When an idle line (step 1409) causes the interrupt, which occurs at the completion of a received message, the previously received message bytes are processed. If the message is a valid message (step 1410), a flag bit corresponding to the received message is set (step 1412), indicating to the message processing task in the background which message to process. Subsequently, the receive message buffers are cleared (step 1414).
If the source of the interrupt is the transmitter, indicating that the transmit data register is empty and ready for another byte to be transmitted (step 1420), isr-- sci writes the next byte to the transmit data register. In sending out a message, the SCI routine formats the message selected by the message processing task. After determining the byte to be transmitted next, isr-- sci writes it to the data register SCDR from which the SCI automatically transmits it (step 1424). Upon completion of the message transmission (step 1426), the transmit line goes to the idle state and the message queued flag bit is cleared (step 1428). When the transmit message is not queued, a disable transmit data register empty interrupt occurs (step 1430). The SCI baud rate for both transmission and reception is set in the initialization task.
Although shown connected as an across-the-line starter in FIG. 1, the motor controller of the preferred embodiment can be connected and programmed for many starter applications, including across-the-line reversing, two-speed, and reduced-voltage. The only differences from one starter application to another are in the assignment and labeling of local and remote inputs and status indicators, the number and connection of remote contacts, and the program code implementing the Boolean logic equations. Some inputs and status indicators are common to such a majority of applications that their functions are fixed. Table 2 illustrates the input and the output assignments for four different starter applications:
A. Local 3-wire, remote 2-wire, across-the-line.
B. Local/remote 3-wire, across-the-line reversing.
C. Local 2-wire, two-speed.
D. Remote 3-wire, reduced voltage.
Device references are to FIG. 3.
TABLE 2__________________________________________________________________________ APPLICATIONDEVICE SYMBOL A B C D__________________________________________________________________________LOCAL INPUTPB1 STOP STOP OFFPB2 START FWD LOWPB3 REV HIGHPB4 HANDPB5 OFFPB6 AUTOPB7 TEST/RESET TEST/RESET TEST/RESET TEST/RESETREMOTE INPUTAC1 START CONTACT STOP PB LOW CONTACT STOP PBAC2 FWD PB HIGH CONTACT START PBAC3 REV PB EXIT TRIP CONTACTAC4 RUN SEAL-IN CONTACTCOIL DRIVEROUT1 START FWD LOW STARTOUT2 REV HIGH RUNOUT3LEDLED1 CPU FAULT CPU FAULT CPU FAULT CPU FAULTLED2 EXT TRIP EXT TRIP EXT TRIP EXT TRIPLED3 PHASE PHASE PHASE PHASE UNBALANCE UNBALANCE UNBALANCE UNBALANCELED4 OVERLOAD OVERLOAD OVERLOAD OVERLOAD TRIP TRIP TRIP TRIPLED5 INCOMPLETE INCOMPLETE INCOMPLETE INCOMPLETE SEQUENCE SEQUENCE SEQUENCE SEQUENCELED6 IMPENDING IMPENDING IMPENDING IMPENDING TRIP TRIP TRIP TRIPLED7 GENERAL GENERAL GENERAL GENERAL FAULT FAULT FAULT FAULTLED8 AUTO AUTOLED9 OFFLED10 HAND HAND HANDLED11 READY READY READY READYLED12 REV HIGHLED13 RUN FWD LOW RUNLED14 STOPPED STOPPED STOPPED STOPPED__________________________________________________________________________
Two of the inputs and nine of the outputs listed in Table 2 are dedicated to the assigned functions and may not be reassigned. The dedicated inputs are PB1, which is always the STOP or OFF button, and PB7, which is always the TEST/RESET button. The dedicated outputs are the following LEDs:
______________________________________1. LED1 - CPU FAULT (indicates a processor fault)2. LED2 - EXTERNAL TRIP (indicates an external fault signal sent from a remote device over one of the AC inputs)3. LED3 - PHASE UNBALANCE (indicates a load current imbalance of over 40% or, when flashing, of between 20% and 40%)4. LED4 - OVERLOAD TRIP (indicates that the motor was tripped off because of an overload condition)5. LED5 - INCOMPLETE SEQUENCE TRIP (indicates that the motor was tripped off because of an incomplete starting sequence)6. LED6 - IMPENDING TRIP (flashes to indicate that the load current is between 100% and 110% of the overload current setting; stays on to indicate the load current is greater than 110% of the setting)7. LED7 - GENERAL FAULT (indicates redundantly a CPU FAULT, an EXTERNAL TRIP, an OVERLOAD TRIP, or an INCOMPLETE SEQUENCE TRIP)8. LED11 - READY (indicates the presence of control power)9. LED14 - STOPPED (indicates the motor is not energized)______________________________________
Of the LED outputs, only LED2 (EXTERNAL TRIP) and LED14 (STOPPED) are controlled by the solution of Boolean logic equations. The states of the other dedicated LEDs are determined by various conditions not related to the selected starter application. The state of each of the undedicated output devices (the three coil drivers and LED8-13) and dedicated LEDs LED2 and LED14 is determined by the solution of a Boolean logic equation whose terms are other inputs and outputs. Certain timing functions, such as the two externally settable timers and the transition and incomplete sequence timers for reduced-voltage starters, can be included in the logic equations. The program code implementing the logic equations for the selected application is stored in the microcomputer's EEPROM, tailoring the control to the selected application. The sets of logic equations for the starter assignments of Table 3 are part of an expandable library of logic equations representing many applications.
Although the various motor starter applications have been described herein as being represented by Boolean logic equations, it should be recognized that the use of other representations, such as ladder diagrams, are contemplated. In fact, the Boolean equations in the library are usually derived from the ladder diagrams of the various applications. If an application changes, the corresponding logic equations can be transmitted to the microcomputer from external communications device 125. No internal wiring changes are required. Of course, any relabeling of input nomenclature or reconnection of remote contactors required by the new application must be done. Each set of logic equations in the library has a unique control circuit number for purposes of identification. The number can be displayed on the set/display device 119 with function F21 in Table 1.
The two externally settable timers may be assigned specific functions for a given application. Two examples are an on-delay for the staggered starting of a series of motors and a delay to prevent switching from forward to reverse, and vice versa, without giving the motor a chance to slow. Because the functions of the timers are programmed as part of the code implementing the logic equations, the functions may change with the application. The timers are set with the set/display device's timer functions, F7 and F25 in Table 1.
Because many of the dedicated functions, such as those associated with the overload relay, can be disabled, the control is adaptable through the logic equations to non-motor applications, such as slide-valves. To handle applications requiring more inputs and outputs than shown in the circuit diagram of FIG. 3, additional output latches and drivers and input buffers, along with the necessary supporting circuitry and interconnection terminals, can be added.
In reduced-voltage starters, a motor is started by connecting the motor terminals through a contractor to a voltage less than the line voltage. As the motor reaches operating speed, another contractor is closed, connecting the motor terminals to full line voltage for running. Typically, the transition from reduced to full voltage is controlled by a timer that starts to time when the start command is given. Because plant electricians set the timer through trial and error, variations in settings are often due more to variations in electricians than to variations in motor characteristics. The availability of a measure of the load current makes possible a smooth, intelligent transition based on the motor's operating status, instead of on guesswork.
The transition from starting to running is best made when the starting current drops to the full-load current value. The logic equations for reduced-voltage starters, in conjunction with code in the A-D conversion routine (isr-- ad), perform intelligent reduced-voltage starting. When a start command is given, the logic equation code starts one of the long-term timers, setting it to time out in 150% of the locked-rotor time. (Locked-rotor times for motors of various sizes are stored in a table in ROM.) Meanwhile, the A-D routine, which is continuously computing the load current, disables the timer and sets the timeout flag if the current drops to the full-load current setpoint value, asset, for example, by function F2 (see Table 1) of the set/display device 119. The logic equation code then detects the timeout flag and initiates the transition. If, however, the current does not drop to the full-load current value, the timer times out in the preset time of 150% of the locked-rotor time, at which time the logic equation code will initiate the transition. Once the transition command is given, the logic equation code starts the one-second incomplete sequence timer and, if the seal-in contact closure is not detected before the timer times out, sets the IS flag bit to illuminate the INCOMPLETE SEQUENCE LED and stop the motor. In this way, a smooth transition is achieved.
In addition to the motor control functions discussed above, the motor control unit is configured to provide overload current protection, short circuit protection, and ground fault protection based upon various motor protection calculations (step 510) suitable to protect motor 101 from these conditions. These protective functions are provided by the motor control unit hardware (discussed above), operating in conjunction with the operating program (discussed above), and the motor protection routines (discussed below).
FIG. 20 generally illustrates a circuit arrangement for a three phase power system including an AC power source 124 including system circuit breaker 2000, a plurality of branch circuit breakers 2002, the motor controller unit, motor 101, contactors 103, and a plurality of other electrical devices 2004. The circuit breaker 2000 protects all three phases (IA, IB, IC) of the main system wiring extending from circuit breaker 2000 to branch circuit breakers 2002, 2006. Circuit breaker 2000 performs this function by providing circuit interruption for all three phases IA, IB, and IC when a predetermined level overload, short circuit or ground fault current occurs.
Since circuit breaker 2000 protects the system circuitry, circuit breaker 2000 will trip for a condition such as ground fault, but it may be very difficult to determine which device caused the ground fault without checking all branch circuit breakers 2002, 2006. Additionally, all of the devices on the respective circuit will be inoperative until the ground fault is corrected.
Branch circuit breakers 2002 protects the branch circuits 2008 from short circuit and overload currents, whereas circuit breaker 2006 only protects circuit 2010 from short circuit currents. For purposes of protecting circuit 2010 from short circuit currents, the National Electric Code (NEC) requires that circuit breaker 2006, or a circuit breaker/contactor arrangement, to provide instantaneous circuit interruption at current levels no higher that 13 times the full load current (Iflc) of motor 101.
The motor control unit and contactors 103 of the preferred embodiment are arranged to protect circuit 2010 and motor 101 from overload, short circuit and ground fault currents as discussed below. Overload and short circuit protection are provided by the combination of the motor model simulation routine (FIGS. 18A-18E), the intermediate motor current protection routine and a short circuit protection device such as a circuit breaker or fuse. Ground fault protection is provided by the ground fault interrupt routine (FIG. 22). (The details of each of these three routines are discussed in detail below.)
As discussed above, the routine isr-- ad (FIG. 7) runs every 5.8 ms so that all of the four channels (0-3) are sampled every 5.8 ms. Accordingly, isr-ad updates the RMS current values (IA, IB, IC) and the RMS ground fault current (IGFI) value based upon 60 samples of each channel every 350 ms (60 samples * 5.8 ms per 4 channel samples).
The preferred embodiment of the motor model simulation routine (illustrated in the flowcharts of FIGS. 18A-18E) provides motor protection between 0 and 10 times Iflc, but this range may be varied depending upon the specific application. The basis of the simulation routine is a motor model which can be digitally simulated and defined in the program which is executed by microprocessor 123 of the motor controller. Based only upon time and digital representations of the RMS values of the load currents in the phases of motor 123, the digital simulation of the motor permits microprocessor 123 to provide output such that the motor controller will control contacts 103 of contactor 130 in accordance with the status of the motor.
The purpose of the motor model is to provide an estimation of the following values:
the temperature of a motor's windings;
a change in the temperature of the motor's windings with respect to time;
the temperature of the motor's housing; and
a change in the temperature of the motor's housing with respect to time.
These values are based upon the actual motor current and changes in the actual motor current with respect to time. The values are then compared with acceptable ranges for the values so that microprocessor 123 can initiate an appropriate action if a particular value falls outside of its acceptable range.
The motor model is based upon a thermal model analogous to the two-capacitor, four-resistor circuit illustrated in FIG. 15. The values of the two capacitors Cw and Ch are analogous to the thermal capacities of the motor windings and the motor housing; the values of the four resistors Rw, Rwc, Rh and Rhc are analogous to the thermal resistance between the windings and the housing and between the housing and the environment; the voltages Tw and Th across the capacitors are analogous to the winding and housing temperatures; and the current P applied to the circuit is analogous to the rate of energy delivered to the motor.
More specifically, Rw is analogous to the winding thermal resistance during a rise in winding temperature, Rh is analogous to the housing thermal resistance during a rise in housing temperature, Rwc is analogous to the thermal resistance of the winding during a decline in winding temperature, and Rhc is analogous to the thermal resistance of the housing during a decline in housing temperature. The values of the various elements depend on empirical motor data and motor nameplate data. Unlike the method of protection employed by overload relays, the motor model is general enough to protect many different sizes and classes of motors, while being flexible enough to provide customized protection for each motor.
The input P to the model is a function of the largest of the RMS current values calculated for the motor phases. P is related to the largest of the RMS current values (IA, IB, IC) and the rated full load current of the motor (flc). For Iratios (I/Iflc) between 0 and 1.1, P is equal to Iratio; for Iratios between 1.1 and 1.6, P is based upon Table 3 below; and for Iratios above 1.6 P is equal to Iratio2.
TABLE 3__________________________________________________________________________NEMA MOTOR SIZE HP Iflc (AMPS) SIZE Iint (AMPS) Itrp (AMPS) 10* Iflc Itrp/Iflc Inrush__________________________________________________________________________ (AMPS)1 0.25 0.48 1A 340 300 4.8 625.00 6.54 0.33 0.583 1A 340 300 5.8 517.24 7.90 0.5 1.16 1A 340 300 11.6 258.62 15.80 0.75 1.4 1B 340 300 14.4 208.33 20.50 1 1.5 1B 340 300 15 200.00 21.90 1.5 2.0 1B 340 300 20 150.00 24.50 2 2.8 1B 340 300 28 107.14 36.20 3 3.6 1B 340 300 36 83.33 51.90 5 6.0 1C 340 300 60 50.00 73.20 7.5 8.9 1C 340 300 89 33.71 119.80 10 11.9 1C 340 300 119 25.21 146.702 15 17.5 2A 550 495 175 28.29 219.70 20 22.7 2A 550 495 227 21.81 256.50 25 28.2 2A 550 495 282 17.55 335.903 30 33.5 3 800 712 335 21.25 426.30 40 44.4 3 800 712 444 16.04 607.50 50 55.7 3 1800 1600 557 28.73 698.504 60 65.0 4 1800 1600 650 24.62 940.60 75 81.2 4 1800 1600 812 19.70 1078 100 112 4 4000 3600 1120 32.14 15645 125 138 5 4000 3600 1380 26.09 1861 150 165 5 4000 3600 1650 21.82 2109 200 217 5 4000 3600 2170 16.59 2979 350 269 6 5400 4750 2690 17.66 3493 300 328 6 5400 4750 3280 14.480 5082__________________________________________________________________________
By way of example, 80° C. has been recognized as an appropriate and safe operating temperature (Tw) for almost all motor windings having class B insulation and 50° C. has been chosen as a reference operating temperature for motor housing (Th). These temperature are relative to ambient temperature. For these steady state temperatures Tw, Th, it can be seen from the model that Rw is 30° C./W and Rh is 50° C./W.
The transient solution of the motor model circuit for heating involves the solution of the following equations:
(T.sub.W(t) /T.sub.0 =(T.sub.W0 /T.sub.0)+((P/P.sub.0)-(P1/P.sub.0))*dt/(C.sub.W /C.sub.0) (1)
(P.sub.1(t) /P.sub.0 =((T.sub.W /T.sub.0)-(T.sub.h /T.sub.0))/R.sub.W /R.sub.0) (2)
(T.sub.h(t) /T.sub.0)=(.sub.h0 /T.sub.0)+((P.sub.1 /P.sub.0)-(P2/P.sub.0)*dt/C.sub.h /C.sub.0 (3)
(P.sub.2(t) P.sub.0)=(T.sub.h /T.sub.0)/(R.sub.h /R.sub.0) (4)
For the presently preferred embodiment of the motor model, the value for Cw was derived from empirical motor data for 2, 4, 6 and 8 pole motors from 0.3 amps to 540 amps. From an analysis of the motor data the relationship illustrated in FIG. 16 was derived. From FIG. 16 it can be seen that the product of the square of the starting current (Ist2) which is substantially the same as the square of the locked rotor current (Ilr2) and the time it takes for a motor winding temperature to rise 140° C. from ambient temperature with its rotor locked (Tlr) are related to the motor full load current Ifl. Class B insulation for motor windings is rated to withstand 180° C. above an ambient temperature of 40° C. The temperature rise of 140° C. was chosen as a basis for the Tlr time since it offers a 25% safety factor with respect to the rated insulation temperature of 185° C.
For purposes of determining Tlr, it is assumed that the starting current (Ist) for an idle motor is six (6) times its rated full load current. For example, for a motor with a rated full load current (Iflc) of 10 amps, the starting current (Ist) for the idle motor would be 60 amps. By referencing FIG. 16 using Iflc of 10 amps and Ilr of 60 amps (Ilr=Ist), Tlr can be determined. From FIG. 16 Ilr2 * Tlr is about 9×104 amp seconds for a cold motor. Based upon this, Tlr is calculated as 25 seconds ((9×104 amp-seconds2)/602 seconds2).
The 25 second Tlr time corresponds to the time it takes for the winding temperatures of the motors tested, and similar motors, to rise 140° C. with a locked rotor. For purposes of a safety factor, the 25 second time was reduced by 20% to 20 seconds.
Based upon the 20 second time constant and the observation that the starting current for a motor (Ist) is approximately six times the value of the full load current Ifl, the value of Cw for the model is calculated as 5.14 w sec/° C. (Cw=(Iratio)2 ×Tlr/temperature rise; for Iratio=6, Tlr=20, and temperature rise=140°, Cw=36×20/140=5.14 w sec./°C.).
The value for Ch is derived from FIG. 17. FIG. 17 illustrates the observed time constants for motor housings (tc). As illustrated, the time constants for the motor housings are related to the full load current of the motor. This relationship is approximated by the following function:
tc=7+53 (1-e.sup.-.01Ifl)
From this relationship the value of Ch can be obtained by dividing tc by Rh, to obtain the following relationship:
Ch=[1/Rh]*[7+53(1-e.sup.-.01Ifl)]
The values of Rhc and Rwc depend on the actual observed time constant of a motor. In the present preferred embodiment of the motor model, Rhc is estimated as 3 times the value of Rh, and Rwc is estimated as 3 times the value of Rw. These estimates are based upon actual data.
Upon establishing the parameters for the motor model, the motor model can be implemented in the form of a program which is executable by microprocessor 123 of the motor controller unit. The implementation of the motor model is described below in reference to FIGS. 18A-18E.
In FIG. 18A the step of initializing (step 502) normalizing values and parameters is shown since the motor model operation is based in part on these values. These values allow the equations used for the motor model to be manipulated in a unit-less form. The time (t), the winding temperature (Tw), the housing temperature (Th), and the values of P1 and P2 (initial values used to solve the model equations) are set to 0.
Twrestart is set at 80T0. Twrestart is compared to the value of the winding temperature (Tw) calculated based on the motor model (step 1800). When Twmax is exceeded by Tw, the motor controller will not allow the motor to be restarted as long as Tw is greater than Twstart unless an override command is provided.
Thtrip is set at 60 T0. Thtrip is compared to the value of housing temperature (Th) calculated. When Th is greater than Thtrip, the motor controller will stop the motor.
The values of Rw, Th, Cw and Ch are discussed above and are set as shown.
Thflc and Twflc are set at 50 T0 and 80 T0 respectively. These values can be used to adjust the motor full load current (Iflc) from the motor's name plate data. This adjustment is made since the full load current Iflc on the data plate of a motor may not be the same as the actual Iflc of the motor. To make the adjustment, the program defining the motor model can adjust Iflc such that the temperature of the housing Th equals Thflc and the temperature of the winding Tw equals Twflc when the motor is running at steady state under normal conditions.
In step 1804, the winding temperature (Tw) is compared to Twstart. If Tw is less than Twstart, the warning that the maximum winding temperature (Twmax) has been reached is cleared (step 1805). If Tw is greater than Twstart the warning remains and prevents the motor from starting.
In step 1806, the temperature limit of the winding for tripping (Twtrip) is redefined. If Twtrip, based upon the motor class, is greater than Twmax, Twtrip is set to Twmax (step 1807) to provide greater protection for the motor. If Twtrip, based upon the motor class is less than Twmax, Twtrip is not changed.
If the motor is not stopped (step 1808), the motor current is measured (steps 1809 and 1811) and the current unbalance for the motor is determined if the motor is multi-phase (step 1810). If the current unbalance is greater than 0.4 (step 1812), P is increased to account for the current unbalance (step 1813).
To determine current unbalance, the maximum phase current is determined (step 1850), the difference between the maximum phase current (IMAX) and the average phase current (IAVE) is calculated (step 1852), and the current unbalance is calculated by dividing the difference by the maximum phase current (step 1854).
In step 1814, the ratio (Iratio) of the motor load current (Imax) and the full load current Iflc of the motor is calculated. Subsequent to calculating Iratio, the intermediate motor current protection routine (FIG. 21) may be incorporated. Where this routine is incorporated, steps 2102, 2104 and 2106 are eliminated.
In step 1816 the status of the motor is again checked to determine whether or not the motor is running. If the motor is not running, the motor run timer is cleared (step 1856). If the motor is running, a motor run timer is set and started (step 1817) if the timer is not already running (step 1819). In step 1818, the running time for the motor is checked, and if the running time is less than 5 times the trip class of the motor, the jam protection and loss of load protection logic of FIG. 18D is bypassed. If the running time is greater than 5 times the trip class, the jam protection and loss of load protection loops are entered.
Jam protection occurs when Iratio is above 1.5 and less than 10 (step 1821), otherwise the jam warning is cleared (step 1825). When Iratio is greater than 1.5 and the jam warning is not set (step 1858), the warning for jam timers are set (steps 1860 and 1862). When the warning for loss of load flag and timer are set (step 1866), I equals Iratio is set for the nth current loop (step 1868). If the answer at step is no, the warning for loss of load timer is started (step 1870). The jam protection operates so that when the motor has been operating at Iratio 1.5 for more than 0.5 seconds, the motor stops (step 1823). The loss of load protection is set up so that the motor is stopped if the change for Iratio is more than 0.2 for a 0.5 second time period (steps 1824 and 1827).
If either a loss of load or jam condition exists, the motor is stopped, the motor run timer is cleared, and the warning for loss of load timer is cleared (step 1829). If neither a loss of load nor jam condition exists, step 1829 is skipped.
Step 1820 is the basis of the motor model, since it is at this stage that the equations defining the motor model are solved to determine Tw and Th. At step 1822, Tw and Th are compared to the limits for the winding temperature and the housing temperature (Twtrip and Thtrip). If either of the limits are exceeded the motor is stopped (step 1824) after Tw is checked against the maximum winding temperature Twmax (step 1826) and the warning that Twmax was reached is set if appropriate (step 1828).
When data is requested (step 1830), a data block can be set up (step 1832) so that when the motor controller is accessed with a display device, data such as the following can be displayed:
average motor current;
motor current at tripping;
time before the motor can be restarted;
total elapsed motor running time;
total number of motor starts; and
total number of overload trips.
From step 1822 the monitoring process is restarting back to step 1806.
Another embodiment of the motor model is based upon a thermal model analogous to the two-capacitor, four resistor electric circuit illustrated in FIG. 19. For this model, the values used for Tw, Th, Cw, Ch, Rw, Rwc, Rh and Rhc are the same as in the model of the preferred embodiment. The difference in the models is found tin the calculation of P and equations used to solve the model.
In this embodiment of the model, for Iratio between 0 and 1.05 P equals Iratio and for Iratio greater than 1.05 P equals (Iratio)2. To solve the model the following equations are used in block 10 to determine Tw and Th: ##EQU1## The constants k1 and k2 are calculated such that the motor model can be adjusted to more accurately model a given motor.
Where the average of the ratio (Iratio) of the maximum phase current (Imax) and the rated full load current (Iflc) of the motor is greater than 10 for 60 samples, the overload programming is set up to immediately stop the motor. At step 1824 a running total of Iratios for 60 samples of the motor currents (IA, IB, IC) is maintained. When this total is complete for 60 samples the total is divided by 60 to obtain the average Iration. The average Iratio is compared to 10, and if greater 10, the program jumps to step 1826 where the command to stop the motor is issued.
The preferred embodiment of the intermediate motor current protection routine provides motor protection between 7 times Iflc and the instantaneous trip setting of circuit breaker 2006 which may be between 11 and over 500 times Iflc. The range of protection provided by the protection routine will depend upon the specific application as further discussed below. (As discussed above, this routine can be modified and incorporated into the motor model simulation routine.).
The first step of the protection routine is to read the full load current (IFLC) for motor 101, step 2104. In the next step, step 2104, each of the RMS values representative of the three phase current's (IA,IB, IC) are determined, and the greatest of these values is set as IMAX. A ratio (IRATIO) is calculated as the ratio of IMAX and IFLC. IRATIO is then compared with the value 7, or another limit value depending upon the specific motor protection application. If IRATIO is less than the limit value, then the protection routine terminates and returns. If IRATIO is greater than the limit value, then contacts 103 are opened and the overload/instantaneous trip LED (LED4) is turned on, and the protection routine returns.
As discussed above, sampling of IA, IB and IC takes place every 5.85 ms and thus the detection of Iratios over 10 will take about 350 ms (60×5.85 ms), since 60 samples of IA, IB, and IC are used to determine the RMS values of IA, IB, and IC. In other words, detection would take about 21 cycles of 60 Hz line current. IRATIO is compared against a second limit value ILIMIT. Where IRATIO is greater than ILIMIT, circuit breaker 2006 is opened. Where IRATIO is greater than ILIMIT, the circuit breaker 2006 will open before the motor control unit has a chance to open contacts 103.
Typically, circuit breaker 2006 will provide an instantaneous (magnetic) trip and open within 8.3 ms (2/60 Hz) or 1/2 of a cycle, whereas, the motor control unit will take approximately 350 microseconds to open contacts 103. Accordingly, a motor control unit will open contacts 103 long after circuit breaker 2006 has opened the circuit leading to motor 101. An advantage of providing intermediate motor current protection using the motor control unit for protection between IRATIOS from 10 to 500, instead of circuit breaker 2006, is to avoid spurious or nuisance tripping of circuit breaker 2006 during motor starting.
For high efficiency motors, the starting currents encountered upon motor starting within the first 8.3 ms of starting (1/2 cycle) can instantaneously go above 10 times IFLC of a motor and may reach 17 times IFLC. Accordingly, if circuit breaker 2006 is used for motor protection between IRATIOS of 7 and 13, as required by the National Electrical Code, the situation will occur where circuit breaker 2006 will open before a high efficiency motor has a chance to start and the high starting currents have a chance to subside.
In operation, the instantaneous trip protection provided by the intermediate motor current protection routine eliminates the problem of nuisance tripping which frequently occurs upon the starting of high efficiency motors. In addition, this protection routine insures that a gap in tripping potential does not exist as in the situation where the operation of the motor contactor only protects to 10 times IFLC and the instantaneous trip limit of the circuit breaker protecting the motor has been set above 10 times IFLC to avoid nuisance tripping. This situation produces a gap in tripping potential between 10 times IFLC and the instantaneous trip limit of the circuit breaker.
When used with the motor controller, and a circuit breaker with a fixed instantaneous (magnetic) trip limit above that for nuisance tripping, the protection routine allows avoidance of nuisance tripping without producing a gap in tripping potential.
By way of example only, Table 4 below illustrates a number exemplary ranges over which the protection routine could be modified to protect. Table 4 is directed to 460 volt applications with energy efficient motors. (HP=motor horsepower; Iflc=motor full load current; TYPE=Siemens contactor type; Iint=rated interrupting current of the contactor; and Itrp=instantaneous (magnetic) trip setting of the circuit breaker.)
TABLE 4__________________________________________________________________________NEMA MOTOR SIZE HP Iflc (AMPS) SIZE Iint (AMPS) Itrp (AMPS) 10* Iflc Itrp/Iflc__________________________________________________________________________1 0.25 0.48 1A 280 255 4.8 531.25 0.33 0.583 1A 280 255 5.8 439.66 0.5 1 1A 280 255 10 255.00 0.75 1.4 1B 280 255 14 182.14 1 1.8 1B 280 255 18 141.67 1.5 2.6 1B 280 255 26 98.08 2 3.4 1B 280 255 34 75.00 3 4.8 1B 280 255 48 53.13 5 7.6 1C 280 255 76 33.55 7.5 11 1C 280 255 110 23.18 10 14 1C 280 255 140 18.212 15 21 2A 500 440 210 20.95 20 27 2A 500 440 270 16.30 25 34 2A 500 440 340 12.943 30 40 3 800 730 400 18.25 40 52 3 800 730 520 14.04 50 65 3 800 730 650 11.234 60 77 4 1700 1530 770 19.87 75 96 4 1700 1530 960 15.94 100 124 4 1700 1530 1240 12.345 125 156 5 4000 3600 1560 23.08 150 180 5 4000 3600 1800 20.00 200 240 5 4000 3600 2400 15.00__________________________________________________________________________
Referring to table 4, for the control of a 30 HP motor having a rated full load current (IFLC) of 40 amps, the motor control unit could be used with a Nema size 3 contactor and a 125 amp circuit breaker having a fixed instantaneous (magnetic) trip limit of 730 amps. A Nema-size 3 contactor has the ability to carry 90 amps of continuous current and the ability to interrupt a maximum of 800 amps. For this arrangement, the maximum current interruption capability of the contactor is 70 amps above that of the instantaneous trip of the circuit breaker. Thus, the circuit breaker will always open before a maximum current interrupting limit (800 amps) is reached for the contactor.
To have IRATIOS greater than 10, one of the phase currents (IA, IB, IC) would be greater than 400 amps (40×10). ILIMIT would be 18.25 (730 amps/40 amps). Accordingly, the motor would be protected from currents ranging between 0 and 400 amps by the motor control unit via the motor model simulation routine, between 400 and 730 amps by the motor control unit via the intermediate motor current protection routine, and above 730 amps, by the instantaneous trip limit of the circuit breaker.
In addition to eliminating gaps in tripping potential, the use of the intermediate motor current protection routine can reduce the number of contactor and circuit breaker combinations required to protect a given range of motor sizes. For example, for NEMA class 1 motors (0.25-10 HP), only 3 contactor sizes (1A, 1B, 1C) and 1 circuit breaker size are required to protect the range of motor sizes in NEMA class 1.
Another problem the intermediate motor protection routine can reduce is that of tripping accuracy. When used with the motor controller, the protection routine typically provides a higher level of tripping accuracy than standard electromechanical trip units. For example, tripping accuracy may be reduced from ±20% to ±5%.
As discussed above, the ground fault protection function of the motor control unit can be enabled and disabled using the function F12, depending upon the particular application of the motor control unit. When enabled, ground fault protection will cause contactor 105 to open contacts 103 in the event of a ground fault; when disabled, display LCD1 will display a notice that a ground fault condition exists, but will not cause contactor 105 to open contacts 103.
One embodiment of the ground fault interrupt routine is illustrated in the flowchart of FIG. 22. The first step of the routine is to increment a counter (COUNT) by one (step 2201A). In step 2202A IGFI is read and used in step 2204A to calculate a running average of the RMS ground fault interrupt current IGFI-AVE. IGFI-AVE is calculated by averaging the current IGFI and the previously calculated IGFI-AVE (step 2204A). When the count is 22 (step 2206A), IGFI-AVE is compared with IGFI-LIMIT, which in the preferred embodiment is 3 milliamps, and COUNT is set to zero (step 2207A).
For IGFI-AVE greater than IGFI-LIMIT (step 2208A), the ground fault interrupt LED (LED 102) is flashed ON and OFF (step 2210A), a ground fault interrupt message is provided at the LCD (step 2210A), and contactor 105 opens contacts 103 (step 2213A) if the ground fault interrupt is enabled (step 2212A). At the end of the routine, a return (step 2216A) is made to the background loop.
During the initialization task (step 502), COUNT, IGFI, IGFI-AVE, and IGFI-LIMIT are set to zero. Referring back to step 2206A, a count of 22 is required before any action is taken by the motor control unit. The purpose of this is to avoid spurious tripping during motor operation if a single IGFI, which is based upon 60 readings of channel 3 of the A/D converter, indicates that there is a ground fault. In the preferred embodiment, it has been determined that the average of 3 IGFI values tends to eliminate spurious tripping. Accordingly, if IGFI is updated every 350 ms (3 IGFI updates in 1050 ms) and the interrupt routine is run about every 50 ms, the interrupt routine must be run at least 22 times (1100 ms) to ensure IGFI is updated at least 3 times for purposes of calculating IGFI-AVE (step 2204A).
Another embodiment of the ground fault detection routine is illustrated in the flow chart of FIG. 22B. The routine runs every 350 ms upon the computation of a new averaged ground fault current value IGFI-AVE by the A/D interrupt routine.
The first step of the ground fault detection routine compares the ground fault current value IGFI-AVE to the pickup current (step 2204B), or ground fault limit value IGFI-LIMIT. In a preferred embodiment, the pickup current is a function of the overload class, but could also be a function of other parameters, such as motor rating and/or contactor size. If IGFI-AVE current exceeds IGFI-LIMIT, execution proceeds to step 2206B where COUNT is compared to 3.
If the count is less than 3, the flashing of LED102 is stopped (step 2222B), COUNT is set to zero (step 2224B), and the ground fault detection routine is exited at RETURN step 2220B. If the count is 3 or greater, indicating that IGFI-AVE exceeded IGFI-LIMIT for at least three consecutive measurement periods, or three times 350 ms (1050 ms), a ground fault condition is determined to exist.
The use of three consecutive ground fault detections is one way of avoiding false detections due to noise. It should be appreciated that values other than three could be used, depending on the noise level and system requirements. Other filtering techniques could also be used effectively.
If IGFI-AVE exceeds the IGFI-LIMIT pickup level, the count is limited to three to prevent the counter from overflowing (step 2210B). Next it is determined whether ground fault protection or warning has been selected through control function F12 (step 2212B). If protection is selected, contactor 105 trips, contacts 103 open and the motor is disconnected from power (step 2214B). The ground fault (LED102) is then illuminated (step 2216B). Other action which could be taken might include the display of a message on the LCD. The routine is then exited at step 2220B. If, on the other hand, ground fault warning is selected, LED102 is set to flash off and on (step 2218B) before the routine is exited. With warning selected, the motor is not disconnected.
If the ground fault condition subsides, i.e., IGFI-AVE is less than IGFI-LIMIT, execution from step 2204B proceeds to step 2222B, which stops the flashing of the ground fault LED (LED102). If the LED was not flashing, step 2222B has no effect. The counter (COUNT) is reset to zero in step 2224B before the routine is exited at step 2220B.
While one embodiment of a motor controller and several modifications thereof have been shown and described in detail herein, various other changes and modifications may be made without departing from the scope of the present invention. For example, the motor controller can be used with a single phase motor coupled to the neutral and power conductors of a power source. Additionally, the motor controller may be used with a two-phase motor. | https://patents.google.com/patent/US5448442?oq=7%2C173%2C247 | CC-MAIN-2018-26 | refinedweb | 23,758 | 50.87 |
I'm using Cypress FX2LP chip(CY7C68013A) on my board to communicate trough USB with Qt using CyAPI library. I Should read 1 KByte data every 100 ms(infinitive) and it should be possible to user to send special commands through buttons during data receiving. So i create another thread other than MainWindow and run it every 100 ms using a timer. My code is something like: Project.pro:
LIBS += -L$$PWD/CyAPI_lib_cpp -lCyAPI
my_thread.cpp:
CCyUSBDevice USBDevice; unsigned char xferBuffer_in[1024]; void my_thread::Receive_new_set_of_Data(){//Runs very 100 ms USBDevice.Open(0); bool is_ok=false; if(USBDevice.IsOpen()){ LONG length=1024; USBDevice.BulkInEndPt->TimeOut=30;// wait 30 ms at max is_ok=USBDevice.BulkInEndPt->XferData((PUCHAR)xferBuffer_in, length , (CCyIsoPktInfo*)0,false); } }
My problem is that when user removes USB between data receiving, it crashes and debugger stop at set time out line. How can i detect USB unplug? Is there any event for USB unplug?
Hello Javad Habibi,
The CyUSB namespace has an event handler for attachment and detachment of USB device. The USBDeviceList.DeviceRemoved is an event handler for USB removal.
Please refer to the source code of Cypress USB Control Center, which can be found in the below path after the installation of CY3684 EZ-USB FX2LP Development Kit (Rev. *B) .
C:\Cypress\USB\CY3684\CY3684_EZ-USB_FX2LP_DVK\1.1\Windows Applications\Application Source files\c_sharp\controlcenter
This has got the implementation of event handling during the attachment and detachment of USB device.
Best regards,
Srinath S | https://community.cypress.com/thread/33197?start=0&tstart=0 | CC-MAIN-2018-39 | refinedweb | 247 | 50.63 |
Having problems with this code, basically once the applet starts up all that is displayed is "The sum is 0.0". The Option panes are not poping up at all.
Java 1.7 / Eclipse.
Also getting a warning @ public class Practice : The serializable class Practice does not declare a static final serialVersionUID field of type long.
If anyone knows what the means that would be super helpful, Any help is much appreciated.
I went ahead and uploaded the applet :
import java.awt.*; import javax.swing.*; public class Practice extends JApplet { // What the Init method is .. is basically being about to put stuff ... in it ? private double sum; public void inti(){ // Init() is short for initialization String fn = JOptionPane.showInputDialog("Enter first Number"); String sn = JOptionPane.showInputDialog("Enter second number"); // Convert the string to double double n1 = Double.parseDouble(fn); double n2 = Double.parseDouble(sn); sum = n1 + n2; } public void paint(Graphics g){ super.paint(g); g.drawString("The sum is "+sum, 25 , 50); } } | http://www.javaprogrammingforums.com/java-applets/17322-simple-applet-troubles.html | CC-MAIN-2015-27 | refinedweb | 163 | 60.11 |
Answered by:
Windows 8.1 Preview GetVersionEx reports 6.2.9200
Can anyone comment on why the GetVersionEx API on Windows 8.1 Preview reports 6.2.9200 instead of 6.3.x?
C:\>getversionex.exe
6.2.9200 N/A Build 9200
systeminfo.exe obtains the version information through WMI: Win32_OperatingSystem and reports the "correct" version:
C:\>systeminfo
Host Name: WIN-QJNHK7TGRV7
OS Name: Microsoft Windows Server 2012 R2 Datacenter Preview
OS Version: 6.3.9431 N/A Build 9431
OS Manufacturer: Microsoft Corporation
getversionex.cpp
#include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { OSVERSIONINFOEX osvi = {0}; osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ::GetVersionEx((OSVERSIONINFO*)&osvi); if(osvi.szCSDVersion[0] == _T('\0')) { _tcscpy_s(osvi.szCSDVersion, L"N/A"); } CString version; version.Format(L"%u.%u.%u %s Build %u", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber, osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF); _tprintf_s(version.GetString()); return 0; }
- Edited by Euclid Tuesday, June 25, 2013 7:06 AM
- Moved by HCK Moderator Friday, June 28, 2013 6:04 PM This is an API question. Not related to HCK.
Question
Answers
All replies
... but the "IsWindows* macros from VersionHelpers." are not defined in VS2012.
Just what I expected - sorry, but I'm tired of the loops we have to jump through just because "compatibility" problems of other people, or that MS thinks that could happen.
Is there any way to detect the presence of such a manifest (that is, if you're lied to), if you're a plugin? Otherwise people will start looking at other ways to detect the "real" version (at least, in our case, just for a LOG file that shows the "real" environment) - we do it by querying the KERNEL32 version, which is a hack that is forced by MS just because they have no way to switch off that intermediate layer.
A new TRUEOSVERSIONINFOEX struct that tells Windows to return the "real" values (different size to the OSVERSIONINFOEX structure) would resolve the issue.
);
If you're a plugin, you must conform to the process environment you live in. If the process believes the world is NT 6.2, it is no other than NT 6.2.
If you need your own environment to see the real world, why don't you use your own process for that purpose?
Imagine it's a plugin that can execute things the application cannot (most of the times, that's what plugins are for). And imagine, the plugin knows it can use a feature under 8.1 (or whatever version) that the application if not built for? Why should the application (created by developers I don't even know) foresee all features my plugin (unknown to the app's creators) would like to use? That makes no sense, it limits the usefulness of plugins (external modules etc).
To make it clearer, assume you have a printing plugin. And the app does not know what the printing plugin could use to do its job. Why should the application foresee the APIs (or other features of "the process environment") it uses to fulfill the job? Imaginge different plugins, some more sophisticated (using newer APIs) and some older ones...
Chuck: There are a few problems with the GetVersionEx API:
1. As it is declared as deprecated we cannot easily use in an application when using the Windows 8.1 SDK. Hacks are required to suppress just this one warning/error and not all others.
2. What guarantee do we have that the correct version is reported for post Windows 8.1 versions? If a new compatibility/application/supportedOS entry is required in the manifest for every new Windows version, we will have the same problem again.
Yes, WMI reports the correct information regardless of the appcompat shims.
What you describe is "By Design". Unless your application has the GUID to indicate compatibility with the current OS, then the OS may provide older information to avoid app compat bugs.
It is not a 'hack' to use #pragma warning(push) #pragma warning(disable:4995) #pragma warning (pop) around code, but you at least know that the API in question is deprecated and you should look to see if (a) you really need to call this API and (b) if there are better alternatives. How about the GetFileVersionInfo on kernel32.dll recommendation from MSDN?
- Proposed as answer by Chuck Walbourn - MSFT Monday, July 08, 2013 8:09 PM
Yes, but Plugins/DLLs etc are not "the app".
They might have different requirements.
Otherwise it sounds as if you're not allowed to modify your car with newer accessories as the ones that existed when the car was designed (no navigation kit for cars older than 10 years!).
No, this is bad design, IMHO.
Hello)
Be calm) All problems solved with simple solution!
If VerifyVersionInfo recommended, so then we will use it and one more numeric method - bisection method.
New api the same. Function name is GetVersionExEx, sources available here -
Implemented in C. Test app available too.
Heh, write in C, let it C)))
Thanks)
- Edited by iContribute Monday, July 08, 2013 6:14 PM addition
VerifyVersionInfo is intended for simple "you must be this high to ride this ride" compatibility tests or to exclude specific versions. It's not a great option if you are just trying to capture a version string for use in logging or diagnostics.
If you read the MSDN link I provided above, getting the File Version info off the KERNEL32.DLL is probably the best way to get just the version for logging. I would NOT guard any feature app or installer behavior based on this.
iContribute's post just recreates the same problem that deprecating GetVersionEx was fixing in the first place. Please don't use this kind of thing...
- Edited by Chuck Walbourn - MSFT Monday, July 08, 2013 8:07 PM note
- Proposed as answer by Chuck Walbourn - MSFT Monday, July 08, 2013 8:09 PM
At least two big projects that I know will start accept some bug requests related to this deprecation.
One of them is Mono Project - alternative .NET implementation.
It's used by Environment.OSVersion property. To be fair an official .NET version does not have this issue and mentioned property returns valid info under Windows 8.1.
So, VerifyVersionInfo and numeric bisection method are better friends here.
Guidelines - good, deprecation without alternative - not. And let's users/developers choose what is better.
And finally... I want super-duper about dialog with valid version numbers.
Chuck, to be fair again.. I don't recreate problem, I fix her. It's custom solution, You want it - You get it.
Oh, and "getting the File Version info off the KERNEL32.DLL" What is it? Joke? Seriously? Only bad words. Embedding manifest, WMI win32 class, system file version - it's all - Kung Fu.
Write, Compile, Copy, Run = Fun.
Thank you very much for your attention!
P.S.: Deprecation it's really bad decision.
P.P.S: Numeric methods rulz!
- Edited by iContribute Monday, July 08, 2013 8:59 PM addition 2
My point is that going the route iContribute recommends will result in a future version of Windows having to lie to VerifyVersionInfo to avoid appcompat problems..
The key question gets back to why you are calling GetVersionInfo(Ex) in the first place... Most use of this function is problematic and probably not needed, so the API has been deprecated.
The MSDN link provides the alternatives.
- Edited by Chuck Walbourn - MSFT Monday, July 08, 2013 11:13 PM link
In that case VerifyVersionInfo,GetFileVersionInfo, VerQueryValue, WMI win32 class... even.NET assembly that can be consumed in code - good candidates to be deprecated... (heh, kernel32.dll will be deprecated too?). Instead simple os api call, we need write a spaghetti code that does the same and even in this case used api maybe will deprecated. Sure.... Yeah... it's right way. Code above uses: simple code, recommended api (ms725492(v=vs.85).aspx "It is preferable to use VerifyVersionInfo rather than calling the GetVersionEx function to perform your own comparisons." and others places on MSDN), same api that in VersionHelpers.h (Who need this header?), precise algo and good old plain C. Oh, no.. it's good... definitely will be deprecated.
So, provided above "alternatives" also will be deprecated if will widely used?Tightening the screws is the right way)
- Edited by iContribute Tuesday, July 09, 2013 4:19 AM addition 3
The right solution is for developers to step back and look at why they are trying to determine the OS version.
For logging and diagnostics, the GetFileVersionInfo solution seems to be the recommended approach given a fallback that can handle 'version information unknown' as a failure case instead of crashing the application. WMI is also a robust way to achieve this.
For install 'you must be this high to ride this ride' checks, that would be best handled with VerifyVersionInfo.
Otherwise, developers should try to eliminate use of GetVersion(Ex) entirely. Often there are other methods for detecting the presence of features that are much more robust. For example, an error return code on a factory method or a failed attempt to QueryInterface. These are the scenarios that deprecating GetVersion(Ex) is explicitly trying to address.. For Someone using the VS IDE to build their projects, it's a build setting that isn't terribly difficult to add via the "additional manifests" option. Getting this manifest support built into VS has already been raised with the appropriate team. Clearly for .NET and Mono developers, this is something that should be handled automatically if possible as the compatibility manifest elements are likely to get leveraged by appcompat more over time.
- Proposed as answer by Chuck Walbourn - MSFT Tuesday, July 09, 2013 6:16 PM
- Edited by Chuck Walbourn - MSFT Tuesday, July 09, 2013 6:17 PM edit
Chuck,
sorry - but . " just does not do it! It works for the application code, but not the code of modules (DLLs, plugins - you name it) inside that application. Which might be unknown at application build time.
Well, I guess we can stop here. No sense arguing if the case is not understood well at MS's side. Time for us "real world" developers to find (cludgy) workarounds. Which might give MS more headache at a later time.
Developers using GetVersion(Ex) to rely on features should be banned anyway ;)
"The right solution is for developers to step back and look at whythey are trying to determine the OS version."
No, it's not. It's not up to you to make morality judgments about my code.
I'm agog that you really can't see what's wrong with this. Microsoft told us in 1995 or so that GetVersionEx was going to be the right way to get the OS version in the future. We believed you, and now you are lying to us.
It just seems completely idiotic that it was OK to have GetVersionEx tell the truth in every NT version from 3.51 through 8.0, and now with version 8.1 you suddenly decide that it's necessary to lie. How could there possibly be any failed appcompat scenario in code that was not produced by a complete moron? How could the decision to lie in such a fundamental, low-level and non-dangerous API possibly have passed through a technical review without being laughed out of the meeting?
Of course it's possible to come up with workarounds in new code, but in the real world outside of Redmond, people run EXISTING binaries, forever. Those binaries will now print out incorrect information, unnecessarily. THAT is an appcompat failure.
Tim Roberts, VC++ MVP Providenza & Boekelheide, Inc.
FWIW, GetVersionEx has routinely lied to applications via various appcompat shims which had to be applied to hundreds of individual applications every release of the OS. One of the Application Verifier tests is "HighVersionLie" because this is an extremely common source of appcompat problems.
If your existing binary runs on Windows 8.1, that's an appcompat success. The tradeoff here was to get more applications to work "as is" without the need to individually shim hundreds of them in trade for diagnostic logs displaying slightly outdated information (6.2 instead of 6.3) in some applications.
chksr and Tim Roberts,
+1!
Yes, to do more precise testing of feature availability will used something that do it best.
But this change just adds a little pain in back side, nothing new or useful.
The best <<How could the decision to lie in such a fundamental, low-level and non-dangerous API possibly have passed through a technical review without being laughed out of the meeting?>>. Getting version number of core OS(not its features) via system file info and much longer code - not bad too.
The lie it's allways very bad.
Technical note: You can use the Manifest Tool (MT.EXE) to inject a manifest into an existing EXE (i.e. without having to rebuild it). The only downside is if the EXE was code-signed which would of course modify it and invalidate the signature.
RE: plug-ins, the best option if you can't avoid the need to use GetVersoin(Ex) would be to get the host application manifested--assuming that's an option.
- Edited by Chuck Walbourn - MSFT Wednesday, July 10, 2013 11:36 PM edit
"RE: plug-ins, the best option if you can't avoid the need to use GetVersoin(Ex) would be to get the host application manifested--assuming that's an option."
More often than not, this is no option. We sell add-on tools for other developers - no way to ask them to do that, they would react correctly and ask if we're crazy.
We use GetVersionEx for "large" changes like theming availability, which are definitely version-bound, all other features are decided upon API or interface availability. And the wrong descriptions in the MSDN (a lot of APIs that existed in NT2000 are not "supported starting Windows XP") does not make life easier for us programmers. Why does the documentation change for the worse?
For me, this is a theoretical discussion, as I think Microsoft should leave some decisions to the developers, and also give them the blame if they do something wrong. I know there are a lot of developers out there which make your hair stand on end, but suppressing mistakes of these will not raise the level to be considered a "developer", to the contrary. And the others will make workarounds that make compatibility harder at a later time.
In Germany, we say "gut gemeint ist das Gegenteil von gut", which means "well-meant is the contrary of well-done".
"We sell add-on tools for other developers - no way to ask them to do that, they would react correctly and ask if we're crazy."
Why would that be 'crazy' exactly? Presumably the host application(s) are intended to be fully compatible with Windows 8.1?
I fully appreciate that relying on the host application doing this in a timely fashion for your add-ons is unrealistic, but longer-term the intent is for every application that explicitly supports Windows 8.1 to have these elements in an embedded manifest.
- Edited by Chuck Walbourn - MSFT Thursday, July 11, 2013 6:38 PM edit
- chksr, ... or ... well are determined to make life complicated
- Edited by iContribute Thursday, July 11, 2013 7:16 PM 777888
Why not? Stable frozen API. Embedded manifest does not guarantee anything for app or add-on. All bugs remain in its places.
New feature - old bugs adapted for new OS (proved by manifest). That what we need)
- Edited by iContribute Thursday, July 11, 2013 7:15 PM 12345
So I used the below code and now everything's alright!
However, where to find supportedOS Id for Win XP, Server 2008, Server 2008 R2 to add to manifest?
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <!-- Windows 8.1 --> <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da}"/> </application> </compatibility>
These manifest elements were introduced in Windows Vista. Windows XP ignores them.
The Windows Vista GUID applies to both Windows Vista and Windows Server 2008.
The Windows 7 GUID applies to both Windows 7 and Windows Server 2008 R2
The Windows 8 GUID applies to both Windows 8 and Windows Server 2012
The Windows 8.1 GUID applies to both Windows 8.1 and Windows Server 2012 R2
- I don't know for sure, but the Windows 8 GUID was fixed as of the Developer Preview. There's not much reason to change it...
- Edited by Chuck Walbourn - MSFT Monday, July 15, 2013 2:45 AM edit
Assuming you would a photoshop plugin, would you really ask Adobe to alter the manifest of Photoshop (although they might gain nothing out of it, even if they are "fully compatible" -> principle "never change a running system")? If your plugin will/should also work in an older, non-maintained version?
I guess not. You can try anyway, but you will not succeed.
Still you would like to get the "correct" Windows version (8.1) in your plugin, if only for debugging purposes if your plugin has problems and you would like to reproduce the problem using the correct environment (and, say, assuming the problem is problem appearing in 8.1 only - and YES, that might happen, even if MS does not like it).
So now MS has the problem that all modules wanting to be independent of the app (i.e. third-party tools) must use some other way to get the correct Windows version, and there's no way to "virtualize" these calls later if MS wants to. Whatever for.
What do you expect that tool developers should do? Remain at the stage of the host app, even if they know they can or must exploit the OS more? No sir. Add-ons might know better what to do, depending on the host OS ;)
OTOH, at least for debugging purposes, we need the real version number. The rest (API flavours etc) is queried on demand (at least, most of it). So as I said it's irrelevant, except it shows some app-centric thinking.
(And why does this control change the font size when I kill a superfluous line break? Sigh.)
The process is the resource partition and the application is the owner of the process. In-process modules must obey the process environment created for the application. It is as simple as that.
If you need independent freedom, you can have it in your own process.
- I would love to know why you think that.
Might make sense in some cases, but obviously not for developer tools (some customers use - yes - VB 6, Access, Alaska xBase, ...). Do you really think MS will add a corresponding "Win 8.1-compatible" manifest to VB6? ;)
Well as long as it's only a "GetVersion()" lie, we can live with it, use the workaround, and feel good. But otherwise, if "real" features themselves are limited according to some application-only manifest, I will send a **** (NSA blackened no-no-word of an explosive) to Redmond.
"If you need independent freedom, you can have it in your own process."
You think we need to rewrite customer's applications or whole development environments just to allow them to use new OS features?
See my comment above. This would cost us a lot of customers who cannot change their IDE/development environment just as their underwear. For some applications, these are fixed for a whole lifetime of that application. Still the customers like new features of our tool, of course!
The obvious solution would be an out-of-process server, but that would be overkill and a speed brake.
You think we need to rewrite customer's applications or whole development environments just to allow them to use new OS features?
VB6 is long out of support:
In all technical environments there comes a time to cut old stuff to medernize. That is the way...
You should be able to solve your problem if you add an manifest as resource to your application (maybe in a post build process, if you can not add user resources in VB!?!? - I',m no VB user). Than GetVersionEx will work. I did this manifest stuff for an old VC++6 application some time ago, and it worked without problems. Why not doing the same in VB?
Best regards
Bordon
Note: Posted code pieces may not have a good programming style and may not perfect. It is also possible that they do not work in all situations. Code pieces are only indended to explain something particualar.
You think we need to rewrite customer's applications or whole development environments just to allow them to use new OS features?
No. The applications should run just fine on the new OS. That's exactly why the version lie is there. It enables the application to work flawlessly on the new OS without rewrinting the application at all.
- Sorry, but is it that hard to understand that "You should be able to solve your problem if you add an manifest as resource to your application " is not possible, as the application is not MINE, but from a customer that just uses our tool to print nice reports?
Yes. The application.
But I'm talking about our DLL in a host application not written by us. And our DLL would like to see all OS features (right now we can see everything, but once Windows "lies" about features, we get into troubles), and the true OS version (for now, just for debug logging).
So right now, it's a non-issue, but it makes me wonder what the MS developers think. There used to be a "divide the work and reuse these parts"-pattern, that's what DLLs are for, and now MS becomes EXE-centric and forgets about the myriad of DLLs that do not care about the OS version that is presented to the application. If at all, they would need their own small "lie" according to a manifest in the DLL.
Imagine, the host application says "well, I can live with and use Windows 8.1's features", but then one of these DLLs gets into trouble as it can NOT support these? Will the developer of the EXE (even be able to!) ask all DLL manufacturers about their attitude towards an entry in the manifest that he likes to set because HE likes to express new Windows-compatibility with HIS application?
It just does not fit the system of Application and DLLs.
An EXE that consumes 3rd party DLLs already has to take responsibility for integration testing. If they add the manifest entry to the EXE that declares support for Windows 8.1, then presumably they actually tested it on Windows 8.1. This is why the compat manifests use a GUID so that developers can't just throw in "I support all the Windows" and then fail to actually test it on a future OS that believes it is compatible.
There are of course special challenges for an EXE that use as-yet-unseen 3rd party DLLs as a 'plug-in' model. The point here is that the host application is not declaring full support for Windows 8.1, so the whole process is treated as if it in a compatibility mode.
- Edited by Chuck Walbourn - MSFT Thursday, August 15, 2013 6:19 PM edit
Here is a new CodeProject article about detection of "true" Windows version.
Still it is a mystery why we have to take all these hoops. Doesn't this mean that the next OS technically is not "Windows" or "Windows NT" any more, so the query becomes meaningless?
-- pa
This seems to be a case of "the cure is worse than the disease".
For most people, the solution is pretty easy.
* Remove use of GetVersion and GetVersionEx everywhere you can. Use built-in versioning mechanisms like gracefully failing to initialize a component.
* Use VersionHelpers.h if you can or the VerifyVersionInfo() API for 'you must be this high to ride this ride' style of checks.
* If you still need it for a reason other than logging, then add the manifest elements and continue to call GetVersion/GetVersionEx.
* For logging, just grab the version string from kernel32.dll and use it as an opaque string (i.e. don't try to parse it).
I do understand that people who are writing plug-ins are in a bind until the core application updates itself with the manifest elements, but that doesn't mean the rest of world of application developers should go crazy over this.
- Edited by Chuck Walbourn - MSFT Tuesday, November 12, 2013 6:51 AM edit
I guess fundamentally you don't get it, which is why the guys are jumping on you about it. Don't lie in your API calls. Period. Some of us have written stable, unchanging, working, industrial code that may be even older than you are. the API is a contract and you broke it. Don't go defending that change. What the developers are doing with the information is their own bad or good decisions and the OS manufacturer has no place in handling our code. Of course, maybe it's that your own MICROSOFT applications have issues and your trying to help your brethren out.
Regardless, there are business reasons we have customers that do not permit changes to released/paid-for code that they put on newer operating systems. If Microsoft built buildings like they do software, the buildings would fall down yearly and require reconstruction. Great for employment, bad for business.
There are a number of appcompat behaviors contingent on application manifests spanning the past few releases of Windows. A summary of the key ones is covered by this blog post.
- Proposed as answer by Chuck Walbourn - MSFT Wednesday, January 08, 2014 6:37 PM | http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/c471de52-611f-435d-ab44-56064e5fd7d5/windows-81-preview-getversionex-reports-629200?forum=windowssdk | CC-MAIN-2014-35 | refinedweb | 4,329 | 64.81 |
[Barry Warsaw] > Is it possible that USE_RECURSION_LIMIT isn't defined for my RH > builds?! I can't see how: it's set by a giant maze of #ifdef's, which are almost as reliable as a giant maze of CVS branches <wink>. Because the #ifdef's nest 4 deep at one point, and the bodies aren't indented, it's damned hard to figure out what they're doing by eyeball. But I *think* this part: """ #else #define USE_RECURSION_LIMIT 10000 #endif #endif #endif """ which gives all the appearance of defining a default value (if nothing else triggers), is actually nested *inside* an #elif defined(__FreeBSD__) block (which is in turn nested in a !defined(USE_STACKCHECK) block, which is in turn nested in an ifndef SRE_RECURSIVE block). God only knows what the intent was. But I expect that, yes, USE_RECURSION_LIMIT isn't getting defined on anything other than FreeBSD and Win64. > I added the attached little bit of (seemingly useful) code > to _sre.c, recompiled and then... > > % ./python > Python 2.3.3a0 (#4, Nov 21 2003, 13:39:39) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import _sre > [24546 refs] > >>> _sre.RECURSION_LIMIT > [24546 refs] > >>> > [24546 refs] > [7129 refs] > > Very odd. OTOH, if you believe what it says, that leads directly to the cause <wink>. | https://mail.python.org/pipermail/python-dev/2003-November/040363.html | CC-MAIN-2017-30 | refinedweb | 229 | 75.3 |
Talk:Support
From OLPC
A draft is in progress on how to better streamline this page for G1G1v2
hi this is just a suggestion, would be nice to have photos of the tools and the dimensions of the screwdriver for example..
- not a bad idea. Please sign your posts :-) --Sj talk to me 19:29, 24 December 2007 (EST) (who notes we should get some of the autobots to sign and unblank contributions)
- The Disassembly page doesn't have pictures of tools, but almost any "small" (#0 or #1) philips head screwdriver -- like those in jeweler's screwdriver sets -- works. Adding link to it to the article... Joemck 17:51, 7 January 2008 (EST)
moving to the Help namespace...
We discussed moving the various FAQs into the Help namespace; as well as triaged AOAQ questions. This will make it possible to search across them simply, and will clean up the article namespace. I'll do this tomorrow if there are no complaints. --Sj talk to me 19:31, 24 December 2007 (EST)
new graphical look
Here's a draft : User:Coderanger/Support
OLPCsupport.org Web Site
You should add the OLPCsupport.org web site to the Community/Live Support section.
RMA information
A link from the main support page to would be good - I suspect I'm not the only one who wasted the operators' time calling in to get an RMA, not having the required information --dragonfrog
Network Marketing
Some ideas: >Network marketing is really taking off in Africa. eg GNLD (division of Golden Products). Perhaps this method of distribution might be better than relying solely on donations/government input? >Cellphones are huge in Africa - people will buy a phone instead of shoes! Perhaps the cell companies could be approached to link the XO to a basic cell package (eg contract for v.basic phone,certain amount of airtime, and XO as rent to buy)?.. >Churches(eg Church of England in South Africa) would probably want to get involved..provide voluntary manpower and funds... | http://wiki.laptop.org/go/Talk:Support | CC-MAIN-2015-35 | refinedweb | 335 | 63.09 |
In yesterday's post I stated that "non-character keys do not trigger KeyPress events." While that is perfectly true, I misunderstood what was meant by a non-character key. In the non-managed Win32 world, pressing a key generates a WM_KEYDOWN, one or more WM_CHAR messages, and a WM_KEYUP message. The managed KeyPress event corresponds to the WM_CHAR message. Windows generates WM_CHAR messages for keys that are mapped to ASCII characters by the keyboard driver. Since pressing the Enter key generates an ASCII character code (0xA, 0xD, or both), a KeyPress event is generated for it.
So, while the code I posted yesterday works, it can be simplified by eating the Enter key in the textbox's KeyPress event handler rather than using the form's KeyPreview.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if ('\r' == e.KeyChar) { // Supress enter key e.Handled = true; } }
In addition, since the textbox is no longer dependent on the form for functionality, I can package it up in it's own class.
public class TextBoxWithAlignment : TextBox { // Remember whether user wants the textbox to act like a // single-line or multiline textbox. // private bool multiline = false; public TextBoxWithAlignment() { // The underlying control will always be a multiline textbox // base.Multiline = true; } protected override void OnKeyPress(KeyPressEventArgs e) { // When the user wants a single-line textbox, // eat carriage returns // if (!this.multiline && '\r' == e.KeyChar) { e.Handled = true; } base.OnKeyPress(e); } // Override the Multiline property to use the internal multiline flag // public override bool Multiline { get { return this.multiline; } set { this.multiline = value; } } }
Pretty nifty, IMHO.
Cheers
Dan | https://blogs.msdn.microsoft.com/bluecollar/2007/02/07/setting-alignment-in-textboxes-no-looking-glass-required/ | CC-MAIN-2019-35 | refinedweb | 262 | 57.87 |
I would like an advice on the "IF" statement about an action "Favorite" which permit to the user to favorite a game.
One association is necessary for one game. One user ID / One Game ID (in the join table).
I got the unicity in the DB with my model GameUser:
class GameUser < ActiveRecord::Base
belongs_to :game
belongs_to :user
validates_uniqueness_of :game_id, scope: :user_id
end
def favorite
game = Game.find(params[:id])
if
# Here is where I struggle,
#if User haven't got already a match in the DB (Join table User_ID / Game_ID) then :
current_user.games << game
flash[:notice] = "#{Game.name} Favorited"
redirect_to games_url
else
flash[:notice] = "#{Game.name} already favorited"
redirect_to games_url
end
end
Has Game
has_many :game_users? If so should be enough
if game.game_users.exists?(user_id: current_user.id)
note that you can do it even without association
if GameUser.exists?(user_id: current_user.id, game_id: game.id) | https://codedump.io/share/lhPR4ASv24Qw/1/rails---statement-if-for-a-join-table-in-the-controller | CC-MAIN-2017-34 | refinedweb | 147 | 59.6 |
Join the 85,000 open source advocates who receive our giveaway alerts and article roundups.
Using Groovy to access and parse an exchange rate API
Using Groovy to access and parse an exchange rate API
A groovy way to simplify bookkeeping: a step-by-step guide to converting currency exchange using Apache Groovy.
opensource.com
Get the newsletter
I live in Canada and do a fair bit of work in other countries, so when I do my bookkeeping, I have to convert revenue and expenses in foreign currencies to Canadian dollars. I used to do this by laboriously looking up historical exchange rates at the Bank of Canada, but last year the bank reduced the number of currencies it supports. I decided to look for a different and more practical solution, using a website that publishes historical data on currency exchange rates and Apache Groovy, a programming language for the Java platform.
I found two foreign exchange history sites that permit some degree of free access in the form of calls to their APIs that return results in JSON, so I wrote a small script in Groovy to parse the JSON and give me back the info I need to enter in my bookkeeping program. Here's how I did it.
Exchange rate sites and their APIs
The first site I found is Fixer.io, which I really like. It is a free service that accesses data from the European Central Bank. The API is straightforward and simple to use. For example, if I want exchange rates for Canadian dollars and Indian rupees, I use the following URL:
which, when I ran that query for this article, returned the following JSON:
{
"base":"EUR",
"date":"2018-02-15",
"rates":{"CAD":1.5604,"INR":79.849}
}
This shows that on Feb. 15, 2018, it took 1.5604 Canadian dollars to buy 1 euro and it took 79.849 Indian rupees to buy 1 euro. To figure out how many Indian rupees it took to buy 1 Canadian dollar, just divide 79.849 by 1.5604 to arrive at 51.172 Indian rupees per Canadian dollar. What could be easier?
Even better, Fixer.io is open source, published under the MIT License, and the code is available on GitHub.
Fixer.io addressed my need to convert Indian rupees to Canadian dollars, but unfortunately, it does not offer a solution for Chilean pesos, since the base data at the European Central Bank covers "only" 32 currencies.
To get information on Chilean pesos, I ended up at Currencylayer, which (at this time) provides data for 168 currencies. Currencylayer requires registration and charges a fee for its more valuable products and complex operations, but basic historical exchange rate conversion between U.S. dollars and 167 other currencies is free. Because of its broad coverage, I used Currencylayer to write this article.
Registering at Currencylayer gives the user a key that grants access to the tier of services selected. Assuming the key is
K, then a URL like:¤cies=CAD,EUR&format=1
will return the following JSON:
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"historical":true,
"date":"2018-01-01",
"timestamp":1514851199,
"source":"USD",
"quotes":{
"USDCAD":1.25551,
"USDEUR":0.832296
}
}
Using Groovy to access the API and parse the JSON results
Groovy provides some concise tools for dealing with URLs, streams of data, and JSON.
Starting at the JSON end, there is the JSON slurper and its handy
parse() method. One form of the JSON slurper parse method takes a stream as its argument.
This is handy because, starting at the URL end, we can open a stream on a URL with its
newInputStream() method.
Assuming we have built the URL string, that is, the API call, in a Groovy string variable called
urlString, we can open the URL, read the stream produced, and parse the JSON with the following Groovy code:
def result = (new JsonSlurper()).parse(
new InputStreamReader(
(new URL(urlString)).newInputStream()
)
)
The Groovy variable
result is a map (that is, a set of key-value pairs) and looks like this:
[success:true, terms:,
privacy:, historical:true,
date:2018-01-01, timestamp:1514851199, source:USD, quotes:
[USDCAD:1.25551, USDEUR:0.832296]]
This map corresponds precisely to the raw JSON shown above. For example, the key
date has the value
2018-01-01.
Groovy allows us to access the value assigned to the
date key either by:
result['date']
or
result.date
either of which will return the value
2018-01-01.
Note that the key quote refers itself to a map with two keys: one that gives the conversion between U.S. and Canadian dollars, the other that gives the conversion between U.S. dollars and the other currency of interest. In the above case, these can be accessed by
result['quotes']['USDCAD'] and
result['quotes']['USDEUR']
or
result.quotes.USDCAD and
result.quotes.USDEUR.
Using the latter format, and assuming the original amount is in a Groovy variable
amtOrig, the amount in Canadian dollars can be calculated as:
def amtCAD = amtOrig / result.quotes.USDEUR * result.quotes.USDCAD
If I need to convert U.S. dollar expenses incurred while passing through DFW airport, for example, the formula is simpler:
def amtCAD = amtOrig * result.quotes.USDCAD
That's really all there is to it.
The (almost) working script
Let's turn it into a working Groovy script. We'll get the arguments from the command line and check them. Then if all looks good, we'll build the URL string, call the API, and get the result in map format. Finally, we'll pull apart the result map and calculate the exchange. Here's the script:
import groovy.json.JsonSlurper
// Check to make sure arguments are correct and print usage if not
if (args.size() != 3) {
System.err.println "usage: groovy fx.groovy yyyy-mm-dd amount currency-code"
System.exit(1)
}
// Check arguments for formatting and reasonable values
String dateString = args[0]
if (!(dateString ==~ /(19\d\d|2[01]\d\d)\-(0[1-9]|1[012])\-([012]\d|3[01])/)) { 1
System.err.println "fx.groovy date $dateString not in format yyyy-mm-dd"
System.exit(1)
}
String amountString = args[1]
if (!(amountString ==~ /\d+(\.\d+)?/)) { 1
System.err.println "fx.groovy amount $amountString not numeric"
System.exit(1)
}
String currencyCode = args[2]
if (!(currencyCode ==~ /[A-Z][A-Z][A-Z]/)) { 1
System.err.println "fx.groovy currency-code $currencyCode not three capital letters, e.g. USD,CAD,EUR,GBP"
System.exit(1)
}
// Our free license will only convert through USD so we adjust the currency list
// according to whether the original currency was USD or something else
String currencyCodeList = currencyCode == 'USD' ? 'CAD' : "CAD,${currencyCode}" 2
// The access key code given during site signup
String accKey = 'a5bd4434d2299ecb3612ad297402481c' 3
// Build the URL string for the API call, get the JSON and parse it
String urlString = "{dateString}¤cies=${currencyCodeList}&format=1" 2
def result = (new JsonSlurper()).parse(new InputStreamReader((new URL(urlString)).newInputStream()))
// Pick apart the values returned and compute the exchange info
BigDecimal amtOrig = new BigDecimal(amountString) 4
if (result.quotes.size() > 1) {
String toUSDString = 'USD' + currencyCode
BigDecimal amtCAD = amtOrig / result.quotes[toUSDString] * 5
result.quotes.USDCAD
println "$amtOrig $currencyCode toUSD ${result.quotes[toUSDString]} toCAD ${result.quotes.USDCAD} $amtCAD" 2
} else {
BigDecimal amtCAD = amtOrig * result.quotes.USDCAD
println "$amtOrig $currencyCode toCAD ${result.quotes.USDCAD} $amtCAD" 2
}
A few comments:
- Those are regular expression pattern matches. Yes, I could have used
try... catchblocks.
- The notation
... ${foo}...is called a Gstring in Groovy; the thing in
${}is evaluated, and that value replaces it in the final string.
- That's not my access key! But it looks kind of like it.
- I'm using
BigDecimalrather than
doubleto carry out my calculations.
- I'm using
[toUSDString]to access the value; this is because
toUSDStringis a variable, not a constant string.
- Long lines have wrapped around somewhat. Sorry about that!
If you haven't used Groovy much, some of the above will probably seem a bit magical, but it's not—really. I hope this encourages further study!
Note that people working with U.S. dollars as their base don't have to go through the intermediate computations.
And a final, cautionary comment: These and other historical exchange rates are indicative, generally computed from averages of other figures. So, if it cost you 2,623 Czech koruna to purchase 100 Euro on Feb 15, 2018, but Fixer.io gives you an exchange rate of 25.370 Czech koruna to the Euro on that date, it's not an error! You may have paid a different amount at a different financial institution. | https://opensource.com/article/18/3/groovy-calculate-foreign-exchange | CC-MAIN-2019-22 | refinedweb | 1,436 | 58.18 |
Not sure the correct words to ask the question are. Here is an example from what I have seen:
So say Chris re-did some of the screencasts,and now he had two versions of the view(content). What is the way like the example url above that you could view the old view(content) by using
?old_content=true. How would that be set up in routes or would that be in the controller?
I hope this question makes sense.
Thanks for the help.
Edit: I just saw a real example here on gorails where it is saying
?autoplay=1
Hey Matt,
?old_content=true is a param that's being passed to the controller action possibly located in
controllers/series_controller.rb. Inside, let's say the
show action, there would be something like
old_content = params[:old_content] which would be populated with it's value, so in this case, true.
Now Chris can do all sorts of things with this info...
def show old_content = params[:old_content] if old_content == true return something special if it's supposed to be the old content else return soemthing else when old_content is false or not present at all end end
You can also chain them:
?old_content=true&autoplay=1&this_is_cool=true
and access like:
old_content = params[:old_content] autoplay = params[:autoplay] this_is_cool = params[:this_is_cool] if this_is_cool puts "you rock!" end
Thanks Jacob. So in the example of his
autoplay=1 is he hardcoding that onto the end of the url path, or how is that getting added to the params hash?
Thanks
In a link, you can do something like
<%= link_to "Put a param", show_series_path(autoplay: 1) %>
to pass the param. You can also manually type it when you're testing in your own application.
Jacob is exactly right. :D
And just a quick note: generally you use these url params to do filtering (like pagination) or sorting or you'd use them to turn on and off simple features like autoplaying of videos like you see on here.
Then sometimes it's nicer to have a full path dedicated to a section to designate it's importance so I'll tend to do that for things like forum categories. Rather than just saying
/forum?category=rails I've got
/forum/category/databases to kind of denote that it's a dedicated page.
It's late so I don't know if I'm explaining that bit well, so here's a stack overflow post that describes the same thing:
Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more. | https://gorails.com/forum/how-is-routing-done-with-a-conditional-in-url | CC-MAIN-2019-35 | refinedweb | 430 | 71.24 |
To reverse a number in Java programming, you have to ask to the user to enter the number. Start reversing the number, first make a variable rev and place 0 to rev initially, and make one more variable say rem. Now place the modulus of the number to rem and place rev*10+rem to the variable rev, now divide the number with 10 and continue until the number will become 0.
Following Java Program ask to the user to enter any number to find its reverse, then display the result on the screen :
/* Java Program Example - Reverse a Number */ import java.util.Scanner; public class JavaProgram { public static void main(String args[]) { int num, rev=0, rem; Scanner scan = new Scanner(System.in); System.out.print("Enter a Number : "); num = scan.nextInt(); while(num != 0) { rem = num%10; rev = rev*10 + rem; num = num/10; } System.out.print("Reverse = " +rev); } }
When the above Java Program is compile and executed, it will produce the following output:
You may also like to learn and practice the same program in other popular programming languages:
Java Programming Online Test
Tools
Calculator
Quick Links | https://codescracker.com/java/program/java-program-reverse-numbers.htm | CC-MAIN-2017-39 | refinedweb | 190 | 58.21 |
#include <snl_fei_MapTraits.hpp>
Define map traits. For now, only a trait for map.lower_bound and map.insert. Generally we simply call the corresponding methods on std::map, but these traits will be specialized for map classes that may not always have directly equivalent methods (such as hash_map, etc.). (hash_map doesn't have lower_bound, and hash_map's insert doesn't allow the use of an iterator argument to hint where the object should be inserted.)
Definition at line 23 of file snl_fei_MapTraits.hpp.
lower_bound
Definition at line 26 of file snl_fei_MapTraits.hpp.
insert a value using iterator for position hint
Definition at line 31 of file snl_fei_MapTraits.hpp. | http://trilinos.sandia.gov/packages/docs/r10.4/packages/fei/doc/html/structsnl__fei_1_1MapTraits.html | CC-MAIN-2014-10 | refinedweb | 107 | 50.73 |
Azure Container Services (ACS) makes it incredibly easy to spin up and manage Kubernetes clusters in the cloud. There are plenty of other Azure resources which you can use to build daily scenarios on a native cloud stack. Common scenarios are serving files from and writing important information to persisted locations. Azure offers many different storage capabilities. In this post, I’ll explain how to use an Azure File Share to serve content by using a .NET Core Web API.
Azure Files
Using Azure Files you can create SMB 3.0 file shares and access them from all over the world. No matter if you’re running a cloud-native application or working in a hybrid scenario, Azure Files can be accessed from everywhere. It’s easy to set up and reliable solution to deal with files from multiple places. Also if you build highly scalable applications in Kubernetes, Azure File Shares can easily be mounted using k8s volumes.
See the following link to get more detailed information about Azure Files and Azure File Shares.
Creating a Managed Azure File Share
For demonstration purpose, we’ll create a simple Azure File Share. Before actually creating the network share itself, a Storage Account (located in the same Azure location as your k8s cluster) is required.
Create the Azure Storage Account
Creating the Storage Account is pretty easy. For demonstration purpose, I’ll go with the cheapest configuration which means Standard_LRS. Depending on your scenario and requirements you may choose one of the advances and more reliable configurations.
# check if the storage account name of your choice is available az storage check-name --name <STORAGE_ACCOUNT_NAME> # if you found an available name, go create the storage account az storage account create --name <STORAGE_ACCOUNT_NAME> --resource-group <RESOURCE_GROUP_NAME> --sku Standard_LRS
Create the Azure File Share
In order to create our Azure File Share, the connection string from our Storage Account is required. Using Azure CLI, we can simply ask for the connection string using:
az storage account show-connection-string --resource-group <RESOURCE_GROUP_NAME> --name <STORAGE_ACCOUNT_NAME> --output tsv
Azure CLI will print just the connection string itself, without any metadata. Copy that connection string. Now it’s time to create the share itself.
az storage share create --name <SHARE_NAME> --connection-string <STORAGE_ACCOUNT_CONNECTION_STRING> --account-name <STORAGE_ACCOUNT_NAME>
The command
az storage share create will simply respond with a
{ created: true } JSON if the operation is finished. You can either mount the share on your operating system, use the Azure Portal or you can download and use the Azure Storage Explorer to upload files to your new Azure File Share.
Take the following image, save it as
docker.jpg and upload it to the root of your Azure File Share.
Create a simple Web API
We’ll create a simple .NET Core Web API to serve a jpeg from the Azure File Share. Again there are plenty of choices about how to create the new .NET Core Web API project. I’ll use JetBrains Rider here. Use Rider’s New Project wizard to create the ASP.NET Core WebAPI project as shown in the following image.
Once Rider has created the Project and pulled all the required NuGet packages, go and add a new Controller named
ImageController and add the following source code.
using System.IO; using System.Net.Mime; using Microsoft.AspNetCore.Mvc; namespace Probe.Api.Controllers { [Route("api/[controller]")] public class ImageController : Controller { [HttpGet] public IActionResult Get() { var image = System.IO.File.OpenRead(Path.Combine("mnt","azure","docker.jpg")); return File(image, "image/jpeg"); } } }
As you can see, it’s a simple
GET endpoint which will return the entire contents of a file located at
./mnt/azure/docker.jpg. Let’s create a
Dockerfile to build an image for our API.
FROM microsoft/dotnet:2.0.0-sdk AS build-environment LABEL maintainer="Thorsten Hans<thorsten.hans@gmail.com>" WORKDIR /app COPY ./src/*.csproj ./ RUN dotnet restore COPY ./src ./ RUN dotnet publish -c Release -o out FROM microsoft/aspnetcore:2.0.0 WORKDIR /app COPY --from=build-environment /app/out . ENTRYPOINT ["dotnet", "AzureFileShareDemo.API.dll"]
First, we restore all NuGet packages and
publish the project using the
microsoft/dotnet:2.0.0-sdk image, once publish as succeeded, a way smaller image
microsoft/aspnetcore:2.0.0 (which is just providing the runtime for ASP.NET Core) is used to build our final docker image. Use
docker build -t azure-file-share-sample . to build the docker image.
Once you’ve successfully built the docker image, you’ve to publish it either to the public docker hub or to a private container registry. If you want to keep the image private, go and read my article on how to use Azure Container Registry (ACR) with an existing Kubernetes cluster.
Create a Kubernetes deployment
A Kubernetes deployment configuration is just a simple yaml or json file which describes how our deployment should look like. In the following snippet we’re creating the Pod (it’s responsible for executing our docker container) and a Secret (it will contain all sensitive information about how the Pod should connect to Azure File Share).
Creating a Secret for Azure File Share connection settings
Secrets in Kubernetes can be created either using kubectl or by specifying it in a configuration file using
yaml or
json. If you want to describe your secret using a configuration file, you’ve to encode values manually as
base64 upfront.
On macOS or Linux this can be done using:
echo -n "Any value that you want to encode" | base64 > QW55IHZhbHVlIHRoYXQgeW91IHdhbnQgdG8gZW5jb2Rl
Take the name of your storage account and the storage account connection string and encode them.
Now create a new file, call it
azure-file-share-deployment.yaml and open it in your favorite editor. Add the following code to define the secret.=
Creating the actual Kubernetes deployment
The deployment can also be expressed using
yaml. We’ll use the official Volumes API from Kubernetes to connect our Pod to Azure File Share and mount the file share to
/app/mnt/azure
Edit the
azure-file-share-deployment.yaml to look similar to this= --- apiVersion: apps/v1beta1 kind: Deployment metadata: name: azure-file-share-deployment spec: replicas: 1 template: metadata: labels: app: azure-file-share-sample spec: containers: - name: azure-file-share-sample image: <YOUR_ACR_NAME>.azurecr.io/azure-file-share-sample ports: - containerPort: 80 imagePullPolicy: Always volumeMounts: - name: azure-fs mountPath: /app/mnt/azure imagePullSecrets: - name: <ACR_SECRET> # if you want to use ACR volumes: - name: azure-fs azureFile: secretName: azure-file-share-secret shareName: acs-file-share readOnly: true
So that’s a lot. But let’s look at the essential things. Most important is the volume definition underneath volumes. That’s where we provide a name for our volume and forward the configuration values from our secret(referenced by name). We also specify the volume to be read-only because our API is only allowed to serve files from there.
The second thing is inside of the container definition. we mount the
volume to a local directory at
/app/mnt/azure and again the
volume that should be mounted if referenced by its name
azure-fs in our example.
Deploying to Kubernetes
Deploying to Kubernetes is fairly simple. Just navigate to the folder where your
azure-file-share-deployment.yaml is located and execute:
kubectl create -f azure-file-share-deployment.yaml
Check the pod deployment by executing
kubectl get pods after a couple of seconds your Pod should be there and print
status as
running.
Normally you’ve to create a Service in Kubernetes, which will automatically deploy Azure Load Balancer 🚀 to expose your service to the public world. But for demonstration purpose or development you can also use the handy
kubectl port-forward command.
kubectl port-forward <POD_NAME> 5000:80
This command will block the terminal and forward all requests to your local port
5000 to port
80 of the Pod.
Open your browser and navigate to and it should return this beautiful image.
Recap
As you can see it’s fairly easy to use powerful services offered by Azure and use them to build your cloud-native applications based on Docker and Kubernetes. | https://thorsten-hans.com/using-azure-files-in-kubernetes-deployments-with-asp-net-core | CC-MAIN-2019-18 | refinedweb | 1,359 | 56.05 |
Your presenters don’t need all those lifecycle events
MVP is the new black in AndroidDev and there’s about a billion ways to do it.
One common mistake that is oft repeated is that developers keep including way too many activity/fragment lifecycle events inside their presenters ending up destroying the separation between the view and presentation layers. The benefits that MVP provides us — testing, agility and separation of concerns can only be achieved if we keep our presentation and UI layers decoupled.
My fellow developers, You must try your darndest to keep those presenters Android free.
So here’s what I propose
Let’s have only two lifecycle related methods inside your presenters. One will be called
onViewAttached and another will be it’s counterpart
onViewDetached.
Here’s what it looks like:
public interface Presenter {
void onViewAttached(MVPView view);
void onViewDetached();
}
All your presenters would implement this interface and in turn would have to implement these methods.
Great, but when do we call them from the view?
I prefer calling
onViewAttached and
onViewDetached during
onStart and
onStop respectively. This way your UI will truly be ready to be interacted with when
onViewAttached is called.
Here’s what that looks like:
public class BaseActivity extends AppCompatActivity {
@Override
protected void onStart() {
super.onStart();
presenter.onViewAttached(this);
}
@Override protected void onStop() {
super.onStop();
presenter.onViewDetached();
}
}
All your Activities would extend from this class and would get those method calls for free. Fragments can have a similar
BaseFragment class or something and extend from that.
What about saving and restoring state?
Here we have two options:
Let the view handle state management by itself: In this case your presenter doesn’t need any extra methods and the view will handle state restoration all on it’s own.
Manage state from the presenter : Here, you can have two extra methods in your
BasePresenter :
onSaveState and
onRestoreState which would be called by
onSaveInstanceState and
onRestoreInstanceState respectively.
You can pass the
Bundle object to these methods directly. This would break our “No Android in Presenters” rule but you can mock the
Bundle during tests using Mockito or the like without too much trouble.
Another way is to not use the bundle at all and save state somewhere else (DB, File, Shared prefs etc) but this might be slower to retrieve and you’ll have to clean up the saved state properly when you don’t need it anymore.
Go with whatever is more convenient to implement and test.
But I want to know if my Activity is new or not!
I hear ya. There are cases when you would need to know if your view is a new instance or an old one being re-created. This might be useful in situations where you need to do something only the first time a particular view instance is brought into the world.
To achieve this, we can modify our
onViewAttached method with an extra boolean parameter
isNew.
So our presenter interface becomes:
public interface Presenter {
void onViewAttached(MVPView view, boolean isNew);
void onViewDetached();
}
and our
BaseActivity becomes
public class BaseActivity extends AppCompatActivity {
private boolean isNewActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate();
// Check if it's a new view
isNewActivity = (savedInstanceState == null);
}
@Override protected void onStart() {
super.onStart();
presenter.onViewAttached(this, isNewActivity);
isNewActivity = false;
}
@Override protected void onStop() {
super.onStop();
presenter.onViewDetached();
}
}
We’re basically keeping track of a new instance creation in the Activity itself and passing this to the presenter whenever it’s attached.
I have a use case that needs more lifecycle events!
Great. Then add them in. I won’t claim that these 2 lifecycle events address every use case in the world and you might occasionally need more of them. When you do need them however, just make sure you’re being careful and not overdoing it.
Conclusion
MVP — good.
Too many lifecycle events in presenters — bad.
If you liked this, click the💚 below so other people will see this here on Medium.
For more musings about programming, follow me so you’ll get notified when I write new posts.
| https://medium.com/@anupcowkur/your-presenters-dont-need-all-those-lifecycle-events-721f500eeef4 | CC-MAIN-2017-09 | refinedweb | 680 | 54.22 |
MIN.
This section contains a high-level overview of the live update and rerandomization functionality.
A live update is an update to a software component while it is active, allowing the component's code and data to be changed without affecting the environment around it. The MINIX3 live update functionality allows such updates to be applied to its system services: the usermode server and driver processes that, in addition to the microkernel, make up the operating system. As a result, these services can be be updated at run time without requiring a system reboot. There is no support for live updating the microkernel or user applications at this time.
The live update procedure can be summarized as follows. The component responsible for orchestrating live updates is the RS (Reincarnation Server) service. When RS applies an update to a particular system service, it first brings that service to a stop in a known quiescence state, ensuring that the live update will not interfere with the service's normal operation, by exploiting the message-based nature of MINIX3. A new instance of the service is created. This new instance performs its own state transfer, copying and adjusting all the relevant data from the old instance to itself. If the state transfer succeeds, the new instance continues to run, and the old instance is killed. If the state transfer fails, RS performs a rollback: the new instance is killed, and the system resumes execution of the old instance. In order to maintain the illusion to the rest of the system that there only ever was one service process, the process slots of the old and the new instance are swapped before the new instance gets to run, and swapped back upon rollback.
The MINIX3 live update system allows updates to all system services. Those include the RS service itself, and the VM (Virtual Memory) service. The VM service can be updated with severe restrictions only, however. The system also supports multicomponent live updates: atomic live updates of several system services at once, possibly including RS and/or VM. In principle, this allows for an atomic live update of the entire MINIX3 service layer.
The state transfer aspect of live update relies heavily on compile-time and in particular link-time instrumentation of system services. This instrumentation is implemented in the form of LLVM “optimization” passes, which operate on LLVM bitcode modules. In most cases, these passes are run after (initial) program linking, by means of the LLVM Link-Time Optimization (LTO) system. Thus, in order to support live update and rerandomization, the system must be compiled using LLVM bitcode and with LTO support. The LLVM pass that performs the static analysis and link-time instrumentation for live update is called the magic pass.
In addition, live updates require runtime support for state transfer in each service. For this reason, system services are relinked with a library that provides all the run-time functionality which ultimately allow a new service instance to perform state transfer from its old instance. This library is called the magic runtime library or libmagicrt. Together, the magic pass and runtime library make up the magic framework.
Live rerandomization consists of randomizing the internal address space layout of a component at run time. While the concept of ASR or ASLR - Address Space (Layout) Randomization - is well known, most implementations are rather limited: they perform such randomization only once, when starting a process; they merely randomize the base location of entire process regions, for example the process stack; and, they apply the concept to user processes only. In contrast, the MINIX3 live rerandomization can randomize the address space layout of operating system services, as often as desired, and with fine granularity. In order to achieve this, the live rerandomization makes use of live updates.
The fundamental approach consists of a two-step process. First, new versions of the service program are generated, using link-time randomization of various parts of its program binary. Ideally, this would be done at run time; due to various limitations, MINIX3 currently only supports pregenerated randomized binaries of system services. Then, at runtime, the live update system is used to update from one randomized version of each service to another.
The randomization of binaries is done with another link-time pass, called the asr pass. The magic runtime library implements various runtime aspects of ASR rerandomization during live update.
In this section, we explain how to set up a MINIX3 system that supports live update and rerandomization, and we describe how to use the new functionality when running MINIX3.
We cover all the steps to set up a MINIX3 system that is ready for live update and rerandomization. For now, it requires crosscompilation as well as an additional build of the LLVM source code. The procedure is for x86 targets only.
The current procedure has been tested only from Linux as host platform, and may require minor adjustments on other host platforms. We provide a few additional instructions for those other platforms, but these may currently not be complete. Please feel free to add more instructions to this page, and/or open GitHub issues for other platforms and link to them from here.
After setting up an initial environment, the first step is to obtain the MINIX3 source code. After that, the next step is to build an LLVM toolchain with LTO support, which is needed because the regular MINIX3 crosscompilation LLVM toolchain does not include LTO support (yet - we are working on this). Once the LTO-supporting toolchain has been built, the final step is to build the MINIX3 sources, with extra flags to enable magic instrumentation and possibly ASR rerandomziation.
Once these steps have been completed successfully for the first time, one can later update the MINIX3 source and then rebuild the system. The LTO-supporting toolchain need not be rebuilt unless we upgrade the LLVM source code itself.
We will now go through all steps in detail. At the end of this section, there is also a summary of the commands to issue.
All of the commands in this section are to be performed on the crosscompilation host system rather than on MINIX3. None of the commands, except the Linux-specific
sudo apt-get example in the first subsection, require more than ordinary user privileges.
The initial step is to set up a crosscompilation environment. General information about setting up a crosscompilation environment can be found on the crosscompilation page. As one example, the reference platform used to test the instructions in this document was the developer desktop edition of Ubuntu 14.04, a.k.a.
ubuntu-14.04.2-desktop-i386.iso, with the following extra packages installed:
$ sudo apt-get install curl clang binutils zlibc zlib1g zlib1g-dev libncurses-dev qemu-system-x86
The MINIX3 build system uses one single directory in which to place all its files. This directory is one level up from the root of the MINIX3 source directory. Thus, it is advisable to create this containing directory at a location known to have enough free hard disk space. Here we use
/home/user/minix-liveupdate as an example, but the location is entirely up to you. The containing directory will end up having one subdirectory for the MINIX3 source code (called
minix-src in this document), one subdirectory for the LLVM LTO toolchain (called
obj_llvm.i386), and one subdirectory for the crosscompilation tool chain and compiled objects (called
obj.i386). Thus, the ultimate directory structure will look like this:
/home/user/minix-liveupdate/minix-src /home/user/minix-liveupdate/obj_llvm.i386 /home/user/minix-liveupdate/obj.i386
You have to choose a location for the containing directory, and create it yourself. The three subdirectories should be created automatically as part of the following steps. However, it has been reported that on some platforms (e.g., FreeBSD), some or all of these directories have to be created manually; this can be done with nothing more than a few basic
mkdir commands. In terms of disk space usage, expect to be needing a bare minimum of 30GB for the combination of these three subdirectories, with a recommended 40GB of available space.
The first real step is to fetch the MINIX3 source code. Other wiki pages cover this in more detail, but the simplest approach is to check out the sources from the main MINIX3 repository using git:
$ cd /home/user/minix-liveupdate $ git clone git://git.minix3.org/minix minix-src
This will create a
minix-src subdirectory with the latest version of the MINIX3 source code.
Later on, a newer version of the source code can be pulled from the MINIX3 repository:
$ cd /home/user/minix-liveupdate/minix-src $ git pull
In both cases, the next step is now to build the source code.
The second step is to build the LLVM LTO infrastructure, if it has not yet been built before. Eventually, this will be done automatically as part of the regular build. For now, we have a script that can perform the build, called
generate_gold_plugin.sh. It is located in the
minix/llvm subdirectory of the MINIX3 source tree. The basic procedure therefore consists of the following steps (but read this entire section first):
$ cd /home/user/minix-liveupdate/minix-src/minix/llvm $ ./generate_gold_plugin.sh
On some platforms, it may be needed to specify the C/C++ compiler and/or the name of the GNU make utility, which can be done as follows:
$ CC=clang CXX=clang++ MAKE=make ./generate_gold_plugin.sh
On FreeBSD and similar platforms, one may have to ensure that GNU make is installed (typically as
gmake) first, and pass in
MAKE=gmake to point to it.
This step may take several hours. It can be sped up by supplying a number of parallel jobs, through a
JOBS=n variable:
$ JOBS=8 ./generate_gold_plugin.sh
As stated before, after this command has finished successfully, it need not be reissued until LLVM is upgraded in the MINIX3 source tree. This is a rare event which is typically part of a larger resynchronization with NetBSD code, and we will clearly announce such events. When this happens, it may be advisable to remove the entire
obj_llvm.i386 directory as well as any files in
minix-src/minix/llvm/bin, before rerunning the generate_gold_plugin.sh script.
The third step consists of building the system and generating a bootable image out of it. When run for the first time, this step will also build the regular (non-LTO) crosscompilation toolchain. The first run may therefore (also) take several hours. The build procedure is just like regular MINIX3 crosscompilation, differing in only two aspects.
First, the appropriate build variables must be passed in to enable the desired functionality. In order to build the system with live update support through magic instrumentation, the build system must be invoked with the
MKMAGIC build variable set to yes. This will perform a bitcode build of the entire system, and perform magic instrumentation on all system services.
In order to build the system with ASR instrumentation, the build system must be invoked with the
MKASR build variable set to yes. This will automatically enable magic instrumentation, perform ASR randomization on all system services, and pregenerate a number of ASR-rerandomized service binaries for each service. This number can be controlled with an additional
ASRCOUNT=n build variable, where the n value must be between 1 and 65536 (inclusive). The default ASRCOUNT is 3.
Second, in order to build a hard disk image suitable for use by the resulting bitcode builds, the
x86_hdimage.sh script must be invoked with the -b flag. This will enlarge the generated image to account for the larger binaries, and enable inclusion of ASR-rerandomized binaries if necessary.
These two aspects can be covered in a single build command. The following short procedure will build a hard disk image with magic instrumentation:
$ cd /home/user/minix-liveupdate/minix-src $ BUILDVARS="-V MKMAGIC=yes" ./releasetools/x86_hdimage.sh -b
In order to speed up the build, a number of parallel jobs may be supplied. It is typically advisable to use as many jobs as there are hardware threads of execution (i.e., CPU cores or hyperthreads) in the system:
$ JOBS=8 BUILDVARS="-V MKMAGIC=yes" ./releasetools/x86_hdimage.sh -b
It may be necessary to ensure that clang is used as the compiler:
$ CC=clang CXX=clang++ JOBS=8 BUILDVARS="-V MKMAGIC=yes" ./releasetools/x86_hdimage.sh -b
Also, some platforms may not be able to compile the compiler toolchain for the target platform due to running out of memory. In that case, it is possible to build an image that does not come with its own compiler toolchain, by passing in the
MKLLVMCMDS=no build variable. This build variable can also be used simply to speed up the compilation procedure.
$ BUILDVARS="-V MKMAGIC=yes -V MKLLVMCMDS=no" ./releasetools/x86_hdimage.sh -b
In order to build an image with ASR randomization, including four additional ASR-rerandomized versions of each system service, use the following build variables:
$ BUILDVARS="-V MKASR=yes -V ASRCOUNT=4" ./releasetools/x86_hdimage.sh -b
Obviously, all variables shown above can be combined as appropriate. The author of this document has used the following command line on several occasions:
$ CC=clang CXX=clang++ JOBS=4 BUILDVARS="-V MKASR=yes -V ASRCOUNT=2 -V MKLLVMCMDS=no" ./releasetools/x86_hdimage.sh -b
After the first run, the build system will perform recompilation of only the parts of the source code that have changed, and should not take nearly as long to run as the first time. In case of unexpected problems when rebuilding, it may be necessary to throw away the previously generated objects and rebuild the MINIX3 source code in its entirety. This can be done by going to the top-level
obj.i386 directory and deleting all files and directories in there, except the
tooldir.{yourplatform} subdirectory. Fully rebuilding the MINIX3 source code will take longer than an incremental rebuild, but since the crosscompilation toolchain is left as is, it will still be nowhere close as long as the first run.
As explained in more detail on the crosscompilation page, it is also possible to rebuild particular parts of the system without going through the entire “make build” process. This involves the use of the
nbmake-i386 tool and generally requires a good understanding of the compilation process.
The x86_hdimage command produces a bootable MINIX3 hard disk image file. The generated image file is called
minix_x86.img and located in the root of the MINIX3 source tree -
minix-src in our examples. Once an image has been generated, it can be run. The most convenient way to run the image is to use qemu/KVM. This can be done using the command as given at the end of the x86_hdimage output.
While explaining the use of qemu is beyond the scope of this document, it may be useful to look into the
-append,
-curses, and
-serial file:.. qemu command line arguments. The following command line will launch qemu with KVM support (remove
--enable-kvm to disable KVM support), a curses-based user interface, and system output redirected to a file named
serial.out:
$ cd /home/user/minix-liveupdate/minix-src $ (cd ../obj.i386/destdir.i386/boot/minix/.temp && qemu-system-i386 --enable-kvm -m 256 -kernel kernel -initrd "mod01_ds,mod02_rs,mod03_pm,mod04_sched,mod05_vfs,mod06_memory,mod07_tty,mod08_mib,mod09_vm,mod10_pfs,mod11_mfs,mod12_init" -hda ../../../../../minix-src/minix_x86.img -curses -serial file:../../../../../minix-src/serial.out -append "rootdevname=c0d0p0 cttyline=0")
Extra boot options can be supplied in the (space-separated) list that follows the
-append switch. For example, adding
rs_verbose=1 will enable verbose output in the RS service, which is highly useful for debugging issues with live update.
The following commands can be used to obtain and build a MINIX3 system that supports live update and live rerandomization, including three alternative rerandomized versions of all system services, in addition to the randomized standard ones:
$ export CC=clang CXX=clang++ JOBS=8 $ cd /home/user/minix-liveupdate $ git clone git://git.minix3.org/minix minix-src $ cd minix-src/minix/llvm $ ./generate_gold_plugin.sh $ cd ../.. $ BUILDVARS="-V MKASR=yes -V MKLLVMCMDS=no" ./releasetools/x86_hdimage.sh -b
The entire procedure will typically take about 30GB of disk space and several hours of time.
Sometime later, the following steps can be used to update the installation to a newer MINIX3 version:
$ cd /home/user/minix-liveupdate/minix-src $ git pull $ CC=clang CXX=clang++ JOBS=8 BUILDVARS="-V MKASR=yes -V MKLLVMCMDS=no" ./releasetools/x86_hdimage.sh -b
In contrast to the initial run, the entire update procedure should take no more than an hour.
Once an instrumented MINIX3 system has been built and started, it should be ready for live updates. MINIX3 offers two scripts that make use of the live update functionality: one for testing the infrastructure, and one for performing runtime ASR rerandomization. In addition, the user may perform live updates manually. In this section, we cover both parts.
The commands in this section are to be run within MINIX3, rather than on the host system. They must be run as root, because performing a live update of a system service requires superuser privileges. These two things are reflected by the
minix# prompt used in the examples below.
The MINIX3 distribution comes with two scripts that can be used to test and use the live update and rerandomization functionality. The first one is testrelpol. This script may be used for basic regression testing of the MINIX3 live update infrastructure. The second one is update_asr. This command performs live rerandomization of system services at runtime.
The MINIX3 test suite has a test script that tests the basic MINIX3 crash recovery and live update functionality. The script is called testrelpol and can be found in
/usr/tests/minix-posix:
minix# cd /usr/tests/minix-posix minix# ./testrelpol
For its live update tests, this script does not use the magic framework for state transfer at all. Instead it uses identity transfer which performs a basic memory copy between the old and the new instance. As a result, the testrelpol script should succeed whether or not services are instrumented. However, it may not work reliably on MINIX3 systems that are not built for magic instrumentation (i.e., built with neither
MKMAGIC=yes nor
MKASR=yes).
As we have shown before, the
MKASR=yes host-side build variable performs the build-time preparation of a MINIX3 system for live rerandomization. Complementing this, the run-time side of the live rerandomization is provided by means of the update_asr command. The update_asr command will update system services to their next pregenerated ASR-rerandomized version, using a cyclic system. Live rerandomization is not automatic, and thus, the MINIX3 system administrator is responsible for running the update_asr command at appropriate times.
By default, the update_asr command performs one round of ASR rerandomization, updating each service to its next version:
minix# update_asr
By default, this command will report errors only. More verbose information can be shown using the
-v switch:
minix# update_asr -v
For further details about this command, see the update_asr(8) manual page.
Aside from providing actual security benefits, the update_asr script is the most complete test of the live update and rerandomization functionality at this time. It uses the magic framework for state transfer, with full relocation of all state, and it applies the runtime ASR features. As of writing, it runs in the default qemu environment without any errors or subsequent issues.
The only aspect that is not tested with this command, is whether ASR rerandomization is effective, that is, whether all parts of service address space were properly randomized by the asr pass. After all, ASR rerandomization between identical service copies works just as well, but provides substantially fewer security guarantees. Developers working on the asr pass are encouraged to verify its effectiveness manually, for example using nm(1) on generated service binaries on the host side.
RS can be instructed to perform live updates through the service(8) command, specifically through its service update subcommand. This command is also used by the automated scripts. For a full overview of the command's functionality, please see the service(8) manual page as well as the command's output when it is run with no parameters.
In its most fundamental form, the service update command will update a running service, identified by its label, to a new version provided as an on-disk binary file. It is however also possible to tell RS to update the service into a copy of itself. In addition, various flags and options can be used for fine-grained control of the live update action. The basic syntax to perform a live update on a single system service is as follows:
minix# service [flags] update [self|<binary>] -label <label> [options]
Through various combinations of this command's parameters, MINIX3 basically supports four types of updates, representing increasingly challenging conditions for the overall live update infrastructure in general, and state transfer in particular. We will now go through all of them, and explain how they can be performed. For more details regarding what is actually going on below the surface, please consult the developers guide section of this document.
The first update type is identity transfer. In this case, the service is updated to an identical copy of itself, with all functions and static data in the new instance located at the exact same addresses as the old instance. Identity transfer bluntly copies over entire memory sections at once, thus requiring no instrumentation at all. This makes it suitable for testing of the MINIX3-specific side of the live update infrastructure, hence its use in the
testrelpol script. Identity transfer is the default of the service(8) command when “self” is given instead of a path to a new binary:
minix# service update self -label pm
This will perform an identity transfer of the PM service. Identity transfer should work for literally all MINIX3 system services. As mentioned, it is guaranteed to work only when the system was built with
MKMAGIC=yes, although it will mostly work on systems built without magic support as well. It works regardless of whether the target service was instrumented with the magic framework (or ASR).
If the live update is successful, the service(8) command will be silent, but RS will print a system message that the update succeeded:
RS: update succeeded
If the system was started on qemu with
OUT=F, this message will end up in
serial.out. Otherwise, the message should show up in the MINIX3 system log (
/var/log/messages) and possibly on the first console.
If the live update fails, RS should print an error to the system log, and service(8) will complain. In order to debug such failures, it may be useful to enable verbose mode in RS, buy starting the system with
rs_verbose=1 as shown earlier.
The second update type is self state transfer. Self state transfer also performs an update of a service into an identical copy of itself, but instead uses the state transfer functionality of the magic framework. Thus, self state transfer requires that the service be instrumented properly. This update type can be used to test whether a service's state can be transferred without problems. Please note that many of the points covered here also apply to the remaining two update types, as all three are using the state transfer of the magic framework.
Self state transfer is performed by supplying the
-t flag along with “self” to the service update command:
minix# service -t update self -label pm
This command will perform self state transfer of the PM service. The libmagicrt state transfer routine in the new service instance will print additional system messages while it is running. Upon success, the system output will look somewhat like this:
total remote functions: 57. relocated: 54 total remote sentries: 186. relocated normal: 84 relocated string: 101 total remote dsentries: 5 st_data_transfer: processing sentries st_data_transfer: processing dsentries st_data_transfer: processing sentries st_data_transfer: processing dsentries st_state_transfer: state transfer is done, num type transformations: 0 RS: update succeeded
If the state transfer routine is not able to perform state transfer successfully, it will print messages that start with
[ERROR]. RS will then roll back the service to the old instance, and both RS and service(8) will report failure. Self state transfer should succeed for all MINIX3 system services that have been built with bitcode and instrumented with libmagicrt and the magic pass. As of writing, there are no system services for which self state transfer is known to result in
[ERROR] lines and subsequent live update failure. However:
-stateoption. This currently applies to all services that make use of userspace threads, namely the VFS, ahci, and virtio_blk services. These services must be updated using quiescence state 2 (request free) rather than state 1 (work free):
minix# service -t update self -label vfs -state 2
Omitting the appropriate state parameter may result in a crash of the service after live update. At the moment, the update_asr(8) script has hardcoded knowledge about these necessary states. None of this is great, and we will be working towards a situation where the default state will not result in a crash - see the section on open issues further below.
-maxtimeoption to service(8):
minix# service -t update self -label vfs -state 2 -maxtime 120HZ
The maximum time is specified in clock ticks by default, but may be given in seconds by appending “HZ” to the timeout. The latter may sound confusing and it is, but the original idea was supposedly that the number of seconds is multiplied by the system's clock frequency, also known as its HZ setting. The above example allows the live update of VFS to take up to two minutes.
The third update type is ASR rerandomization. Like self state transfer, ASR rerandomization uses the magic framework to perform state transfer. In this case, the service performs state transfer into a rerandomized version of the same service. This involves specifying the path to a rerandomized ASR binary to the service(8) command, as well as the
-a flag. The
-a flag tells the new instance to enable the run-time parts of rerandomization during the live update.
minix# service -a update /service/asr/pm-1 -progname pm -label pm
In a system that has been built with ASR rerandomization, the (randomized) base service binaries are located in
/service and the (randomized) alternative service binaries are located as numbered files in
/service/asr. As mentioned before, the update_asr(8) command can be used to perform these updates semi-automatically.
Compared to self state transfer, ASR rerandomization comes with one extra restriction: the VM service cannot be subjected to forms of state transfer more complicated than self state transfer. For this reason, VM is also skipped by the update_asr(8) command. We will explain the restrictions regarding the VM service in the developers guide.
The final update type is a functional update. Compared to self state transfer, ASR rerandomization relocates code and more data. However, for ASR rerandomization, there are still fundamentally no differences between the old and the new version of the service. In contrast, in the case of a functional update, the service performs state transfer into a new program. While this new program is typically highly similar, it may be different from the running service in various ways.
In terms of the service(8) command, such functional updates can be performed by simply using service update with a new binary. For example, one could test a new version of the UDS (UNIX Domain Sockets) service, without installing it into
/service yet, and without affecting its open sockets:
minix# service update /usr/src/minix/net/uds/uds -label uds
The possibility of actual differences between the old and new service versions adds an extra dimension for the state transfer. Additional state transfer problems can be expected in this case, and must be dealt with accordingly. The developers guide will (eventually) elaborate on this point.
Similarly, depending on the nature of the update, the update action may require a specific state of quiescence. Taking UDS as an example, an update may change file descriptor transfers over sockets, in which case the update may impose that no file descriptors be in flight at the time of the update. The old instance of the service must support this as a custom quiescence state. This custom state can then be specified through the
-state option of the service update command.
Since the live update functionality is relatively new for MINIX3, we do not yet have much experience with the practical side of performing functional updates to services. This document will be expanded as we gain more insight into the common usage patterns of live update. Stay tuned!
From the user's perspective, updating multiple services at once is not much more complex than updating a single service. First, a number of service update commands should be issued, just as before, but each with the
-q flag added:
minix# service -q -t update /service/pm -label pm minix# service -q -t update /service/vfs -label vfs -state 2
Then, the entire update can be launched with the service sysctl upd_run command:
minix# service sysctl upd_run
The RS output will be much more verbose in this case. Note that timeouts are still to be specified on a per-service basis, rather than for the entire update at once. If necessary, any queued service update commands may be canceled with the upd_stop subcommand:
minix# service sysctl upd_stop
This will cancel the entire multicomponent live update action.
This part of the document provides in-depth information for developers. We start with information for system service developers, explaining how to support live update for a newly written service. This requires limited understand of the details of the live update infrastructure, and is therefore a somewhat separate section.
The rest of the developers guide is targeted towards people who maintain the live update infrastructure. We first cover some of the theoretical and practical aspects of the live update approach and infrastructure on MINIX3. We then elaborate on several practical aspects related to state transfer using the magic framework, including how to prevent and resolve state transfer issues.
This section is for writers of system services. We cover two aspects: general requirements for live updates, and specifying custom live update quiescence states.
In by far most cases, allowing future live updates on a new service requires no action at all from the service developer. That is, if the service has been written properly, it can also be updated. Specifically, a service can be updated if it meets these conditions:
The first three points are required for all services in any case, and are not specific to live update. These points are therefore covered better on other pages, in particular those on programming device drivers on MINIX3 and the System Event Framework API (warning: currently outdated). We do explain the reason behind these three points in detail later on.
Only the fourth point is specific to live update, and is relevant only to a small subset of services. This point is covered in more detail in the “State transfer in practice” section below. Specifically, as a service developer, you will want to verify that your new service does not suffer from potential issues with long-running memory grants, userspace threads, and physically unmovable memory. Then, you will want to test self state transfer on your service, and resolve any state transfer errors that come up. Only in these cases does the SEF live-update API (that is, the sef_*_lu_*(3) calls) become relevant. We do not elaborate on most of the SEF API in this document.
In certain cases, a service may have to meet custom requirements before it is allowed to be updated. This depends on both the service and the update. We previously gave an example regarding the UDS service and transferring file descriptors before. As another example, an update that affects message protocols may have to ensure that the service has no outstanding requests to other services using that protocol. As yet another example, certain drivers may want to avoid being updated while certain types of DMA are ongoing, etcetera.
It is up to the writer of the service to implement any such custom quiescence states, assigning a number to each of them. It is then up to the system administrator to supply such a state with the service update command, using the
-state <number> option. Some of the quiescence states are predefined; others must be defined by the service developer explicitly. The following states are defined:
SEF_LU_STATE_WORK_FREE): work free. This state ensures that the service is not currently performing any work. The fact that the service is being prepared at the time of verifying the quiescence state implies that it is not doing any other work, and thus, SEF is hardcoded to accept updates in this state. The service developer can not override the check for this state.
SEF_LU_STATE_REQUEST_FREE): request free. This state ensures that the service is not currently processing any requests from other services. The state is not valid by default, and may be implemented by the service writer.
SEF_LU_STATE_PROTOCOL_FREE): protocol free. This state ensures that the service is not currently engaged in any protocol exchange with other services. The state is not valid by default, and may be implemented by the service writer.
SEF_LU_STATE_CUSTOM_BASE+n): custom states. These states may be used by services to define their own custom states. The namespace is per-service, so each service may define its custom states with numbers starting from 7 (
SEF_LU_STATE_CUSTOM_BASE+0).
Thus, a service writer may want to implement states 2, 3, and/or any additional states starting from 7. This involves two necessary parts, and a third optional part.
First, the service must use the sef_setcb_lu_state_isvalid(3) SEF API call to specify a callback routine which specifies whether a particular state is valid for the service. In order to allow for states 2 and 3, but not any custom states, the standard sef_cb_lu_state_isvalid_standard(3) SEF callback routine may be given:
sef_setcb_lu_state_isvalid(sef_cb_lu_state_isvalid_standard);
The service would typically issue this call before calling sef_startup(3). In order to allow for additional custom states, a custom callback routine must be supplied:
sef_setcb_lu_state_isvalid(my_state_isvalid);
This routine has the signature
int my_state_isvalid(int state, int flags), and will be called when a live update is initiated through service(8). As its most important parameter,
state is the requested quiescence state. The
flags parameter contains update flags and is typically unused. The routine must return
TRUE if the state is valid for the service, and
FALSE otherwise. Most services will want to allow the standard states as well as any custom states:
#define MY_CUSTOM_STATE_0 (SEF_LU_STATE_CUSTOM_BASE+0) #define MY_CUSTOM_STATE_n (SEF_LU_STATE_CUSTOM_BASE+n) return SEF_LU_STATE_IS_STANDARD(state) || (state >= MY_CUSTOM_STATE_0 && state <= MY_CUSTOM_STATE_n);
Second, the service must use the sef_setcb_lu_prepare(3) SEF API call to specify a callback routine which verifies whether the service accepts a live update for a particular state, typically also before calling sef_startup(3):
sef_setcb_lu_prepare(my_lu_prepare);
This routine has the signature
int my_lu_prepare(int state), and will be called when a live update is initiated through service(8), after ensuring the given state is valid. Again,
state is the requested quiescence state. The function must return
OK if the live update can proceed in this state, and
ENOTREADY otherwise. It should check the standard states and/or any custom states, typically in a switch statement.
Third, the service may optionally provide a quiescence state debugging function through the sef_setcb_lu_state_dump(3) SEF API call. The given callback routine has the signature
int my_lu_state_dump(int state) and should use the sef_lu_dprint(3) printf-like function to print information about the given quiescence state and its current internal state as appropriate, using newline-terminated lines.
We now get into the details of the live update infrastructure. For many parts of the story, it may be useful to take a look at the actual source code as well. In this section we give a quick overview of what parts of the source code are where, and what they do.
The LLVM instrumentation passes are located in
minix/llvm of the MINIX3 source code, along with generate_gold_plugin.sh script described in the users guide. The following relevant LLVM passes are located in
minix/llvm/passes:
In addition to the passes, the following pieces of system functionality are especially important for live update:
minix/lib/libmagicrt.
minix/lib/libsys/sef*.cfiles.
minix/servers/rs. RS uses live update functionality implemented in the kernel, located in
minix/kernel, and VM, located in
minix/servers/vm.
We now elaborate on various MINIX3-specific aspects that are important to understand regarding live update. We describe the live update procedure, show the consequences of the quiescence approach, list the properties of various process memory sections, describe the two supported types of state transfer, and elaborate on the exceptions to the general model for various core system services.
We first describe the live update procedure in more depth.
In general, properly achieving quiescence is one of the main challenges for a live update system. For example, if a live update changes the implementation of a particular function, the component being updated must not be executing that function at the time of the live update - if it is, the live update will most likely result in a crash of the component. In MINIX3, the quiescence issue is resolved in a way that leaves little room for problems, by exploiting MINIX3's message-based nature. In essence, all the MINIX3 services consist of a main message loop that repeatedly receives a message and processes this message. MINIX3 supports no kernel threads, and thus, the MINIX3 services have no internal CPU-level concurrency. As a result, a message can be used to enforce quiescence.
MINIX3 live updates are orchestrated by the RS (Reincarnation Server) service. The administrator of the system first compiles a new version of the service into an executable on disk, and then instructs RS to update a particular running system service into the new version, through the service(8) utility. RS starts by loading the new version of the service as a new service process, without letting it run. Thus, there are temporarily two instances of the service: the old instance, which is still running, and the new instance, which contains the new code but not yet any of the necessary state.
RS then asks the old instance of the service to prepare to be updated, by sending a prepare request message to it. At the moment that the service receives and processes the preparation message, it is by definition in a known state, as it cannot also be doing something else at the same time. While this is a good start for quiescence, the service may have to meet additional requirements regarding its current activity, depending on the service and the type of live update. The administrator provides the intended quiescence state for the live update when starting the update, and the service itself determines whether or not it is ready when handling the prepare message. If the service decides that it does not meet the given quiescence requirements, the live update is aborted.
However, if the old instance does meet the requirements, it acknowledges that it is ready by sending a ready message to RS, blocking on receipt of a reply from RS. Thus, the old instance is effectively stopped in a known state. In order to maintain the externally visible state (most importantly, the communication endpoint) of the service being updated, the process slots of the old and the new service instances are swapped. The new instance, now in the original process slot, is then allowed to run. Upon startup, the new instance finds out from RS that it is the new instance of an old, stopped process, and attempts to perform state transfer from this old process into itself.
State transfer requires transfer of all individual pieces of data from the old to the new process, possibly to a new location. This is performed by the magic framework. In a nutshell, the magic state transfer approach relies on having a full view of all the individual pieces of data that make up the process, along with type information about the data, including for example structure layouts and types of pointers. For static data, this information is generated by the magic pass through static analysis performed at compile time, and included with the service binary. For dynamic data, the information is collected and maintained by the magic runtime library attached to the service. The end result is that the state transfer framework knows about all global variables and functions, and for each pointer, what type of data the pointer points to.
This knowledge, in addition to full access to the memory of the old instance through a special memory grant, allows the libmagicrt state transfer procedure in the new instance to iterate over all data of the old process. This procedure recursively follows any pointers it encounters, and pairs each piece of data with the corresponding piece of data in the new process, copying over and adjusting (as necessary) the data for the new layout as necessary. In certain cases, the state transfer system may not be able to pair all pieces of data, or deal with all pointers. In that case, state transfer fails. Annotations in the service source code, as well as custom data transfer methods, can be provided in order to aid the state transfer process.
Regardless of whether state transfer succeeded or failed, the new instance sends the result of the state transfer to RS using an init request message. If state transfer succeeded, RS allows the new instance to continue to run, and kills the process of the old instance. If the state transfer fails, RS again swaps the process slots of the old and the new instance, allows the old instance to run again, and kills the new instance. In both cases, RS communicates the result to the service(8) utility as well, ultimately letting the system administrator know about the outcome of the live update.
For multicomponent live updates, all affected services are first brought into the ready state, after which they are all updated. Any service failing to get ready in the preparation phase will cause an abort of the entire update, and any service failing the state transfer phase causes a rollback of the entire update.
Updating the RS and VM components requires various deviations from the procedure sketched above. In addition, support for live updating the VM service is limited. We elaborate on these points later on.
We describe the quiescence model in a bit more detail, in order to make two points: 1) the implementation of system services must follow a basic standard structure in order to allow for live update, and 2) the process stack is and can be disregarded for the purpose of state transfer.
The following piece of pseudocode represents a simplified and flattened version of the general structure of each system service:
main: # initialization receive INIT message from RS if INIT message requests a FRESH start: perform service initialization if INIT message requests a LIVE UPDATE start: perform state transfer send result of performed action to RS # there should be nothing else here # the main message loop while true: receive message if message from RS and message is PREPARE: # for simplicity, we are always ready send READY message to RS receive response message from RS # if we get here, the live update has failed continue handle message
As can be seen, the service's initialization code starts by learning from RS what type of initialization it should perform. This can be either fresh initialization of the system service, or state transfer for the purpose of live update (for simplicity we disregard crash recovery). If the service is started anew, typically during system boot, it will perform the service initialization. Such fresh initialization typically consists of initializing global variables, performing initialization-only procedures, etcetera. In contrast, if a new service instance is started for the purpose of live update, it will skip the fresh initialization and instead perform state transfer from the old instance.
In practice, all interaction with RS is implemented in the System Event Framework (SEF) library code. The service-specific actions such as the fresh initialization action are implemented as callbacks from SEF. In the case of fresh initialization, the service is to provide a callback function to SEF using the sef_setcb_init_fresh(3) API call. The default state transfer action for a live update start does not require code in the actual service at all.
If the service has initialization code that is called outside of the “fresh initialization” procedure, for example at the “there should be nothing else here” point, then this code will also be called in case of a live update, possibly undoing the effects of the state transfer. Therefore, services must perform initialization only from the designated initialization routines.
After either type of initialization, the service will enter the main message loop, where it will repeatedly receive a message and handle that message. If the received message is a prepare request from RS, then the service is about to be updated, and it sends a ready message to RS, blocking until it gets a response. If the live update is successful, this old instance will never get a response, and instead be killed.
As can be seen, in terms of the process stack of the service, the execution path from main() to the point where the service gets blocked receiving the ready response from RS (let's call this the quiescence point) is short and simple. As a result, if the state transfer procedure restored the new instance's stack and program counter to continue from the quiescence point, the result would essentially be the same as not doing so: in both cases, the new service would end up at the start of the message loop. Therefore, the MINIX3 state transfer approach chooses to disregard the execution context of the old process, thus obviating the need to transfer the stack altogether. This is viable only due to the well defined quiescence model.
However, it is possible that the functions leading up to the quiescence point, including the main message loop, have local variables on the stack that maintain long-running state. For example, the main() function could maintain a counter for the number of messages received so far. The values of such variables will be lost during the live update. If this were a major issue, the live update framework could be made to instrument the stack as well, but this could come at great cost since instrumenting only the stack of functions leading up to the quiescence point would be difficult. In practice, not having essential long-running variables in main() is rather simple, and we have not seen problems so far.
The address space of a process is typically made up of various memory sections with different purposes, and MINIX3 system services are no different. There are important differences between various sections when it comes to state transfer.
For a live update of the VM service, the last two points are different. We describe the exceptions for VM in a later section.
With this situation as a given, MINIX3 allows for two forms of state transfer: identity transfer, and state transfer by the magic framework. These forms of state transfer are covered in the next two sections.
The simple case is identity transfer. Identity transfer is a minimal state transfer approach that can only transfers state from an old instance to a new instance of exactly the same service, that is, a process with exactly the same address space layout and functionality. Identity transfer is also supported when the target service has not been instrumented, and in fact even when the system has not been compiled using LLVM bitcode altogether.
Since new instance is a newly started copy of the same service, it already has a text section that is identical to the old instance. As described, the stack section need not be transferred, and the mmap section is inherited automatically.
Therefore, identity transfer is concerned with the data and heap sections only. The new instance's identity transfer procedure starts by copying over the old instance's entire data section to itself. This includes the variable that contains the size of the old instance's heap (
_brksize). The identity transfer procedure then calls brk(2) to allocate a heap for itself which is just as large, and copies over the old instance's entire heap section it itself as well. The identity transfer procedure is implemented in the System Event Framework (SEF) as part of libsys.
If the system is not built with
MKMAGIC=yes, which means that
_MINIX_MAGIC is not defined, then the mmap section of the process is not well delineated and may in fact overlap with other memory areas. This is intentional, as it ensures that for such a set-up, the address space layout of services is not unnecessarily restricted and services can use the full address space for, say, a page cache. However, as a result, some memory-mapped areas may not be mapped into the new process, possibly leading to segmentation fault after the live update. Therefore, even identity transfer is not expected to be reliable on a system not built with
MKMAGIC=yes. Eventually, MINIX3 should be changed to use another approach for transferring memory-mapped regions to the new process altogether, which is either not based on ranges or not the default at all. See also the section on open issues in this document.
The other case is state transfer by the magic framework. This type of state transfer is used by the self state transfer, ASR rerandomization, and functional update update types as covered in the users guide. This form of state transfer relies on the magic pass and library to implement instrumentation and runtime support for state transfer. Again, state transfer is performed by the new instance of the service, using full access to the address space of its old instance.
The magic framework's state transfer procedure transfers data objects one by one. This includes all static objects. In this context, an object may for example be one global variable. The actual transfer of an object is not a simple memory copy; it involves analyzing any pointers in the object and adjusting these pointers as appropriate to match the address layout of the new instance.
The state transfer procedure also transfers dynamic data objects, which are located in the heap and mmap sections of the old instance. In essence, the procedure recreates the heap and mmap sections during the state transfer, by allocating new heap or mapped memory for each dynamic object, and then transferring its actual contents. This again includes pointer analysis and adjustment. Here, one object is one piece of memory created by a call to malloc(3) or mmap(2), for example.
Since MINIX3 already transfers the mmap section to the new instance automatically, the state transfer framework starts by unmapping all memory-mapped areas that it knows it will recreate. However, since some memory areas (the aforementioned memory-mapped I/O and DMA memory) cannot be recreated by the magic framework, these are not destroyed and recreated. These areas are called special, out-of-band memory. The service has to tell the magic runtime library about special memory areas. For the two common ways of allocating such memory, alloc_contig(3) and vm_map_phys(2), this is done automatically by libsys.
Out-of-band memory is seen as opaque, physically and virtually unmovable memory, and ignored entirely for the purpose of state transfer. Thus, if a piece of out-of-band memory contains a pointer to a piece of memory that is not marked as out-of-band, this pointer will be missed during state transfer. For the aforementioned (memory-mapped I/O and DMA) memory types, this is not a problem.
The default of inheriting the entire mmap section leads to the situation that if the magic framework misses any memory-mapped areas for any reason, these will effectively translate to a memory leak in the new instance. Currently, one such memory leak is addressed explicitly: the page directory that is allocated with mmap(2) internally by the libc malloc code.
The state transfer procedure may fail if its analysis is not successful, in which the system will roll back to the old instance, and the live update fails. It is then up to the programmer to deal with such problems. This may involve annotating source code, for example to instruct the state transfer procedure to ignore certain pointers, or to copy over certain data as is. It may involve adding special state transfer routines to libmagicrt, which deal with fundamentally problematic cases such as unions. In rare cases, it may involve adapting source code to avoid state transfer problems. We discuss all this in more detail later.
In the case of self state transfer, all static objects will have the same location in both the old and the new instance. However, due to their dynamic recreation, the addresses of dynamic objects may change during self state transfer.
In the case of ASR rerandomization, not just the dynamic part, but also the static part of the address space will have objects that are relocated between the old and the new instance. In addition, ASR rerandomization permutes the order in which the old instance's dynamic objects are allocated in the new instance. Finally, the asr pass may insert padding which may expose wrong assumptions about alignment of various buffers. Thus, while live rerandomization is a security feature, in practice it may expose not only additional problems with state transfer, but also bugs in the service itself.
In the case of a functional update, the new instance may be fundamentally different from the old instance. Unlike the previous cases of state transfer, such live updates may involve functions and global variables that are added or removed, thus causing problems in the pairing part of the state transfer. The programmer may have to provide explicit state transfer routines in order to deal with these problems.
While MINIX3 allows all of its services to be updated, certain services require special exceptions to allow for live updates, because they are crucial to the live update process itself. These services are RS and VM. This section elaborates on the exceptions made for RS and VM, and explains why VM in particular cannot be updated arbitrarily.
TODO
MINIX3 has limited support for performing a live update of the VM (Virtual Memory) service. There are two reasons why VM is a special case. First, VM provides essential memory management and page fault handling functionality to the other system services. Thus, the live update must ensure that none of that functionality is required during the course of a live update that includes VM. Second, VM's core data structures include page tables. If these page tables are changed during a live update, it may be impossible to perform a proper rollback.
During normal operation, VM may allocate memory for itself. VM has both a heap and dynamic pages, implementing special local versions of brk(2) and mmap(2) to support this. In particular, page tables are stored in dynamically allocated memory, effectively in VM's mmap section. For VM, the live update procedure must therefore include the transfer of such dynamic state from the old to the new VM instance.
Since page tables cannot simply be copied, they are made visible to the new instance by mapping the old instance's dynamic memory ranges directly into the new instance's address space. That means that any changes made to the dynamic data structures by the new instance (page tables included) becomes visible to the old instance after a rollback. However, the two instances do each have their own static memory (i.e., text and data sections, as well as a preallocated stack). Thus, any changes to dynamic memory made by the new instance, would create a potential mismatch between the static and dynamic memory in the old instance after rollback.
Therefore, in order to allow for rollback, VM must not make any changes to its dynamic memory during the live update. That also means that it may not allocate memory during the live update, not for other processes and not for itself. This situation leads to the following exceptions:
Overall, it should be clear that live update for the VM service is rather brittle. Eventually, a full revision of the live update approach for VM will have to reveal whether some or all of the current restrictions can be lifted.
In this section, we elaborate on some of the practical details of the state transfer of the magic framework, mainly aiming to allow developers to resolve real-world state transfer failures.
We do not get into most of the theoretical side of the state transfer, and we skip over many other practical details. Interested readers are advised to read the published work of Cristiano Giuffrida - see the “Further reading” section at the bottom of this document.
The magic framework keeps track of each static object of data using a sentry (“state entry”) data structure. The framework keeps track of each dynamic object of data using a dsentry (“dynamic state entry”) data structure, which itself has an embedded sentry data structure. The magic pass installs libmagicrt wrappers around memory allocation routines so that it can allocate extra memory to store the dsentry metadata right before the actual memory object. Special, out-of-band memory regions are maintained in obdsentry (“out-of-band dynamic state entry”) data structur. Since no extra memory can be allocated next to the actual memory object in this case, obdsentries themselves are (currently) stored as static data as part of libmagicrt's own state.
The magic framework also uses the concept of a selement (“state element”), which is a particular element within a state entry; for example, it can be one particular field in a structure. State is transferred one element at a time. If the state transfer procedure encounters a problem, it will report about the state element that is causing the problem.
Each pointer in the service process is expected to point a data type known to libmagicrt. All the possible data types that can be used by the service are enumerated through static analysis by the magic pass, and stored in a type table as part of the instrumented service. It may happen that one data type is cast to another, either in the source code of the service or as a result of the LLVM compilation and linking process. As a result, while the static analysis may conclude that a pointer is for one type, runtime state transfer may find that the pointer was (for example) allocated for another type. Normally, such mismatches would cause state transfer to fail, but casting makes this a legitimate case. Therefore, the magic framework has the notion of compatible types: if type A is cast to type B anywhere, type A is marked as a compatible type for type B, and finding type A when transferring data of supposed type B will not result in state transfer failure. The magic pass adds a list of compatible types to the service binary as well, all for use by libmagicrt at state transfer time.
In particular the analysis part of state transfer may not always succeed, for a variety of reasons. In particular, the state transfer framework has problems with unknown pointers, unions, and more generally cases of ambiguity. Such issues can often be resolved by the programmer through annotation in source code, which instructs the state transfer framework what to do with a particular variable. A variable can be annotated by prefixing either its type name (through
typedef) or its variable name with the annotation prefix followed by an underscore (e.g.,
noxfer_foo). The following annotation prefixes are supported by the magic framework.
messagetype. This data type contains a complicated union, and the quiescence model typically ensures that transferring this state is not necessary, as the service being updated is not involved in processing a message at the time of the update.
void *but may be used to store a small integer as well.
ixferand the pointer union(s) with
pxfer. This is indeed how
pxferis currently used in practice as well.
The transfer exception is applied to the type (or variable) with the annotation. For example, a noxfer typedef for a pointer to a structure will refrain from transferring that pointer:
typedef struct foo * noxfer_foo_ptr_t; /* annotate the pointer */ struct foo my_foo_struct; /* the structure will be transferred */ noxfer_foo_ptr_t my_foo_pointer = &my_foo_struct; /* the pointer will not be transferred */
However, a pointer to a noxfer typedef'ed structure will be transferred; the contents of the structure will not:
typedef struct foo noxfer_foo_t; /* annotate the structure */ noxfer_foo_t my_foo_struct; /* the structure will not be transferred */ noxfer_foo_t * my_foo_pointer = &my_foo_struct; /* the pointer will be transferred */
It is possible to enable debugging flags in libmagicrt such that it will print more details on how it handles annotated exceptions: in
minix/lib/libmagicrt/include/st/callback.h, change
ST_CB_DEFAULT_FLAGS from
(ST_CB_PRINT_ERR) to
(ST_CB_PRINT_ERR|ST_CB_PRINT_DBG). The debugging statements will be sent to the system log, and have a
[DEBUG] prefix.
Custom state transfer routines can be used in cases where annotation does not suffice.
TODO
There is currently one example case where a custom state transfer routine is used, namely for the
dsi_u union in the
struct data_store structure which is used by the Data Store (DS) service and defined in
minix/servers/ds/store.h. The custom state transfer routine is located in
minix/lib/libmagicrt/magic_ds.c, and provides the state transfer process with information as to which of the union's fields should be transferred.
In some cases, small adjustments must be made to a service in order to prevent issues with state transfer. These types of issues will not result in failure of the state transfer procedure; instead, they may result in a crash of the new instance after a seemingly successful live update. We cover three topics: memory grants, userspace threads, and physically unmovable regions.
One potential issue concerns memory grants. Each service has a memory grant table, which is an array of all the memory grants that allow other processes to read and/or write the service's memory. If the service has any grants active at the time of a live update, the grants should in theory be adjusted in accordance with any relocation of the memory pointed to by the grants.
However, the main union of the grant structure (
cp_grant_t, defined in
minix/include/minix/safecopies.h) is currently marked as ixfer, meaning it will be transferred as is. This is not a problem for grants that point to memory outside the process being updated, and that means that indirect and magic grants pose no problem for state transfer. It is however a problem for grants that point to memory inside the process being updated, that is, for direct grants.
For this reason, for a service that may potentially have direct grants active at the time of the live update, its writer has two options: 1) implement a custom state transfer routine for the
cp_grant_t structure in libmagicrt, thus resolving the problem described in this entire section altogether, or 2) prevent live updates of the service whenever the service has active memory grants. The first option is preferred. In any case, the potential consequence of doing neither is that the service ends up suffering from arbitrary memory corruption after a live update, since the transferred direct grant will point to the wrong memory location.
The live update system itself actually relies on the presence of a long-running direct grant, which provides access of the process's full address space to the process itself. The new instance uses this grant during a live update to access the memory contents of the old instance. Since the grant provides access to the process's entire address space, it does not suffer from the problem above.
Userspace threads pose a problem for state transfer as well. We have previously explained that the process stack of the old instance can be disregarded by the state transfer procedure because it is “naturally” recreated in the new instance. The same does not apply to the stacks of userspace threads, since stack variables are not tracked at run time: even though the threads' stacks are transferred to the new instance by the magic framework, they are seen as blobs of (typically) memory-mapped character arrays. The result is that any pointers on these stacks will not be known to libmagicrt and thus not be transferred properly. In addition, thread context (CPU register) state will typically be stored as an array of integers, and similarly end up being skipped by the state transfer procedure. The result is that while state transfer may (appear to) succeed, the service will crash after completion of the live update.
At this time, the recommended solution is for the service to shut down all threads explicitly before starting state transfer, and to recreate the threads both after successful live update and as part of a rollback. The service may refuse to be updated if any of its threads are in use and cannot be shut down. The last point requires that the service supply a custom callback routine to SEF to perform that check for a quiescence state other than the default, through sef_setcb_lu_prepare(3). In order to allow the use of a nondefault state, a sef_setcb_lu_state_isvalid(3) callback routine must be supplied as well. For VFS and libblockdriver, we have chosen the following approach:
sef_setcb_lu_state_isvalid(sef_cb_lu_state_isvalid_standard)is used to mark all standard quiescence states as valid, including
SEF_LU_STATE_REQUEST_FREEand
SEF_LU_STATE_PROTOCOL_FREE.
SEF_LU_STATE_REQUEST_FREEor the
SEF_LU_STATE_PROTOCOL_FREEstate, the function will first check whether all worker threads are idle. If they are not, it will return a failure, aborting the live update. If they are, it will shut them down and report success.
SEF_LU_STATE_REQUEST_FREEor
SEF_LU_STATE_PROTOCOL_FREE, the function recreates the worker threads. This ensures that worker threads are recreated in the old instance upon a rollback.
info→prepare_statewas either
SEF_LU_STATE_REQUEST_FREEor
SEF_LU_STATE_PROTOCOL_FREE, then it continues by recreating the worker threads. This ensures that the new instance has worker threads before it leaves the state transfer phase.
The result of this approach is that updates must be invoked with
-state 2 (request free) or
-state 3 (protocol free) in order to guarantee proper state transfer. As a sidenote, none of these issues are a problem for identity transfer, which should continue to work even with
-state 1 (work free, the default).
Another case where the programmer may have to ensure that state transfer does not result in problems that will surface only after the live update, is when a service uses memory areas that are physically unmovable. Such memory areas are typically in use for DMA purposes. If the state transfer procedure changes the physical location of the buffers, DMA may be performed from or to the original physical location, resulting in garbage and possibly arbitrary memory corruption. Such DMA areas must be marked as special out-of-band memory in libmagicrt, and unmarked when freed, using the sef_llvm_add_special_mem_region(3) and sef_llvm_del_special_mem_region(3) SEF calls. This is done automatically by the alloc_contig(3) and free_contig(3) wrapper routines, but must be done explicitly for memory allocated in different ways.
However, this is only necessary if DMA can happen across a live update. In cases where it is known that no DMA can possibly be ongoing during the live update, the regions are not actually physically unmovable, and therefore need not be marked as such. For example, this is the case for the file system buffer cache implemented in libminixfs. This library allocates and manages buffers without using physically contiguous memory and alloc_contig(3), instead using mmap(2) directly and requesting DMA I/O in page-sized chunks (in order to avoid DMA issues on ARM). Therefore, it would be affected by the above problem, were it not for the fact that all its block I/O calls are synchronous. Any future introduction of more asynchrony will turn this situation into a real problem for live update, though.
As we mentioned before, memory-mapped I/O poses a similar problem. However, the only way to map such I/O memory is currently through the vm_map_phys(2) and vm_unmap_phys(2) calls, of which the libsys wrappers automatically call the special-memory marking/unmarking functions as well.
If the magic state transfer procedure encounters problems, it will report failure, with details written to the system log entries using an
[ERROR] prefix. In this section, we cover a number of common reasons for state transfer to fail in practice, including some example errors and workarounds.
In order to know how to transfer a piece of memory, the magic runtime library must know about the data type associated to that piece of memory. If no type information is known for a piece of memory, it cannot be transferred. There are various reasons why libmagicrt might not have type information about a piece of memory. The simplest one is a case of a dangling pointer: a pointer that used to be valid at some point, but no longer is, because the memory pointed to has been deallocated. While the actual program may know not to use that particular pointer anymore, the state transfer routine does not have such knowledge. A typical error resulting from a dangling pointer may look like this, with some important parts of the output highlighted:
(parent=sbuf.1900354961, num=1, depth=0, address=0xdfb760a8, **name**=**sbuf**.1900354961, type=TYPE: (id=53 , name=, size=4, num_child_types=1, type_id=10, bit_width=0, flags(ERDIVvUP)=01010000, values=%%''%%, type_str=i8/**char%%*%%**))
(num=1, type=ptr, flags(DIVW)=1110, **value**=**0x080cb49f**, trg_name=, trg_offset=0, trg_flags(RL))=D0, ptr_found=1, **unknown_found=1**, violations=1)
In this case, the global variable sbuf (suffixed with a tag to make its name unique) is a char* pointer to location 0x080cb49f. Since the magic runtime library knows no type information about this target (trg) memory location, it marks the location with the placeholder type UNKNOWN_TYPE and aborts state transfer because an unknown type was found. Another example:
(parent=inode.3951291702, num=80, depth=2, address=0xdfbe3210, **name**=**inode.3951291702/4/i_data**, type=TYPE: (id=61 , name=, size=4, num_child_types=1, type_id=10, bit_width=0, flags(ERDIVvUP)=01010000, values=%%''%%, type_str=i8/**char%%*%%**))
(num=80, type=ptr, flags(DIVW)=1110, **value**=**0x08108098**, trg_name=, trg_offset=0, trg_flags(RL))=H0, ptr_found=1, **unknown_found=1**, violations=1)
In this case, the i_data field of the fifth element (/4/) of the global inode structure, also a char* pointer, is pointing to address 0x08108098 which is unknown to libmagicrt. The pointer address typically allows one to determine what kind of memory it is, by means of the memory sections of the process. In this particular example, the address was somewhat higher than the service's data end, thus suggesting the memory pointed to is heap memory. This matched with the source code of the service (PFS, the Pipe File Server), which dynamically allocates and frees the i_data buffers using malloc(3) and free(3).
It is up to the programmer of the service to ensure that the state transfer routine will not attempt to transfer a dangling pointer. This can be as simple as zeroing out the pointer after use, which is usually good practice anyway:
free(rip->i_data); rip->i_data = NULL;
That is the solution that we applied in both cases.
A similar problem occurs when a process has a pointer that is only valid in the address space of another process, or possibly the kernel. Unlike dangling pointers, such external pointers are never valid, and thus do not need to be transferred as pointers. The magic framework must be instructed to that end, for example using noxfer annotation. However, external pointers often end up in the local address space as a result of copying in entire structures at once (we already gave process tables as an example), in which case it may be necessary to use ixfer rather than noxfer. For example, the ProcFS (/proc File System) service has several instances of the following construction:
typedef struct mproc ixfer_mproc_t; static ixfer_mproc_t mproc;
In some cases, it may make more sense to zero out pointers instead. In other cases, we have changed code to retrieve not entire kernel tables but only specific values, or to use the kernel-mapped pages instead of copies of kernel structures to retrieve values. The magic runtime library already ignores pointers into kernel space (that is, 0xf0000000 and higher) altogether.
Theoretically it is possible that remote pointers end up being valid in the local address space by sheer luck. In known cases of copying in external pointers, it is best to not to rely on failures in the magic framework, but rather annotate the code in a proactive manner.
If a service uses weak symbols, the code and data pointed to by these weak symbols may not be included in the linked service object at the time that the instrumentation passes are run. These weak symbols will be resolved and included only after the instrumentation stage. This results in the situation that some of the code and data that is part of the service, will not have been analyzed by the magic pass. The result is a range of possible state transfer failures, including cases where pointers end up pointing to unknown static memory and cases where memory allocation is not properly instrumented, ultimately leading to pointers to unknown dynamic memory.
The following example is from the DS service, where its use of the weak aliases for regcomp(3) and regfree(3) resulted in regcomp's malloc(3) calls not being instrumented:
(parent=ds_subs.1944246923, num=9, depth=3, address=0xdfbe6108, name=**ds_subs.1944246923/0/regex/re_g**, type=TYPE: (id=18 , name=, size=4, num_child_types=1, type_id=10, bit_width=0, flags(ERDIVvUP)=00000000, values=%%''%%, type_str=opaque*))
(num=9, type=ptr, flags(DIVW)=1110, **value**=**0x08111000**, case, the pointer ds_subs[0].regex.re_g ended up pointing to the unknown heap-section value of 0x08111000. We worked around this issue by forcing DS to use the targets of the weak aliases, _regcomp and _regfree, rather than their original names, using Makefile hacks.
If the magic runtime library itself uses other library modules, for example from libc, and these modules are not already used by the service itself anyway, then the bitcode linker may not include them in the linked object on which the instrumentation passes are run. Again, this may result in various failures, and unknown pointers in particular:
(parent=_ctype_tab_, num=1, depth=0, address=0xdfb760a8, **name**=**_ctype_tab_**, type=TYPE: (id=204 , name=, size=4, num_child_types=1, type_id=10, bit_width=0, flags(ERDIVvUP)=11000000, values=%%''%%, type_str=i16/unsigned short*))
(num=1, type=ptr, flags(DIVW)=1110, **value**=**0x0809ccb6**, particular failure case, the global _ctype_tab_ variable pointed into another global variable, at location 0x0809ccb6 the data section. The other global variable was invisible to the magic pass, so no sentry object could be created for it. As a result, libmagicrt did not know about the target of the pointer. The _ctype_tab_ variable itself was used by the
<ctype.h> isalpha(3) (etc) set of macros from within libmagicrt. We worked around this issue by putting our own replacement set of macros in libmagicrt instead.
Yet another case that leads to invisibility of certain aspects is the direct inclusion of assembly code. Assembly code is machine code, not bitcode, and thus, the bitcode instrumentation passes will have problems processing them. Needless to say, the use of assembly code should be minimal throughout the source code. In cases where it cannot be avoided, custom solutions have to be found for any resulting state transfer problems. Fortunately, much of the assembly in use by services these days is the result of optimized str*(3) and mem*(3) functions, which require no special treatment for the purpose of state transfer.
Finally, we describe one class of state transfer failures which are the result of shortcomings in the magic instrumentation framework itself. LLVM bitcode has the notion of an opaque data type. The opaque data type is used for data of which the type has been declared but not defined, typically as a result of forward declarations of structures (
struct foo;). Instead of resolving these types after they have been instantiated, LLVM tends to cast between various data types which are identical except for the presence of opaque pointers. As a result, opaque pointers may show up in various places in linked bitcode.
The magic pass should mark all these practically identical data types as compatible types. However, due to the fact that the casts can take rather complex forms, this is not always happening. The result is that in some cases, state transfer may fail because libmagicrt erroneously detects an incompatibility between a pointer type and the type of data being pointed to. As an example, the following state transfer error was reported during state transfer of the PM service:
(parent=timers.515278380, num=1, depth=0, address=0xdfb760a8, **name**=**timers**.515278380, type=TYPE: (id=96 , name=, size=4, num_child_types=1, type_id=10, bit_width=0, flags(ERDIVvUP)=01000000, values=%%''%%, **type_str**={ $minix_timer tmr_next \2, tmr_exp_time i32/long unsigned int, **tmr_func opaque%%*%%**, tmr_arg { (U) $ixfer_tmr_arg_t ta_int i32/int } }*))
(num=1, type=ptr, flags(DIVW)=1110, value=0x08147460, trg_name=mproc, trg_offset=274616, trg_flags(RL)=D0, trg_selements=(**#2**|0: **1**|o=SELEMENT: (parent=mproc, num=0, depth=0, address=0x08147460, name=**mproc/143/mp_timer**, type=TYPE: (id=38 , name=minix_timer, size=16, num_child_types=4, type_id=9, bit_width=0, flags(ERDIVvUP)=00000000, values=%%''%%, names='minix_timer_t|minix_timer', **type_str**={ $minix_timer tmr_next { $minix_timer tmr_next \2, tmr_exp_time i32/long unsigned int, tmr_func hash_3792421438/*, tmr_arg { (U) $ixfer_tmr_arg_t ta_int i32/int } }*, tmr_exp_time i32/long unsigned int, **tmr_func hash_3792421438/%%*%%**, tmr_arg { (U) $ixfer_tmr_arg_t ta_int i32/int } })), **2**|o=SELEMENT: (parent=mproc, num=0, depth=0, address=0x08147460, name=mproc/143/mp_timer/tmr_next, type=TYPE: (id=37 , name=, size=4, num_child_types=1, type_id=10, bit_width=0, flags(ERDIVvUP)=00000000, values=%%''%%, **type_str**={ $minix_timer tmr_next \2, tmr_exp_time i32/long unsigned int, **tmr_func hash_3792421438/%%*%%**, tmr_arg { (U) $ixfer_tmr_arg_t ta_int i32/int } }*))))
(type=ptr, trg_flags(RL)=D0, ptr_found=1, **other_types_found=1**, violations=1)
In this case, the analysis failed on the global timers variable. The analysis dump shows that two matching types (#2) were found, both associated with the mproc[143].mp_timer structure field, but neither type matched the type of the pointer. A closer look at the textual representations of the pointer type (the type_str of the primary selement) and of the data types (the type_str of the target selements) reveals that there is only one difference between the two: the tmr_func field of the structure type to which the timers variable should point is an opaque pointer, whereas the same tmr_func field of the target structures is a particular function pointer (to a function referred to as hash_3792421438). The remainder of the types are the same.
The type strings are somewhat difficult to read. The asterisk at the end of a { structure } block indicates a pointer to this structure. In this case, the timers variable is a pointer to a minix_timer_t structure. The \n notation indicates type recursion of the type n levels up. In the type string of timers, the \2 after the tmr_next field indicates that it is again a pointer to minix_timer_t: one type level up is the structure itself, two type levels up is the pointer to the minix_timer_t structure. In this case there are no three levels up, but in other cases three levels up could for example be a pointer to a pointer to a structure, etcetera. Although irrelevant in this case, the name of each structure is prefixed with a dollar sign, and (U) denotes a union.
In this case, the analysis failed because it foudn different, incompatible, and therefore other types, even though the opaque pointer and the function pointer were really the same field types. A look at the corresponding declarations in
minix/include/minix/timers.h shows that there is indeed a forward declaration of
struct minix_timer which is the cause of LLVM's link-time introduction of casts. We resolved this case by extending the casting analysis of the magic pass to include casts of structures through function prototypes.
The following example also resulted from the same forward declaration of MINIX3 timer structures, this time in the sched (scheduling) service:
(parent=sched_timer.29458437, num=4, depth=1, address=0xdfbe70b0, **name**=**sched_timer.29458437/tmr_func**, type=TYPE: (id=17 , name=tmr_func_t, size=4, num_child_types=1, type_id=10, bit_width=0, flags(ERDIVvUP)=00000000, values=%%''%%, type_str=**opaque%%*%%**))
(num=4, type=ptr, flags(DIVW)=1110, value=0x08048dc0, trg_name=**balance_queues**.29458437, trg_offset=0, trg_flags(RL)=T0, trg_selements=(#1|0: 1|o=SELEMENT: (parent=???, num=0, depth=0, address=0x08048dc0, name=???, type=TYPE: (id=119 , name=, size=1, num_child_types=0, type_id=4, bit_width=0, flags(ERDIVvUP)=11000001, values=%%''%%, type_str=**hash_3792445575/**))))
(type=ptr, trg_flags(RL)=T0, ptr_found=1, **other_types_found=1**, violations=1)
In this case, the type mismatch was not between two structures that differed in opaque fields, but between two function pointers themselves: the function pointer in sched_timer.tmr_func, and the function it is pointing to, balance_queues. Registering these types as compatible would result in much more complexity in the magic pass, and likely still not resolve the more general problem of opaque pointers. This is currently one of the open issues, and we believe that another approach would be more viable; see below. In this particular case, it turned out that the sched service did not need to use timers at all, and we simplified it by getting rid of its use of timers altogether. Obviously, adapting the actual functionality of a service to allow for state transfer is not always an option, nor is it generally the right approach: the core code of system services should not have to be (re)written specifically to allow for state transfer.
In this section, we describe what we believe are currently the main open issues related to live update. For most issues, no active development is ongoing. We therefore invite any interested parties to work on resolving these issues, and welcome both inquiries and updates regarding the current status on both the MINIX3 newsgroup and info@minix3.org.
This section is roughly sorted by order of importance, starting with the most important issues.
As shown in the setup part of the users guide, the live update functionality requires that a a separate instance of the LLVM toolchain be built. Unlike the standard toolchain, this separate instance is suitable for Link-Time Optimization (LTO). It is built by
minix/llvm/generate_gold_plugin.sh, and placed in
obj_llvm.i386. The exact same LLVM 3.6.1 source code is used to compile both the LTO-enabled toolchain and the additional regular crosscompilation toolchain in
obj.i386, using the exact configuration flags. The separate compilation is necessary only because of a problem with makefiles.
NetBSD uses its own set of makefiles to build imported code using its own build system. MINIX3 imports this system, and thus also uses the NetBSD set of makefiles to build the LLVM toolchain. The problem is that these makefiles do not operate in the same way as LLVM's own set of makefiles, resulting in certain parts of the LLVM toolchain being built in a different way. The separate LLVM LTO toolchain build does use LLVM's own makefiles, thereby generating some missing pieces that are required for the live update instrumentation.
The solution here is to adapt the NetBSD set of makefiles to build LLVM in a way that is closer to LLVM's own makefiles, thereby generating all the necessary parts of the toolchain without the need to build LLVM twice.
As part of this, the generated instrumentation passes should not be placed in the
minix/llvm/bin subdirectory of the source MINIX3 tree. Instead, they should end up in an appropriate subdirectory of
obj.i386, thereby keeping the source directory clean.
A number of shortcomings in our instrumentation passes currently lead to potential problems at run time.
As shown in the developers guide, the magic instrumentation pass is not always capable of establishing that two different data types are in fact compatible, resulting in state transfer errors at run time. The main cause of these issues lies in LLVM's use of the opaque placeholder data type. We described the practical results of this in the earlier “Incompatible types” section.
This problem is a product of circumstances. Between LLVM 2.x and LLVM 3.x, a significant change was made in LLVM regarding the way that types are handled. In a nutshell, rather than unifying various instances of the same data type at compile time, LLVM 3.x keeps these instances as separate types, instead using bit casting between the types to resolve the resulting incompatibilities at link time. More details about this change can be found in the LLVM blog post LLVM 3.0 Type System Rewrite by Chris Lattner.
However, the magic framework was written for LLVM 2.x, and as a result, this problem was dealt with as an afterthought. The combination of the wildly varying forms that these bit casts can take, and the limited support for processing the bit casts in the magic pass, has created the situation that not all cases of identical types are properly registered as compatible types. As of writing, this has not yet been a real problem, but it is likely to become a problem in the future.
We believe that the right solution would be the introduction of a new type unification pass. This pass would unify all effectively-identical types in the module at link time, eliminating redundant types and bitcasts in the module. The pass could then be run before the magic pass. This would not only resolve the complete problem, but also free the magic pass of the burden to provide a complete system for enumerating compatible types. As a beneficial side effect, there would be a reduction in the amount of type state that needs to be included with the service, and a reduction in effort needed by libmagicrt to search through compatible types.
The ASR pass currently exempts all of the magic runtime library from rerandomization. This is highly problematic for the overall effectiveness of ASR: libmagicrt is in principle linked with all system services, thus providing any attacker with a well known, large, unrandomized set of code and data for use in an attack on any running service.
The exact reasons as to why this exception was made are currently unknown. However, if possible, this overall limitation should be resolved by either removing the exception or at least narrowing it to the exact scope of the problem.
The MINIX3 memory management, implemented in the VM service, currently has a number of significant limitations and missing features. Some of its problems are relevant for live update only. Other problems are merely becoming more visible as a result of enabling or using live update functionality.
As we already mentioned earlier, the transfer of memory-mapped pages requires that these pages be in a strictly delineated address range. This range may not overlap with any of the process's other sections' address ranges. The range is hardcoded globally, and thus, defined much more strictly than necessary for most service processes. Moreover, the definition indiscriminately affects all processes, including application processes. The result is that if the system is built with live update support, all processes are severely restricted in how much of their address space they can use for memory-mapped regions. Conversely, if the system is not built with live update support, even identity transfer may fail.
Another problem mentioned before, is the bulk transfer of all pages in the process's mmap section, regardless of whether the state transfer framework knows about them. This could easily lead to memory leaks due to transfer of untracked pages.
We believe that both points could be resolved with a system that does not automatically transfer memory-mapped pages from the old to the new instance, but rather performs such transfer on demand, so that the (identity or magic) state transfer routine can determine exactly what memory to transfer.
MINIX3 currently does not deal well with running out of memory. Most system services do not have preallocated pages in their heap, stack, and mmap sections. This may create major issues in low-memory situations. For example, if a service attempts to use an extra page of stack while the system has no free memory, the service will be killed, possibly taking down the entire system with it. Beyond VM freeing cached file system data when it runs out of memory, any sort of infrastructure to deal with this general problem is completely absent.
The live update and rerandomization support is making this situation even more problematic. The magic runtime library uses extra dynamic memory, and is not particularly careful about using preallocated memory where necessary. The ASR functionality increases memory usage even further. For example, its stack padding feature requires a considerable amount of extra stack space. The result is that there is now an increasingly large number of scenarios where out-of-memory conditions result in failure of running system services, and possibly the entire system.
Even though certain services should be rewritten to deal more gracefully with cases of dynamic memory allocation failure, the example of faulted-in stack pages illustrates that this is not a viable option in general. There has been a partial attempt to prepare file system service's buffer caches for having their memory stolen by VM at run time, but its implementation is, where present, deeply flawed, and will likely be removed altogether soon. Instead, we believe that the easiest solution for this problem is to let VM reserve a certain amount of memory exclusively for satisfying page faults and page-handling requests involving memory in system services.
In the meantime, it can be expected that test64 of the MINIX3 test set - the test case that tests one particular scenario of running out of memory - will causes test or system failure in an increasing number of cases. It may have to be removed from the default set of tests in the short term.
In addition, MINIX3 does not deal with running out of physically contiguous memory at all. Some services require blocks of physically contiguous memory for DMA purposes. VM currently has no way to recombine fragmented blocks of free memory into larger physically contiguous ranges. In addition, some services require memory that is located in the lower 1MB or 16MB of the physical system memory. The support in VM for obtaining memory in those ranges is very limited as well. Both of these cases may result in the inability for a system service to obtain its needed resources if it is not started immediately at system bootup time.
These problems are not particularly important for live update, since the new instance will inherit special memory from its old memory by default. They are important for crash recovery however, and they are known to cause failures in the
testrelpol test set on occasion.
Finally, support for setting or enforcing page protection bits is mostly missing in VM as well. The live update integration has resulted in one particular case where this is now a problem. The MINIX3 userspace threading library, libmthread, inserts a guard page at the bottom of each thread stack in order to detect stack overruns. The guard page was originally created by unmapping the bottom page of the stack, thus leaving an unmapped hole there. This approach worked, but was not ideal: the hole could potentially be filled by a separate one-page allocation later, thereby subverting the intended protection.
Since libmagicrt performs extra memory allocations, this problem is a bit more relevant for live update. For this and other reasons, the libmthread code was changed to reallocate the guard page with
PROT_NONE protection instead. Theoretically, this should work fine. In practice, since VM does not implement support for protection, the guard page is now simply an additional stack page. Thus, as of writing, the libmthread guard page functionality is broken.
Ideally, this issue would be resolved by implementing proper support for page protection in VM, including for example an implementation of mprotect(2).
We now list a number of other issues concerning the MINIX3 runtime infrastructure side of live update.
The case of userspace threads has shown that it may be not just useful, but actually necessary for certain services to provide their own handlers for checking, entering, and leaving a custom state of quiescence. These services may crash if the default quiescence state is used for a live update instead of the custom state. The result is the requirement that not just users, but also scripts - the update_asr(8) script in particular - be aware of specific services requiring custom quiescence state. This is inconvenient and dangerous.
The default quiescence state is currently hardcoded in the service(8) utility, in the form of
DEFAULT_LU_STATE in
minix/commands/service/service.c. Instead, we believe that the service should be able to specify its own default quiescence state, possibly using an additional SEF API call. It is not yet clear whether RS would need to be aware of the alternative quiescence state. If not, the translation from a pseudo-state to the real state could take place entirely in the service's own SEF routines. Otherwise, the SEF may have to send the default state as extra data to RS at service initialization time.
While the following issue is relevant more for crash recovery than for live update, it is included here because it affects the infrastructure supporting the
testrelpol script.
Each service effectively knows what its own crash recovery policy should be. Separately, procfs has a policy table with an entry for each service in
minix/fs/procfs/service.c, containing the same crash recovery policy information, for export to userland and
testrelpol in particular. This is effectively redundant information.
Ideally, each service would communicate its policy to RS. That information can then be used by procfs to expose the policy information to userland, thus eliminating the redundancy.
Earlier in this document, we have described the limitations of performing live updates on the VM service, as well as the reasons behind these limitations. Despite a large number of exceptions that allow VM to be updated at all, the resulting situation is that VM can still not be subjected to any meaningful type of update.
It is unclear whether all these limitations are fundamental, however. We believe it may be possible to restructure the VM live update facilities to resolve at least some of the limitations. For example, it might be possible to store the pagetables in a separate memory section, and make actual copies of all or most other dynamic memory in VM. The out-of-band region could then be limited to the pagetable memory, thus allowing for relocation of at least static memory. Furthermore, more explicit rollback support in the old VM instance might even allow changes to VM's own pagetable, thereby possibly allowing dynamic memory allocation during the live update. It remains to be seen whether any of this is possible in practice.
If process A is being updated, process B should temporarily not make use of process A's grants, because during the live update, those grants may be inaccessible, invalid, etcetera. The kernel currently has a simple way to enforce that rule, by responding to process B's safecopy kernel call with an
ENOTREADY error response whenever process A is being updated. The service-side libsys implementation of sys_*safecopy*(2) automatically suspends the calling service for a short while (using tickdelay(3)) and then retries the safecopy. This shortcut approach works, but it is not ideal: it should not be the responsibility of system services to determine when the safecopy can be retried again, and the approach could lead to starvation.
Instead, the kernel should block the caller of a safecopy call for the duration of its target's live update procedure, retrying the safecopy operation and unblocking the caller only once the target is no longer being updated. A proper implementation of this functionality requires several cases to be covered: indirect grants, either the granter or the grantee being terminated or having its process slots swapped, etcetera. As a possible simplification, the kernel could internally retry the safecopy operation more often than necessary, since the caller would simply remain blocked if the retried safecopy operation hits a case of live update again.
In a very specific scenario, the kernel performs a memory copy of the entire asynsend table between two processes of which the slots are being swapped. Although it is not yet clear which exact circumstances cause the need for this memory copy, the actual copy action relies on very specific conditions which are not fully validated before the copy action. Thus, this is a rather dangerous kernel feature.
A rather long comment in
minix/lib/libsys/sef_liveupdate.c elaborates on the specifics of this case, and suggests why RS may be the only affected service. If the comment is correct, it may be possible to engineer another solution for RS in particular, and remove the copy hack from the kernel.
A number of miscellaneous issues remain. The first issue, regarding performance, is a relatively important issue. The other issues listed in this section are relatively minor.
The performance of various parts of the live update infrastructure is not fantastic. This is true for both the instrumentation passes and, more importantly, the run-time functionality. As one of the effects, live update operations may have to be given a lenient timeout in order to succeed. In fact, state transfer currently takes too long to consider automatic runtime ASR rerandomization as a realistic option.
We have not yet looked into the causes of the poor performance. Part of it may be due to the extra memory allocations performed by libmagicrt, but that is only a guess. This issue is therefore rather open ended. Statistical profiling may provide at least some hints.
Currently, the safecopy memory grant tables of system services are transferred as is: the main union of the
cp_grant_t structure as defined in
include/minix/safecopies.h is marked as ixfer.
In some scenarios, however, it is possible that during a service's live update, the service has grants allocated for remote services. For direct grants (of type
CPF_DIRECT),
cp_direct.cp_start is actually a pointer into the local address space. The identity transfer therefore prevents this local pointer from being updated. Especially with ASR, there is a risk that after the live update, the grant points to arbitrary memory within the updated service. In the worst case, a remote user of the grant may end up overwriting this arbitrary memory in the updated service.
To resolve this, the grant structure should not be using ixfer for its main union. This probably means that a custom state transfer routine for the grant structure must be written, so as to use a pointer transfer only for
CPF_DIRECT grants.
The same does not apply to magic grants (of type
CPF_MAGIC), as
cp_magic.cp_start is an address in a remote process, which is either a userland process or a system process blocked on a call to VFS (as of writing, only VFS can use magic grants at all), and thus never subject to live update while the magic grant is active.
If the
testrelpol script is run a number of times in a row, it will start to fail on the crash recovery tests for unclear reasons. We know that this is a test script failure rather than an actual failure. We suspect that it is caused by RS's default exponential backoff algorithm for crash recovery causing timeouts in testrelpol. If that is the case, it should be possible to change testrelpol to disable the exponential backoff using existing service(8) flags.
The implementation of the magic runtime library currently relies on asserts being enabled. We have changed its Makefile so that asserts should be enabled regardless of build system settings, but this is merely a workaround. Instead, libmagicrt should function properly (and, in particular, fail properly) regardless of whether asserts are enabled.
During live update and crash recovery, the following VM error may be seen:
VM: cannot fork with physically contig memory
The error indicates that it is currently not possible to mark physically contiguous memory as copy-on-write, which is true. However, the error may occur during a live update, when VM copies over the memory-mapped pages of a service's old instance to the new instance. The error is therefore not the result of a fork(2) call. In addition, the error code thrown by the function producing the error message, is ignored by its caller, with as result that the reference count of the contiguous memory range is increased anyway, which is exactly what needs to happen for live update operations. Thus, during live updates, this error is both misleading and meaningless. However, we have to review whether it is still useful to keep around the error for other scenarios.
State transfer makes exceptions based on name prefixes. Some of these name prefixes are overly broad. For example, it is possible that the current exception of the prefix
st_ also ends up matching certain variables in actual service code by accident. At the very least, all exception prefixes should start with
magic_.
The following publication covers the MINIX3 live update architecture, design, and implementation, and provides more details on various theoretical and practical aspects. | https://wiki.minix3.org/doku.php?id=developersguide:liveupdate&do= | CC-MAIN-2020-05 | refinedweb | 17,034 | 50.57 |
Hey guys,
Not sure why this is happening, but when I try to import xml.dom.minidom and call parseString() on it it fails as such..
from pyexpat import *
ImportError: No module named pyexpat
Looks like it needs an XML parser?works find in my python2.6 console. I even tried sym-linking it to sublimes python directory! No DiceNot sure whats up with that.
I just need to parse some XML sublime! Jeez!
Any help would be greatly appreciated.. Doing a big project for you PHP developers out there
Running Sublime Text 2 Build 2139 on Ubuntu 11.10
And how to fix it for Linux?
Any ideas?
Interesting package github.com/a-sk/sublime-css-colors also generates this error.
If it is not bundled with the version of Python that is included with Sublime, you could always bundle it with your plugin. The only complication would be if it is not pure python, then you would need to figure out how to handle the different platforms. I believe SublimeCodeIntel has figured out how to handle native code for the various platforms, so you may want to look there.
I had to do something similar with the SFTP plugin because the version of ftplib in 2.6 doesn't appear to respect timeouts after the connection phase, which lead to issues trying to gracefully handle incorrect passive/active settings. I bundled a custom version of ftplib which I renamed to prevent conflicts with other plugins.. | https://forum.sublimetext.com/t/minidom-issues/3210/3 | CC-MAIN-2016-07 | refinedweb | 247 | 66.84 |
c interview questions and answers paper 323 - skillgunNote: Paper virtual numbers may be different from actual paper numbers . In the page numbers section website displaying virtual numbers .
float data type with example in c:
What is the output of below C program?
#include <stdio.h>
int main(void)
{
float res = 12/5;
printf("%f", res);
return 0;
}
prints 2.000000
prints 2
prints 2.400000
prints 2.4
float res = (float)12/5; //since 12 is converted to float,
//total expression will yield float result that is 2.400000
What is the use of malloc function in c?
It is used to remove memory of a pointer.
It is used to allocate memory for a function.
It is used to allocate memory for a pointer.
none
What is the use of free function in c?
It is used to free the memory allocated by malloc.
It is used to reallocate memory for a pointer.
Back To Top | http://skillgun.com/c/interview-questions-and-answers/paper/323 | CC-MAIN-2017-30 | refinedweb | 157 | 69.99 |
Localizing ASP.NET MVC Validation
This is
not specific to ASP.NET MVC, but is a feature of Data Annotations and
ASP.NET. And everything I cover here works for ASP.NET MVC 1.0 (except
for the part about client validation which is new to ASP.NET MVC 2).
I covered this feature a back in March at Mix 09 in my ASP.NET MVC Ninjas on Fire Black Belt Tips talk. If you want to see me walk through it step by step, check out the video. If you prefer to read about it, continue on!
Let’s start with the
ProductViewModel I used in the last post
public class ProductViewModel { [Price(MinPrice = 1.99)] public double Price { get; set; } [Required] public string Title { get; set; } }
If we’re going to localize the error messages for the two properties, we need to add resources to our project. To do this, right click on your ASP.NET MVC project and select Properties. This should bring up the properties window. Click on the Resources tab. You’ll see a message that says,
This project does not contain a default resources file. Click here to create one.
Obey the message. After you click on the link, you’ll see the resource editor.
Make sure to change the Access Modifier to Public(it defaults to
Internal).
Now enter your resource strings in the resource file.
Hopefully my Spanish is not too bad. An ASP.NET build provider will
create a new class named
Resources behind the scenes with a property
per resource string. In this case there’s a property named
PriceIsNotRight and
Required. You can see the new file in the
Properties folder of your project.
The next step is to annotate the model so that it pulls the error messages from the resources.
public class ProductViewModel { [Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "Required")] public string Title { get; set; } [Price(MinPrice = 3.99, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "PriceIsNotRight")] public double Price { get; set; } }
For the
ErrorMessageResourceType, I just specify the type created by
the build provider. In my case, the full type name is
CustomValidationAttributeWeb.Properties.Resources.
For the
ErrorMessageResourceName, I just use the name that I specified
in the resource file. The name identifies which resource string to use.
Now when I submit invalid values, the error messages are pulled from the resource file and you can see they are in Spanish.
Localized Error Messages Custom Client Validation
Note that these localized error messages continue to work even if you enable client validation. However, if you were to try it with the original code I posted in my last validation example, the error message would not work for the custom price validation attribute.
Turns out I had a bug in the code, which is now corrected in the blog
post with a note describing the fix. Just scroll down to the
PriceValidator class.
As always, I have a code sample you can look at. It’s the same example as before, just updated. Download the sample!
Tags: aspnetmvc, asp.net, validation, localization, data annotations | https://haacked.com/archive/2009/12/07/localizing-aspnetmvc-validation.aspx/ | CC-MAIN-2017-51 | refinedweb | 513 | 68.16 |
void *realloc( void *p, size_t s )
void *p; /* address of a previously allocated piece of memory */
size_t s; /* new size in bytes */
Synopsis
#include "stdlib.h"
The realloc function changes the size of the object pointed to by p to the size indicated by s . The contents of p will be unchanged unless s is smaller than its original size.
Parameters
p is the address of a piece of memory previously allocated from the heap (as if by malloc, calloc, etc.). s is an integer specifying the new size of the memory block.
Return Value
realloc returns a pointer to the new region if successful, and NULL if not, in which case the contents of p are left unchanged.
See Also
malloc, calloc, free
Help URL: | http://silverscreen.com/idh_silverc_compiler_reference_realloc.htm | CC-MAIN-2021-21 | refinedweb | 126 | 61.77 |
.
This article lists some questions and common issues you might experience when building Ext JS applications.
"Ext is undefined".
You can also check the "Net" tab in Firebug to verify that all of your paths are correct. Any invalid include paths will show up in red as invalid links.
My code does not work in Internet Explorer, but it works fine in Firefox
You might have an extra comma somewhere in your code that causes Internet Explorer to stop parsing the code correctly (also check if you have commented out all firebug commands that will confuse IE). for ",]" or ",}", this way you can find some of the "extra commas". You can also search in your "not minified" code with regular expressions like ,[\s ]*\] .
"sp is undefined"
This is usually when calling Ext.extend and the superclass you pass has not been defined. Check your namespace and for spelling errors, etc.
"XX has no properties".
Security Warning in IE using SSL
If you're getting that annoying security warning that asks you if you want to download insecure items in IE over SSL, don't fret. You just have to remember to set your BLANK_IMG_URL to the local version of s.gif.
1 Comment
Tamesh3 years ago
IE is giving “null” is null or not an object and mozila is giving ct is null.
I am getting the error
In IE is giving “null” is null or not an object and mozila is giving ct is null
Below i have metioned the code plz help.
callFunction = function(){
alert(“call”);
}
Ext.onReady(callFunction );
Leave a comment:Commenting is not available in this channel entry. | http://www.sencha.com/learn/common-ext-js-errors/ | CC-MAIN-2014-10 | refinedweb | 272 | 72.66 |
pyshout 0.2.0
Loud python messaging!
Shout!
Loud Python messaging.
Shout is a single module providing simple messaging vocabulary for small applications. Shout is NOT a distributed messaging framework.
from shout import Message, hears, shout class WhoAreYou(Message): pass @hears(WhoAreYou) def lucky_day(): return "We are..." @hears(WhoAreYou) def dusty_bottoms(): return "The threeee..." @hears(WhoAreYou) def ned_nederlander(): return "Amigos!!" msg = shout(WhoAreYou) print("".join(msg.results)) # We are...The threeee...Amigos!!
Why Shout
- Decoupling of a GUI and it’s behavior
- PySide/PyQt signals are bound to widgets making it harder to decouple widgets. You have to explicitly connect each widget’s signals with their slots which could live deep in a hierarchy of widgets.
- Shout Messages are classes themselves, readily available to all other objects in their scope. Shout from inside, outside, top, or bottom of a widget hierarchy, Messages will still get to where they need to go!
- Shout is a single module, easily included with any package.
- It’s easy and fun to use.
Get Shout
Shout is available through the python package index as pyshout.
pip install pyshout
- Note that only the python package name is pyshout, the module it installs is simply shout.
- Author: Dan Bradham
- License: MIT
- Package Index Owner: danbradham
- DOAP record: pyshout-0.2.0.xml | https://pypi.python.org/pypi/pyshout/0.2.0 | CC-MAIN-2016-30 | refinedweb | 215 | 60.51 |
Introduction
By the end of this article you’ll know:
- What is Gradient Clipping and how does it occur?
- Types of Clipping techniques
- How to implement it in Tensorflow and Pytorch
- Additional research for you to read
Gradient Clipping solves one of the biggest problems that we have while calculating gradients in Backpropagation for a Neural Network.
You see, in a backward pass we calculate gradients of all weights and biases in order to converge our cost function. These gradients, and the way they are calculated, are the secret behind the success of Artificial Neural Networks in every domain.
But every good thing comes with some sort of caveats.
Gradients tend to encapsulate information they collect from the data, which also includes long-range dependencies in large text, or multidimensional data. So, while calculating complex data, things can go south really quickly, and you’ll blow your next million-dollar model in the process.
Luckily, you can solve it before it occurs (with gradient clipping) – let’s first look at the problem in-depth.
Common problems with backpropagation
The Backpropagation algorithm is the heart of all modern-day Machine Learning applications, and it’s ingrained more deeply than you think.
Backpropagation calculates the gradients of the cost function w.r.t – the weights and biases in the network.
It tells you about all the changes you need to make to your weights to minimize the cost function (it’s actually -1*∇ to see the steepest decrease, and +∇ would give you the steepest increase in the cost function).
Pretty cool, because now you get to adjust all the weights and biases according to the training data you have. Neat math, all good.
Vanishing gradients
What about deeper networks, like Deep Recurrent Networks?
The translation of the effect of a change in cost function(C) to the weight in an initial layer, or the norm of the gradient, becomes so small due to increased model complexity with more hidden units, that it becomes zero after a certain point.
This is what we call Vanishing Gradients.
This hampers the learning of the model. The weights can no longer contribute to the reduction in cost function(C), and go unchanged affecting the network in the Forward Pass, eventually stalling the model.
Exploding gradients.
arXiv:1211.5063 [cs.LG]: The objective function for highly nonlinear deep neural networks or for recurrent neural networks often contains sharp nonlinearities in parameter space resulting from the multiplication of several parameters. These nonlinearities give rise to very high derivatives in some places. When the parameters get close to such a cliff region, a gradient descent update can catapult the parameters very far, possibly losing most of the optimization work that had been done.
Deep dive into exploding gradients problem
For calculating gradients in a Deep Recurrent Networks we use something called Backpropagation through time (BPTT), where the recurrent model is represented as a deep multi-layer one (with an unbounded number of layers) and backpropagation is applied on the unrolled model.
In other words, it’s backpropagation on an unrolled RNN.
Unrolling recurrent neural networks in time by creating a copy of the model for each time step:
We denote by a<t> the hidden state of the network at time t, by x<t> the input and ŷ<t> the output of the network at time t, and by C<t> the error obtained from the output at time t.
Let’s work through some equations and see the root where it all starts.
We will diverge from classical BPTT equations at this point, and re-write the gradients in order to better highlight the exploding gradients problem.
These equations were obtained by writing the gradients in a sum-of-products form.
We will also break down our flow into two parts:
- Forward Pass
- Backward Pass
Forward Pass
First, let’s check what intermediate activations of neurons at timestep <t> will look like:
Eq: 1.1
W_rec represents the recurrent matrix that will carry the translative effect of previous timesteps.
W_in is the matrix that gets matmul operation by the current timestep data and b represents bias.
An intermediate output at timestep <t> will look something like:
Eq: 1.2
Note that here “σ” represents any activation function of your choice. Popular picks include sigmoid, tanh, ReLU.
Using the predicted and ground-truth value, we can calculate the Cost Function of the entire network by summing over individual Cost functions for every timestep <t>.
Eq: 1.3
Now, we have the general equations for the calculation of Cost Function. Let’s do a backward propagation, and see how gradients get calculated.
Backward Pass
In order to acquire the gradients from all timesteps, we again do a summation of all intermediate gradients at timestep <t>, and then the gradients are averaged over all training examples.
Eq: 1.4
So, we have to calculate the intermediate Cost Function(C) at any timestep <t> using the chain rule of derivatives.
Let’s look at the dependency graph to identify the chain of derivatives:
For a timestep <3>, our Cost Function will look something like:
Eq: 1.5
Note: We’ve only mentioned derivative w.r.t to W which represents all the weights and bias matrices we’re trying to optimize.
As you can see above we get the activation a<3> which will depend on a<2>, and so on till the first layer’s activation is not calculated.
Hence the dependency will go something like:
a<t> → a<t-1> → a<t-2> → …. → a<1>
So if we take the derivative with respect to W we can’t simply treat a<3> as constant.
We need to apply the chain rule again. Finally, our equation will look something like this:
Eq: 1.6
We sum up the contributions of each time step to the gradient.
In other words, because W is used in every step up to the output we care about, we need to backpropagate gradients from t=3 through the network all the way to t=0.
So, in order to calculate activation for a timestep <t>, we need all the activations from previous timesteps.
Note that ∂a<T>/∂a<k> is a chain rule in itself! For example:
Eq: 1.7
Also note that because we are taking the derivative of a vector function with respect to a vector, the result is a matrix (called the Jacobian matrix) whose elements are all the pointwise derivatives.
We can rewrite the above gradient in Eq:1.6:
Eq: 1.8
Eq: 1.9
This represents a Jacobian Matrix whose value is calculated using Frobenius or 2-norm.
To understand this phenomenon we need to look at the form of each temporal component, and in particular at the matrix factors → ∂a<t>/ ∂a<k> (Eq:1.6,1.9) that take the form of a product of (t − k) Jacobian matrices.
In the same way, a product of (t − k) real numbers can shrink to zero or explode to infinity, so does this product of matrices (along with some direction v).
Hence, we get the condition of Exploding Gradients due to this temporal component.
How to identify and catch Exploding Gradients?
The identification of these gradient problems is hard to comprehend before the training process is even started.
When your network is a deep recurrent one, you have to:
- constantly monitor the logs,
- record sudden jumps in the cost function
This will tell you whether these jumps are frequent, and if the norm of the gradient is increasing exponentially.
The best way to do this is by monitoring logs in a visualization dashboard.
We’ll utilize Neptune AI’s awesome visualization and dashboarding of the logs to monitor the loss and other metrics which will help in the identification of Exploding gradients. You can head over to a detailed blog mentioned below to set up your dashboard.
See the article:
How to fix exploding gradients: gradient clipping
There are a couple of techniques that focus on Exploding Gradient problems.
One common approach is L2 Regularization which applies “weight decay” in the cost function of the network.
The regularization parameter gets bigger, the weights get smaller, effectively making them less useful, as a result making the model more linear.
However, we’ll focus on a technique that’s far superior in terms of gaining results and easiness in implementation – Gradient Clipping.
What is gradient clipping?
Gradient Clipping is a method where the error derivative is changed or clipped to a threshold during backward propagation through the network, and using the clipped gradients to update the weights.
By rescaling the error derivative, the updates to the weights will also be rescaled, dramatically decreasing the likelihood of an overflow or underflow.
Effect of gradient clipping in a recurrent network with two parameters w and b. Gradient clipping can make gradient descent perform more reasonably in the vicinity of extremely steep cliffs. (Left)Gradient descent without gradient clipping overshoots the bottom of this small ravine, then receives a very large gradient from the cliff face. (Right) Gradient descent with gradient clipping has a more moderate reaction to the cliff. While it does ascend the cliff face, the step size is restricted so that it cannot be propelled away from the steep region near the solution. Figure adapted from Pascanu et al. (2013).
Gradient Clipping is implemented in two variants:
- Clipping-by-value
- Clipping-by-norm
Gradient Clipping-by-value
The idea behind clipping-by-value is simple. We define a minimum clip value and a maximum clip value.
If a gradient exceeds some threshold value, we clip that gradient to the threshold. If the gradient is less than the lower limit then we clip that too, to the lower limit of the threshold.
The algorithm is as follows:
g ← ∂C/∂W
if ‖g‖ ≥ max_threshold or ‖g‖ ≤ min_threshold then
g ← threshold (accordingly)
end if
where max_threshold and min_threshold are the boundary values and between them lies a range of values that gradients can take. g, here is the gradient, and ‖g‖ is the norm of g.
Gradient Clipping-by-norm
The idea behind clipping-by-norm is similar to by-value. The difference is that we clip the gradients by multiplying the unit vector of the gradients with the threshold.
The algorithm is as follows:
g ← ∂C/∂W
if ‖g‖ ≥ threshold then
g ← threshold * g/‖g‖
end if
where the threshold is a hyperparameter, g is the gradient, and ‖g‖ is the norm of g. Since g/‖g‖ is a unit vector, after rescaling the new g will have norm equal to threshold. Note that if ‖g‖ < c, then we don’t need to do anything,
Gradient clipping ensures the gradient vector g has norm at most equal to threshold.
This helps gradient descent to have reasonable behavior even if the loss landscape of the model is irregular, most likely a cliff.
Gradient clipping in deep learning frameworks
Now we know why Exploding Gradients occur and how Gradient Clipping can resolve it.
We also saw two different methods by virtue of which you can apply Clipping to your deep neural network.
Let’s see an implementation of both Gradient Clipping algorithms in major Machine Learning frameworks like Tensorflow and Pytorch.
We’ll employ the MNIST dataset which is an open-source digit classification data meant for Image Classification.
For the first part, we’ll do some data loading and processing which is common for both Tensorflow and Keras.
Data loading
import tensorflow as tf from tensorflow.keras import Model, layers import numpy as np import tensorflow_datasets as tfds print(tf.__version__)
We recommend you install the latest version of Tensorflow 2 which at the time of writing this was 2.3.0, but this code will be compatible with any future version. Make sure you’re installed with 2.3.0 or higher. In this excerpt, we’ve imported the TensorFlow dependencies as usual, with NumPy as our matrix computation library.
from tensorflow.keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() # Convert to float32. x_train, x_test = np.array(x_train, np.float32), np.array(x_test, np.float32) # Flatten images to 1-D vector of 784 features (28*28). x_train, x_test = x_train.reshape([-1, 28, 28]), x_test.reshape([-1, num_features]) # Normalize images value from [0, 255] to [0, 1]. x_train, x_test = x_train / 255., x_test / 255. # Use tf.data API to shuffle and batch data. train_data = tf.data.Dataset.from_tensor_slices((x_train, y_train)) train_data = train_data.repeat().shuffle(5000).batch(batch_size).prefetch(1)
Now, let’s see how to implement Gradient Clipping by-value and by-norm in Tensorflow.
Tensorflow
# Create LSTM Model. class Net(Model): # Set layers. def __init__(self): super(Net, self).__init__() # RNN (LSTM) hidden layer. self.lstm_layer = layers.LSTM(units=num_units) self.out = layers.Dense(num_classes) # Set forward pass. def __call__(self, x, is_training=False): # LSTM layer. x = self.lstm_layer(x) # Output layer (num_classes). x = self.out(x) if not is_training: # tf cross entropy expect logits without softmax, so only # apply softmax when not training. x = tf.nn.softmax(x) return x # Build LSTM model. network = Net()
We’ve created a simple 2-layer network with the Input layer of LSTM (RNN based unit) and output/logit layer as Dense.
Now, let’s define other hyperparameters and metric functions to monitor and analyze.
# Hyperparameters num_classes = 10 # total classes (0-9 digits). num_features = 784 # data features (img shape: 28*28). # Training Parameters learning_rate = 0.001 training_steps = 1000 batch_size = 32 display_step = 100 # Network Parameters # MNIST image shape is 28*28px, we will then handle 28 sequences of 28 timesteps for every sample. num_input = 28 # number of sequences. timesteps = 28 # timesteps. num_units = 32 # number of neurons for the LSTM layer. # Cross-Entropy Loss. # Note that this will apply 'softmax' to the logits. def cross_entropy_loss(x, y): # Convert labels to int 64 for tf cross-entropy function. y = tf.cast(y, tf.int64) # Apply softmax to logits and compute cross-entropy. loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=x) # Average loss across the batch. return tf.reduce_mean(loss) # Accuracy metric. def accuracy(y_pred, y_true): # Predicted class is the index of highest score in prediction vector (i.e. argmax). correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64)) return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1) # Adam optimizer. optimizer = tf.optimizers.Adam(learning_rate)
Note that we are using Cross-Entropy loss function with softmax at the logit layer since this is a classification problem. Feel free to tweak the hyperparameters and play around with it to better understand the flow.
Now, let’s define the Optimization function where we’ll calculate the gradients, loss, and optimize our weights. Note that here we’ll apply the gradient clipping.
# Optimization process. def run_optimization(x, y): # Wrap computation inside a GradientTape for automatic differentiation. with tf.GradientTape() as tape: # Forward pass. pred = network(x, is_training=True) # Compute loss. loss = cross_entropy_loss(pred, y) # Variables to update, i.e. trainable variables. trainable_variables = network.trainable_variables # Compute gradients. gradients = tape.gradient(loss, trainable_variables) # Clip-by-value on all trainable gradients gradients = [(tf.clip_by_value(grad, clip_value_min=-1.0, clip_value_max=1.0)) for grad in gradients] # Update weights following gradients. optimizer.apply_gradients(zip(gradients, trainable_variables))
At Line:14 we applied the Gradient Clip-by-value by iterating over all the gradients calculated at Line:11. Tensorflow has an explicit function definition in its API to apply Clipping.
To implement Gradient Clip-by-norm just change the Line 14 with:
# clip-by-norm gradients = [(tf.clip_by_norm(grad, clip_norm=2.0)) for grad in gradients]
Let’s define a training loop and log metrics:
# Run training for the given number of steps. for step, (batch_x, batch_y) in enumerate(train_data.take(training_steps), 1): # Run the optimization to update W and b values. run_optimization(batch_x, batch_y) if step % display_step == 0: pred = lstm_net(batch_x, is_training=True) loss = cross_entropy_loss(pred, batch_y) acc = accuracy(pred, batch_y) print("step: %i, loss: %f, accuracy: %f" % (step, loss, acc))
Keras
Keras works as a wrapper around the TensorFlow API to make things easier to understand and implement. The Keras API lets you focus on the definition stuff and takes care of the Gradient calculation, Backpropagation in the background. Gradient Clipping can be as simple as passing a hyperparameter in a function. Let’s see the specifics.
from keras.layers import Dense, LSTM from keras.models import Sequential from keras.optimizers import SGD from keras.callbacks import Callback # define model # using the hparams of tensorflow model = Sequential() model.add(LSTM(units=num_units)) model.add(Dense(num_classes))
We’ll now declare the gradient clipping factor, and finally fit the model with Keras’ awesome “.fit” method.
# Gradient Clip-by-value passed as hyperparamter to Optimizer function. optimizer = SGD(lr=0.01, momentum=0.9, clipvalue=1.0) # compile model model.compile(loss='binary_crossentropy', optimizer=optimizer) # fit model history = model.fit(train_data, epochs=5, verbose=1, steps_per_epoch=training_steps, callbacks=[MonitoringCallback()])
Keras optimizers take care of additional gradient computation requests (like clipping in the background). Developers only need to pass values on these as hyperparameters.
In order to implement Clip-by-norm just alter the hyperparameter in Line:11 to:
# Gradient Clip-by-norm optimizer = SGD(lr=0.01, momentum=0.9, clipnorm=1.0)
Pytorch
The implementation of Gradient Clipping, although algorithmically the same in both Tensorflow and Pytorch, is different in terms of flow and syntax.
So, in this section of implementation with Pytorch, we’ll load data again, but now with Pytorch DataLoader class, and use the pythonic syntax to calculate gradients and clip them using the two methods we studied.
import os import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision from torch.optim.lr_scheduler import StepLR
Now, let’s declare some hyperparameters and DataLoader class in PyTorch.
# Hyperparameters n_epochs = 2 batch_size_train = 64 batch_size_test = 1000 learning_rate = 0.01 momentum = 0.5 log_interval = 10 random_seed = 1 torch.backends.cudnn.enabled = False torch.manual_seed(random_seed) # Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') sequence_length = 28 input_size = 28 hidden_size = 128 num_layers = 2 num_classes = 10 batch_size = 100 num_epochs = 2 learning_rate = 0.01 os.makedirs('files',exist_ok=True)=False, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.1307,), (0.3081,)) ])), batch_size=batch_size_test, shuffle=True)
Model time! we’ll declare the same model with LSTM as the input layer and Dense as the logit layer.
# Recurrent neural network (many-to-one) class Net(nn.Module): def __init__(self, input_size, hidden_size, num_layers, num_classes): super(Net, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, num_classes) def forward(self, x): # Set initial hidden and cell states h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) # Forward propagate LSTM out, _ = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size) # Decode the hidden state of the last time step out = self.fc(out[:, -1, :]) return out # Instantiate the model with hyperparameters model = Net(input_size, hidden_size, num_layers, num_classes).to(device) # Loss and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
Now, we’ll define the training loop in which gradient calculation along with optimizer steps will be defined. Here we’ll also define our clipping instruction.
# Train the model total_step = len(train_loader) for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = images.reshape(-1, sequence_length, input_size).to(device) labels = labels.to(device) # Forward pass outputs = model(images) loss = criterion(outputs, labels) # Backward and optimize optimizer.zero_grad() loss.backward() #Gradient Value Clipping nn.utils.clip_grad_value_(model.parameters(), clip_value=1.0) optimizer.step() if (i+1) % 100 == 0: print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' .format(epoch+1, num_epochs, i+1, total_step, loss.item()))
Since PyTorch saves the gradients in the parameter name itself (a.grad), we can pass the model params directly to the clipping instruction. Line:17 describes how you can apply clip-by-value using torch’s clip_grad_value_ function.
To apply Clip-by-norm you can change this line to:
# Gradient Norm Clipping nn.utils.clip_grad_norm_(model.parameters(), max_norm=2.0, norm_type=2)
So, upto this point you understand what clipping does and how to implement it. Now, in this section we’ll see it in action, sort of a before-after scenario to get you to understand the importance of it.
The framework of choice for this will be Pytorch since it has features to calculate norms on the fly and store it in variables.
Let’s start with the usual imports of dependencies.
import time from tqdm import tqdm import numpy as np from sklearn.datasets import make_regression import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import neptune # The init() function called this way assumes that NEPTUNE_API_TOKEN="<your-token-here>" neptune.init('<username>/sandbox',api_token = NEPTUNE_API_TOKEN) neptune.create_experiment('Gradient-Clipping-monitoring-example')
For the sake of keeping the norms to handle small, we’ll only define two Linear/Dense layers for our neural network.
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(20, 25) self.fc2 = nn.Linear(25, 1) self.ordered_layers = [self.fc1, self.fc2] def forward(self, x): x = F.relu(self.fc1(x)) outputs = self.fc2(x) return outputs
We created “ordered_layers”variable in order to loop over them to extract norms.
def train_model(model, criterion, optimizer, num_epochs, with_clip=True): since = time.time() dataset_size = 1000 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs)) print('-' * 10) time.sleep(0.1) model.train() # Set model to training mode running_loss = 0.0 batch_norm = [] # Iterate over data. for idx,(inputs,label) in enumerate(tqdm(train_loader)): inputs = inputs.to(device) # zero the parameter gradients optimizer.zero_grad() # forward logits = model(inputs) loss = criterion(logits, label) # backward loss.backward() #Gradient Value Clipping if with_clip: nn.utils.clip_grad_value_(model.parameters(), clip_value=1.0) # calculate gradient norms for layer in model.ordered_layers: norm_grad = layer.weight.grad.norm() batch_norm.append(norm_grad.numpy()) optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) epoch_loss = running_loss / dataset_size if with_clip: neptune.log_metric('Gradient Norm with clipping', np.mean(batch_norm)) else: neptune.log_metric('Gradient Norm without clipping', np.mean(batch_norm)) print('Train Loss: {:.4f}'.format(epoch_loss)) print() time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format( time_elapsed // 60, time_elapsed % 60))
This is a basic training function housing the main event loop that contains gradient calculations and optimizer steps. Here, we extract norms from the said “ordered_layers” variable. Now, we only have to initialize the model and call this function.
def init_weights(m): if type(m) == nn.Linear: torch.nn.init.xavier_uniform(m.weight) m.bias.data.fill_(0.01) if __name__ == "__main__": device = torch.device("cpu") # prepare data X,y = make_regression(n_samples=1000, n_features=20, noise=0.1, random_state=1) X = torch.Tensor(X) y = torch.Tensor(y) dataset = torch.utils.data.TensorDataset(X,y) train_loader = torch.utils.data.DataLoader(dataset=dataset,batch_size=128, shuffle=True) model = Net().to(device) model.apply(init_weights) optimizer = optim.SGD(model.parameters(), lr=0.07, momentum=0.8) criterion = nn.MSELoss() norms = train_model(model=model, criterion=criterion, optimizer=optimizer, num_epochs=50, with_clip=True #make it False for without clipping )
This will create a chart for the metrics you specified which will look something like this:
You can see the discrepancy between norms with and without clipping. During experiments without clipping the norms exploded to NaN after a few epochs whereas experiment with clipping was fairly stable and converging. You can see the logs and source code in the Neptune notebook here and the charts here.
You’ve reached the end!
Congratulations! You’ve successfully understood the Gradient Clipping Methods, what problem it solves, and the Exploding Gradient Problem.
Below are a few endnotes and future research things for you to follow through.
Logging is king!
Whenever you work on a big project with a large network, make sure that you are thorough with your logging procedures.
Exploding Gradient can only be efficiently caught if you are logging and monitoring properly.
You can use your current logging mechanisms in Tensorboard to visualize and monitor other metrics in Neptune’s dashboard. What you have to do is simply install neptune-client to accomplish that. Head over here to explore the documentation.
Research
- This paper explains how training speeds in Deep Networks can be enhanced using gradient clipping.
- This paper explains the use of Gradient clipping in differentially private neural networks.
That’s it for now, stay tuned for more! Adios! | https://neptune.ai/blog/understanding-gradient-clipping-and-how-it-can-fix-exploding-gradients-problem | CC-MAIN-2020-50 | refinedweb | 4,107 | 50.12 |
#include "Arduino.h"#include "File.h"
#ifndef __File_H__#define __File_H__#include <Arduino.h>extern int a = 7;extern int b = 6;extern int c = 5;#endif
#include <File.h>setup(){#define a lot of things}loop(){#do something}
// foo.hextern int bar;void f();class foobar {public: foo();};
int var;void func() { var++;}
You cannot do anything in a .h file that allocates memory -- essentially, you may declare functions (but not define them), declare data as extern (but not as non-extern) and declare classes (and structs and enums and unions...)okay:Code: [Select]// foo.hextern int bar;void f();class foobar {public: foo();};not okay:Code: [Select]int var;void func() { var++;}Note that if a variable is declared extern, it must be defined somewhere else. "extern" means "the variable is defined somewhere else" so you'll just confuse the linker if you say it's somewhere else and then not have it at all. This also means you can't give a value to them because that's a definition, not a declaration.
I have just one more question regarding libraries :Is it possible to just give compile it and send it to my friends in order to avoid them looking in the source (cpp) ?Like a folder in Libraries with a File.h and File.o instead of File.cpp?
essentially, you may declare functions (but not define them)
extern int a = 7;extern int b = 6;extern int c = 5;
extern int a = 5;extern int b = 6;extern int c = 7;
Another file could quite legitimately have
Which is a good argument for NOT using one letter variable names.
extern int antidisestablishmentarianismInitiator = 12;
extern int antidisestablishmentarianismInitiator = 11;
It doesn't matter if the variable name is "a" or "antidisestablishmentarianismInitiator", the scope (pardon the pun) for confusion is still there:
Only the implicit global should be initialised.
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=121441.0;prev_next=prev | CC-MAIN-2016-18 | refinedweb | 346 | 54.32 |
gregglesMember
Content count125
Joined
Last visited
Community Reputation347 Neutral
About greggles
- RankMember
- :) Let me know if something needs to be clarified.
- First of all, the bold vs. not bold: Anything bold is a point, anything not bold is a number. So when you see p(u, v), it means the Point at the barycentric coordinates u, v. Secondly, the sigma notation used in the article means "sum together all of the values where this equation is true." So, for example, the equation i+j+k=n could be true when 1+0+6=7 or when 0+3+4=7, and so on. Let's look at the first equation you have posted: When determining how to create the loops, I found the picture of the triangle very helpful. Lets assume that each digit in the point corresponds to the variables i, j, and k in order. Thus, the lower left point of the triangle p003 means i=0, j=0, and k=3. The first thing that I notice is that i increases from 0 to 3 from bottom to top of the image. This is a basic for loop that we can easily handle. Next, I notice that for any i, the j value starts at 0 on the left and increases until i+j=n on the right. This is another loop we can handle. Finally, the original equation gives us k via algebra: i+j+k=n can be rearranged to k = n - (i+j). That is the final value we need to know. This gives us our final form: Point p; for (int i = 0; i <= n; ++i) { for (int j = 0; i+j <= n; ++j) { int k = n - (i + j); p += B(i, j, k, u, v, n) * p(i, j, k); //Probably not quite what you want here, but this is an example of what this might look like. } } Now, the B() function refers to the function on the Gamasutra page and the p function here means "give me the point with i, j, k index." For example, p(0, 6, 1) means p061. Does this help? The partial derivatives would then be created in a very similar way.
What I learned from 21 games on permadeath
greggles replied to makuto's topic in Game Design and TheoryFirst of all: great post! I like that you brought up such an interesting topic and it got me thinking a bit more about permadeath as another tool in a game designer's arsenal. Some things that I considered and thought I would share: As was mentioned, permadeath forces the player to concentrate and rely more on strategy. This makes it harder for a player to sprint into the action with a shotgun or try a crazy move just to see if it succeeds. It adds the thrill of thinking through your actions and being correct, but reduces the possibility of the thrill of "I can't believe that worked!" It makes the player more protective of his character, which can lead to a stronger emotional attachment. If a player is going to perform an action, he must be confident it will succeed. I think this is where THPS3 utterly fails as a permadeath game, since it is built on repetitive skill honing (eg. keep practicing until you are able to perform the required steps to reach the secret tape). It can be used to help produce a strong sense of accomplishment ("I can't believe I've made it this far!"), which continually pays off in thrill and feeling of achievement. If the game requires repetition, it may be good to help the gamer have an enjoyable fresh start by producing a new gameplay experience (through procedural levels, changing gameplay, or some other way). Note that cut scenes can become dull because of reduced suspense and surprise. The other option is to build levels in a way that it is exciting to play through again, maybe the earlier parts become easier after repetition. Replay ability becomes paramount. Permadeath isn't necessarily all-or-nothing. Consider games like Super Mario Bros. (first example that popped in my head, though many games fit this description). When considered from the big picture you wouldn't consider it a permadeath game, but inside individual levels it is; hit the lava and you must start back at the beginning. If you wanted to make it more permadeath-esque it could be that each world must be replayed if you die in any level. Take it to the extreme and you must always restart from level 1-1. So death can be considered a bit of a continuum from restart from your last save to restart from the beginning.
- [quote name='BobXIV' timestamp='1352385937' post='4998874'] [quote name='greggles' timestamp='1352084345' post='4997410'] Maybe I'm missing something, but what is wrong with (0, 20)? Although it is not one of the vertices, it [i]is[/i] on the bounds of the minkowski difference. My understanding of the GJK algorithm is that it should still work correctly. [/quote] Greggles maybe I'm misunderstanding you, what you say is correct but the vertex (0,20) or any support point is indeed one of the vertices... if you mean the vertices of the Minkowski difference. [/quote] I think you may have misunderstood me. Let me clarify the calculations: The original shapes are define by vertices (-5, 5), (5, 5), (5, 15), (-5, 15) and (-5, -5), (5, -5), (5, 5), (-5, 5) We know (intuitively, but this can be determined algorithmically with more calculation) that the resultant diffence will be a square, so finding the four vertices of the difference: (-5, 5) - (5, 5) = (-10, 0) (5, 5) - (-5, 5) = (10, 0) (5, 15) - (-5, -5) = (10, 20) (-5, 15) - (5, -5) = (-10, 20) So there is an edge from (10, 20) to (-10, 20). (0, 20) lies in the middle of this edge instead of one of its endpoints; thus it is not a vertex.
- Maybe I'm missing something, but what is wrong with (0, 20)? Although it is not one of the vertices, it [i]is[/i] on the bounds of the minkowski difference. My understanding of the GJK algorithm is that it should still work correctly.
IDE most comparable to VS
greggles replied to MattProductions's topic in For Beginners[quote name='MattProductions' timestamp='1349715613' post='4988038'] Thanks guys, but now another question. What is the difference between Java SE/FX/EE/ME/... I have to choose a version of Netbeans to download What's the best one for game development? [/quote] SE = Standard Edition ([url=""][/url]) FX = Java FX ([url=""][/url]) EE = Enterprise Edition ([url=""][/url]) ME = Micro Edition ([url=""][/url]) I suggest the standard edition.
Help me name my game!
greggles replied to AndreasHeydeck's topic in GDNet LoungeLooks good. I really liked the education level of the janitor: Sweeping 101, Advanced Sweeping, and Sweeping with a Passion. The first name I thought of when I saw the game is Big Huge Evil Company Inc. Another idea is to play off of telephone/telemarket, like using Telemagnate, Telemogul, or Telemarketeer. Or maybe stick with a basic name like Com Command or Call Center Command.
Java .GIF to Image Array
greggles replied to CryoGenesis's topic in For BeginnersIt's been a while since I used it, but I believe the javax.imageio package should have what you need. There is a function in the class ImageIO called [url=""]getImageReadersByFormatName[/url] that returns an Iterator of [url=""]ImageReader[/url]s. The ImageReader class appears to contain some functions that allow you to read multiple Images from a file.
Seattle Area
greggles replied to greggles's topic in GDNet Lounge[quote name='way2lazy2care' timestamp='1335683599' post='4935773'] Get fish thrown at/over you and go to the glass museum in Tacoma and watch them blow glass. Those were my two favorite things when I lived there. At least things that are very seattle-y. [/quote] I think it is awesome that a well known attriction in a town could be seeing people throw fish [img][/img]. [quote name='blueEbola' timestamp='1335749098' post='4935958'] I've lived in the PNW all of my life and just recently moved up to Seattle to start a new web developer position up here.. and it rocks! [/quote] First of all, congrats on the new position! [quote name='blueEbola' timestamp='1335749098' post='4935958'] Seattle is split up into several districts (sometimes called neighborhoods): Fremont, Ballard, Magnolia, Queen Anne, U-distict, Belltown, West Seattle, Green lake.. and the list goes on. Each district kind of has its own vibe. I live in northern Magnolia just south of Ballard, and it's got some amazing views and a "residential" kind of feel. Works for me because I came from kind of a country town and living on a busy street in downtown Seattle probably would've been a bit too hectic for me. Ballard is the condo part of town, there's tons of development going on up there and lots of young professionals living in that area. [/quote] I'll be working in the South Lake Union district (at Amazon.com), but I've heard it's not the best area in which to live. I don't think I'd mind a busy street, but I'm probably looking for an area that is (relatively) close to work and has a decent number of young professionals. From the sounds of it, Magnolia sounds like a good place to include in my search. [quote name='blueEbola' timestamp='1335749098' post='4935958'] There are several music venues and big acts roll through all the time. I've gone to 4 concerts in the past month so far [img][/img] [/quote] I've heard good things about the music scene, which is exciting. As for sports in the area, how difficult is it to get tickets? Having lived near Pittsburgh, PA for several years, it has always been hard for me to get good, cheap tickets for football and hockey games, but baseball is pretty easy + the Pirates have a beautiful stadium.
Seattle Area
greggles posted a topic in GDNet LoungeAfter much work, college is finally coming to a close: in just a few weeks I will be graduating! I am looking forward to starting a job in the Seattle, WA area this July, and I, as someone who grew up on the East coast and doesn't know much about Seattle, was wondering if anyone from the area would be willing to share their wisdom. I would like to get suggestions on things like: good areas to live, fun hangouts, interesting places to visit, gamedev groups, game jams, etc.
aggregate initialization list in class definition
greggles replied to mancubit's topic in For BeginnersStatic variables must be initialized outside of the class definition, like this: [code]#include <iostream> using namespace std; class A { public: static const int i[]; }; const int A::i[] = {1, 2, 3, 4}; int main() { cout << A::i[0] << endl; return 0; }[/code]
[C++]problem with getline
greggles replied to sheep19's topic in For BeginnersThe extraction (>>) operator will not read in the \n after date. So when getline is called, it reads in an empty string. An example (with endlines shown as \n instead of whitespace): John \n 300 \n 3/3/2011 \n Ed \n 300 \n 3/4/2011 \n Your code will read in the first set of data correctly, but this is what the file looks like after it is done: \n Ed \n 300 \n 3/4/2011 \n So the next name will be "", the next score will be "Ed", and the next date will be "300". Obviously this isn't correct and will cause an error.
Java docs
greggles replied to ms75214's topic in For BeginnersYou can download it on the javase download page: [url=""][/url].
Is there a Tablet PC or somethig simillar for taking class notes?
greggles replied to n3Xus's topic in GDNet LoungeThe college that I'm attending supplies tablet PCs to all of the students. I work at the help desk for diagnosing and fixing problems for the tablets. They have been getting HP computers for several years now and they tend to work well. The major thing that we see coming in to get fixed is hard drives, so I would suggest an SSD for your tablet. The model I have is several years old (I have a Compaq tc4400--which I love). I take all of my notes using the pen in OneNote (the pen is especially nice for Math classes). It takes some time getting used to it, but you start to love it after a while. I would strongly suggest buying a tablet pc. The current model that the school is buying for freshman is the HP EliteBook 2740p, which has worked pretty well so far. The only problem I've seen with them is some problems with the keyboards, but that is because our college got the first batch of laptops produced. I think that they've fixed things since then.
[java] Problem with window dimensions (I think) pong clone
greggles replied to nolsen01's topic in General and Gameplay ProgrammingYour right, they are both symptoms of the same problem. The problem is that frames have borders. So, when you add the panel into the frame, it is added within the borders. But your frame is 800x600 including borders, so, when the panel is added to the frame the bottom-right part of it is obscured. So, the paddles are actually in the correct spot and stopping at the correct time for a 800x600 panel. So, now for the fix: remove this.setSize(Globals.getGameWidth(), Globals.getGameHeight()); from Main and add this.pack(); just before this.setVisible(true); in makeGUI. This will force your frame to be a little bigger than 800x600 so that the 800x600 panel will fit inside of it. | https://www.gamedev.net/profile/129002-greggles/?tab=posts | CC-MAIN-2018-05 | refinedweb | 2,337 | 69.41 |
Two water jug problem in C++
In this tutorial, we will learn how to solve the two water jug problem in C++.
PROBLEM STATEMENT:
You are given two unmarked jugs with capacities x and y liters. Determine the moves to obtain exactly n liters of water in any of the two jugs or both by the end.
Given that:
1. There is infinite supply of water.
2. Both the jugs are empty at the beginning.
Operations allowed:
1. Empty /fill a jug completely with water.
2. Pour water from one jug to another until one of the jugs is either empty or full.
SOLUTION:
We will first see the steps to solve the given problem.
- If it is possible to fill n liters of water using the two jugs with x and y liters.
It is possible only if
1. n<x or n<y
2. n%gcd(x,y) is equal to zero.
- Fill x completely.
- Pour x in y.
- Empty y if it is full.
- Check if x is empty or not. If x is not empty, repeat step 3-5. If x is empty, repeat steps 2-5.
- Stop the process when n litres of water is obtained in any of the two jugs or both.
Now, we will implement these steps using C++ code.
#include<bits/stdc++.h> using namespace std; int x; int y; void show(int a, int b); int min(int w, int z) { if (w < z) return w; else return z; } void show(int a, int b) { cout << setw(12) << a << setw(12) << b<<endl; } void s(int n) { int xq = 0, yq = 0; int t; cout << setw(15) <<"FIRST JUG"<< setw(15) <<"SECOND JUG"<<endl; while (xq != n && yq!=n ) { if (xq == 0) { xq = x; show(xq, yq); } else if (yq == y) { yq = 0; show(xq, yq); } else { t = min(y - yq, xq); yq= yq + t; xq = xq - t; show(xq, yq); } } } int main() { int n; cout << "Enter the liters of water required out of the two jugs: "; cin >> n; cout << "Enter the capacity of the first jug: "; cin >> x; cout << "Enter the capacity of the second jug: "; cin >> y; if(n<x || n<y) { if(n%(__gcd(x,y))==0) s(n); else cout<<"This is not possible....\n"; } else cout<<"This is not possible....\n"; }
OUTPUT:
Enter the liters of water required out of the two jugs: 2 Enter the capacity of the first jug: 4 Enter the capacity of the second jug: 3 FIRST JUG SECOND JUG 4 0 1 3 1 0 0 1 4 1 2 3
So, we have solved the two water jug problem in C++. I hope you enjoyed it.
Also, read:
- Create all possible strings from a given set of characters in c++
- C++ program to create a text file, open and read a particular line | https://www.codespeedy.com/two-water-jug-problem-in-cpp/ | CC-MAIN-2019-43 | refinedweb | 474 | 81.02 |
In my previous post, I explained that floating point numbers are a leaky abstraction. Often you can pretend that they are mathematical real numbers, but sometimes you cannot. This post peels back the abstraction and explains exactly what a floating point number is. (Technically, this post describes an IEEE 754 double precision floating point number, by far the most common kind of floating point number in practice.)
A floating point number has 64 bits that encode a number of the form ± p × 2e. The first bit encodes the sign, 0 for positive numbers and 1 for negative numbers. The next 11 bits encode the exponent e, and the last 52 bits encode the precision p. The encoding of the exponent and precision require some explanation.
The exponent is stored with a bias of 1023. That is, positive and negative exponents are all stored in a single positive number by storing e + 1023 rather than storing e directly. Eleven bits can represent integers from 0 up to 2047. Subtracting the bias, this corresponds to values of e from -1023 to +1024. Define emin = -1022 and emax = +1023. The values emin – 1 and emax + 1 are reserved for special use. More on that below.
Floating point numbers are typically stored in normalized form. In base 10, a number is in normalized scientific notation if the significand is ≥ 1 and < 10. For example, 3.14 × 102 is in normalized form, but 0.314 × 103 and 31.4 × 102 are not. In general, a number in base β is in normalized form if it is of the form p × βe where 1 ≤ p < β. This says that for binary, i.e. β = 2, the first bit of the significand of a normalized number is always 1. Since this bit never changes, it doesn’t need to be stored. Therefore we can express 53 bits of precision in 52 bits of storage. Instead of storing the significand directly, we store f, the fractional part, where the significand is of the form 1.f.
The scheme above does not explain how to store 0. Its impossible to specify values of f and e so that 1.f × 2e = 0. The floating point format makes an exception to the rules stated above. When e = emin – 1 and f = 0, the bits are interpreted as 0. When e = emin – 1 and f ≠ 0, the result is a denormalized number. The bits are interpreted as 0.f × 2emin. In short, the special exponent reserved below emin is used to represent 0 and denormalized floating point numbers.
The special exponent reserved above emax is used to represent ∞ and
NaN. If e = emax + 1 and f = 0, the bits are interpreted as ∞. But if e = emax + 1 and f ≠ 0, the bits are interpreted as a
NaN or “not a number.” See IEEE floating point exceptions for more information about ∞ and
NaN.
Since the largest exponent is 1023 and the largest significant is 1.f where f has 52 ones, the largest floating point number is 21023(2 – 2-52) = 21024 – 2971 ≈ 21024 ≈ 1.8 × 10308. In C, this constant is defined as
DBL_MAX, defined in
<float.h>.
Since the smallest exponent is -1022, the smallest positive normalized number is 1.0 × 2-1022 ≈ 2.2 × 10-308. In C, this is defined as
DBL_MIN. However, it is not the smallest positive number representable as a floating point number, only the smallest normalized floating point number. Smaller numbers can be expressed in denormalized form, albeit at a loss of significance. The smallest denormalized positive number occurs with f has 51 0’s followed by a single 1. This corresponds to 2-52*2-1022 = 2-1074 ≈ 4.9 × 10-324. Attempts to represent any smaller number must underflow to zero.
C gives the name
DBL_EPSILON to the smallest positive number ε such that 1 + ε ≠ 1 to machine precision. Since the significant has 52 bits, it’s clear that
DBL_EPSILON = 2-52 ≈ 2.2 × 10-16. That is why we say a floating point number has between 15 and 16 significant (decimal) figures.
For more details see What Every Computer Scientist Should Know About Floating-Point Arithmetic.
First post in this series: Floating point numbers are a leaky abstraction
25 thoughts on “Anatomy of a floating point number”
Thanks for the nice summary of floating point numbers. BTW, I think you made a small mistake in the third paragraph: 2043 should be 2047.
Karl, thanks for pointing out the mistake. I updated the post after reading your correction.
bool IsNumber(double x)
{
// This looks like it should always be true,
// but it’s false if x is a NaN.
return (x == x);
}
mentioned in “IEEE floating-point exceptions in C++”
This is not working at least in VC++ 6.0 compiler
Manjunath, I’m surprised to hear that. I’ve tested that function on several versions of Visual C++, though I can’t recall whether I tested VC6. I’ve tested it on several versions of gcc as well.
John, In gcc its working fine, but VC6 its not working as expected.
Here is my x,
x = numeric_limits::quiet_NaN();
In my test code, I made my own NaNs manually rather than using
quiet_NaN(). For example, I’d have code like
x = -1.0; z = sqrt(x); assert(!IsNumber(z));
or
x = 1.0; y = 0.0; x /= y; z = y*x; assert(!IsNumber(z));
I also have some more elaborate code to generate a quiet NaN. Maybe VC6 has a bug in
quiet_NaN? I wouldn’t think so, but that seems more plausible than a violation of IEEE arithmetic.
of course i did similar thing for test this function by generating NaN and in VC6 its failed. Then i’ve tried with quiet NaN for verifying it.
In C++, the standard way to deal with these constants is via the parameterized numeric_limits class:
#include <limits>
double x = std::numeric_limits<double>::max();
double y = std::numeric_limits<double>::epsilon();
double nan = std::numeric_limits<double>::quiet_nan();
[etc.]
This has the advantage of working for float, double, long double, and whatever is in vogue tomorrow… It also works for the integer types (well, not NaN, but you know what I mean). It also works for typedefs where you neither know nor care what the underlying type is:
typedef long double real_t;
real_t x = std::numeric_limits<real_t>::max();
The <limits> header is part of the C++98 standard, so this also has the advantage of being perfectly portable across 21st-century compilers.
IEEE should hurry up with that floating point interval arithmetic standard
Thanks for the more detailed article on floating point; they’re hard to find. I was wondering, my math is a little weak. How do you get the expression 2^1023(2 – 2^-52) from 1.f * 2^1023, where f is a string of 52 1’s. I assume the 2^1023 remains untouched, so the question then is how do you get (2 – 2^-52) from 1.f? I tried finding a common denominator, so (2^52 + 2^51 + … 2^0) / 2^52, but didn’t seem to get me anywhere.
Thanks.
Be great to add a diagram showing the bit structure of a float. The first time I learned about them there was a diagram and I found it incredibly clear in one glance. 🙂
Hi Jack,
I am trying to explain why 1.f = (2-2^(-52))
1.f = 2⁰+2^(-1) + 2^(-2) + … + 2^(-52)
so,
2^(52) (1.f) = 2^(52) + 2^(51) + … + 2⁰ = 2^(53) – 1 (this is the key)
And finally,
1.f= (2^(53) – 1) / 2^(52) = 2 – 2^(-52)
Best regards,
Javier
Hi John,
Just as an FYI the sun page you referenced is now located here;
Cheers,
Nathan
Thanks. I updated the link in the post.
That link has changed several times since I found it. | https://www.johndcook.com/blog/2009/04/06/anatomy-of-a-floating-point-number/ | CC-MAIN-2018-51 | refinedweb | 1,313 | 75.1 |
OP only things that do Phase 2 are hardware scanners and hardware radios and OP25 for software radios. Bear in mind Phase 2 could be encrypted and nothing you can do will decode it.
OP25 is HARD. I’m a geek and I messed with it on and off for a year or more and it whipped me more than once. Now that I have it working I find that it is REMARKABLY easy and I’m mad at all the geeks out there who never made a simple tutorial. There are tutorials out there, some good but everybody leaves out the good stuff or the stuff they took for granted.
I’m kind of working on the assumption that you have Linux installed and have your SDR device working. In a pinch I guess the first thing you could do is to install gqrx which would pull in all the necessary RTL stuff you need. Follow the directions here if you need to. Yeah that’s a weird way of doing it but it’ll work and probably the easiest thing to do for a newbie.
Installing OP25 is a SNAP. Download from the repository using this command. I’m doing this on Ubuntu 18.04
“NOTE: I’m told that on newer installations that it may be required to install an older version of cmake if compilation errors occur. There are instructions in the comments below by Scott B that detail the procedure to overcome the compilation error.” Thanks Scott!
“NOTE 2: I just installed a fresh version of OP25 on a Raspberry Pi 4 (April 14th,2020) and there was no cmake error. GNUPlot is built in too now it looks like.”
git clone
It will make a folder called op25
cd op25
./install.sh
Wait a bit for it to install. It should take care of everything.
Now it is installed but there are three obstacles to overcome.
- How to launch the program with what command to use
- How to set up the file trunk.tsv
- How to set up the file yourcity.tsv
That’s basically it. Now my assumption here is that you are using a generic RTL-SDR device. I’m using a V3.
These will set you back about $30 or so. But you only need one of these to track a trunked radio system.
So plug in your RTL-SDR device and let’s get ready to do this thing.
I’m going to demonstrate using my home town of New Bern NC. Lets find the trunked system to follow.
Go to this page to list the frequencies.
This page will not always be spot on. The actual control channel at the moment (they change it sometimes) is 857.2625.
To find the control channel if you don’t know which one it is just open a program like GQRX and look and listen for the control channel. It will sound like digital noise. And the signal will be a constant spike. As you can see I found my Control Channel at 857.2625 as stated above.
Now go back to your system and get in the correct directory. Check your path for accuracy.
cd /home/john/op25/op25/gr-op25_repeater/apps
Now try this command IF YOU ARE SETTING UP A DIFFERENT FREQUENCY FOR YOUR TOWN MAKE SURE TO ADJUST THE FREQUENCY IN THE COMMAND. I ALSO FOUND I CAN DO THIS WITH AN ADALM-PLUTOSDR BY CHANGING THE –ARGS TO ‘plutosdr’.
./rx.py --args 'rtl' -N 'LNA:47' -S 2500000 -x 2 -f 857.2625e6 -o 17e3 -q 2
If you get a bunch of errors remove the last part of the command (-q -2) It works as above on my V3 SDR but not on my NESDR Smart. You may also have to adjust the -2 number depending on your individual SDR. Have fun with that. To further illustrate my SDR v3 works at -2, my NESDR Smart works with the -q -2 removed (0), and my Adalm-Pluto works at -q 5 (positive 5). You just have to play around until you get your signal centered on the plot.
As per the pic below ………If where it says 857.262500/812.262500 is all zeros then you need to keep adjusting the -q number. On that screen you can start GNUPLOT by pressing the number 1 key. Keep messing with the q number until the signal is centered on the plot.
Something like the box above should pop up. There won’t be any sound but take note of the NAC. In my case it is 0xfc We’re going to need that. Copy your NAC for your frequency. YOU WILL ONLY GET THE CORRECT NAC IF YOU ARE TUNED TO THE CONTROL CHANNEL YOU WANT TO MONITOR.
Now you should still be in the apps directory. Double click on the file named trunk.tsv and open it with LibreOffice. Make sure the file looks like this and has these settings. (I’ve already modified my file, so ignore the difference.)
Now take note of the way I changed the file. I made the SysName = NewBern, then put my control channel frequency in, put the NAC I copied earlier in, and then told it the tag file was named newbern.tsv Under modulation there are only two types, CQPSK or C4FM. If one doesn’t work, try the other. Save this and exit. Save it as the “Use Text CSV Format”
Now open the file tompkins.tsv It looks like this. Make sure the settings are the same as depicted above.
Delete all the filled in fields in here and go back to the radio reference.com page where all the New Bern frequencies were.
NOTE: TO EASILY INPUT TALK GROUP DATA GET A PREMIUM MEMBERSHIP AT RADIOREFERENCE.COM ($30 per year) AND YOU CAN DOWNLOAD SPREADSHEETS AND JUST CUT AND PASTE THEM INTO YOUR TSV FILES BELOW. I MERGED TWO TAG CELLS TOGETHER TO GET MORE DESCRIPTIVE INFORMATION, ESPECIALLY ON THE VIPER SYSTEM THAT HAS OVER 2000 ENTRIES. HOW’D YOU LIKE TO HAND ADD 2000 ENTRIES?
Now go to the tompkins.tsv file that you cleared and type in column A the numbers in the DEC column (i.e. 100, 101, 102, etc.) Then in column B insert in the tag (i.e. Law Dispatch, Public Works, etc.).
Sorry mine are not in order. Sue me.
Do a “Save As” and name the file newbern.tsv (remember that field in the other file you named newbern.tsv). Make sure this file is also saved in the same format as above and also in the apps directory where the tompkins.tsv file was.
Okay open your terminal. cd to the apps directory /op25/op25/gr-op25_repeater/apps and do this command:
./rx.py --args 'rtl' -N 'LNA:47' -S 2500000 -x 2 -f 857.2625e6 -o 17e3 -q 0 -T trunk.tsv -V -2 -U 2> stderr-stream0.2
Again you may have to remove the -q -2 or adjust it depending on your SDR
When OP25 launches hit the number “1” on your keyboard to open GNUPLOT
And now when there is a transmission on the Control Channel, OP25 will track it to the correct frequency and even display the talk group that is currently active.
Now lets make a little script file so we aren’t forever typing long commands.
cd
cd op25
sudo nano op25.sh
Paste in the following data in the file (MAKE SURE YOUR PATH IS CORRECT AND DON’T FORGET ABOUT THE -q -2 part if you have problems):
#! /bin/sh
cd /home/john/op25/op25/gr-op25_repeater/apps
./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2500000 -f 857.2625e6 -o 17e3 -q -2 -T trunk.tsv -V -2 -U 2> stderr.2
(notice I have changed the -S and -o entry above. Pic below differs)
Hit CTL + the X key then Y to save the file. Now make it executable.
sudo chmod +x op25.sh
Now to launch the file simply be in the directory that script file is in and type:
./op25.sh
It will cd to to the right directory and run the command to start OP25.
In the comments below Mr. Alex Bowman found an easier way to launch the program. Create an alias in Linux so that you just type “op25” (without the quotes) into the terminal from any directory.
sudo nano .bashrc
Then paste in the following lines.
#OP25 alias
alias op25=’bash /home/john/op25/op25.sh’
Be sure your path is right about. Note my path of /home/john. Yours is different unless your name is John, of course.
Now hit Ctl key plus X, then hit Y to save. Restart the terminal and you should now be able to launch OP25 just by typing OP25. It works like a champ. I tried it.
That’s it. I hope I made this easier for someone.
Here’s OP25 in action:
And lastly here is a video of me using OP25 to track 2 Control Channels simultaneously. You’ll hear the transmissions echo in the video. That is my screencast software recording both from the microphone and speakers and not the way OP25 sounds.
On a final note just for fun I installed OP25 on a Raspberry Pi 3 B+. It works like a champ. I installed GQRX first which pulled in most everything OP25 needs and plus I use GQRX a lot anyway. OP25 takes a while to build on a Pi but it does build. If you look at the pic below the CPU usage is 40% however to get this picture I was running a VNC server as well so some of that usage is almost certainly the VNC session.
This is a living document (for a while). If you find something I should add feel free to go to my contact page and email me.
Pingback: Tutorial on Setting up OP25 for P25 Phase 2 Digital Voice Decoding - rtl-sdr.com
Thank you. Runs great on a Tinkerboard. Monitoring Louisville Metrosafe. Used the standard RTL install procedures then I used sudo apt-get install gqrx-sdr and then sudo apt-get install libvolk1-bin and ran volk_profile. Then I followed all of your steps. And just for info the -n option in OP25 somewhere near the beginning of the will block the encrypted squeals that can cause loved ones to vote you off the island.
I’m not sure why but this system has a better sound than others that I use and like.
Thanks again, have finally found a use for this SBC that I had written off months ago. As an additional note my V3 is running off a powered USB adapter, not the Tinkerboard usb power.
Ok, So far this is working out amazingly. but could i use this for Conventinal Scanning if my First Responders are using Analog and P25 convintional
What OS are you running on your Tinkerhoard? I run op25 latest build on a pi b+ and now and then the system just locks up on me.
No sound. Data channel and talk groups decoding, but no audio. Tried changing modulation types as well.
Pingback: OP25 on a Raspberry Pi (part 3) | John’s Tech Blog
Can you point me for assistance on getting Unbuntu 18 onto a Pi?
Thanks for great tutorials. Not only got op25 phase 2 running on my laptop under Ubuntu, but also got it working on my Raspberry Pi 3 perfectly!
I have a question, I am using the -n switch to silence the encrypted stuff (works fine), but is there a way to block them completely? I find sometimes the encrypted “silenced” talkgroups, over ride the non-encrypted ones and I miss some of the information. I listen to the fire departments in my area, but the police who are encrypted are on the same control channel and I will sometimes miss the dispatch of a fire call because a “silenced” talkgroup is active. Is there a way around this by chance?
Thanks again for taking the time to put this information together in a easy to understand format!!
In your .tsv file you can set Priority but you’d have to know which talk groups the encrypted stuff is generally on. Set a low priority for it.
ah, OK. I’ll give that a go then. I am getting a pretty good idea of which talk groups are the busiest and those will be my priority first.
Thanks for the reply!
How can I set priority for a particular talk group in .tsv?
The “blacklist” field in trunk.tsv tells op25 to skip a talkgroup completely and keep listening for other talkgroups; I have been putting the encrypted talkgroups on the local system in that field and it seems to work OK. See my reply further below for the details.
(Even with a talkgroup in the blacklist, if somebody transmits on that talkgroup, you will still see the talkgroup near the top of the screen, where op25 lists the last 5 frequencies it heard things on – you just won’t hear the audio for that talkgroup.)
I hope this helps!
I see all the comments about getting this going on RasPi 3 B+, but not the details on it. So could you please post the RasPi 3 B+ portion of the tutorial. A couple SDR dongles and a PI 3+ would still be cheaper than a $600 P25-PII scanner, or a $3K P25 PII radio and hoping you can keep it unaffiliated and unstunned.
Check the later posts on my blog. I did just that.
First time link user (ubuntu18-04) how and where can I check my build to ensure all is their and what not and something to compare to
I am linux stupid, but this tutorial helped me out a lot thank you. I am having trouble with setting up the whitelist I can’t seem to find it ( if you have it and I skipped it i’m sorry my brain is still fried from the commands )
Do you have to setup a new line with the nac and the whitelist every time? Or just in the whitelist box you can have many many entries?
Thanks for the tutorial. It saved me days of work. I had this working great for a few weeks but then i got a software update thru ubuntu yesterday and now its broken. I run op25.sh and it stops at setting gain LNA to 47
Any ideas how to fix it?
@ashleigh The issue I kept having is it needed a 0 in the offset column, that and double check to make sure its not saved as trunk.tsv.csv it should be trunk.tsv ,
I had this issue too
The issue was that gnuradio didn’t find the RTL-2832U SDR due to bug #528 The following website solved that issue:
Modify or create a file: etc/modprobe.d/rtlsdr.conf
and add:
blacklist dvbusbrt128xxu
blacklist e4000
blacklist rtl2832
Then reboot
I suggest you check some forums, lots of help there.
Thanks for the write-up! I got an RTL-SDR a few years ago, when P25 decoding was not as far along as it is now. I started playing with it again recently and now I have a scanner – thanks!
Some notes on how I set it up:
I found I could copy the text of the tables on Radio-Reference and paste it into LibreOffice. LibreOffice treats the paste like importing a text file, and breaks it up into columns and rows pretty much how you would expect. You can then cut it down to just the talkgroup ID (first column) and whatever you want to use for the description (second column), for the .tsv file that describes the system you want to listen to.
I used the “Description” field from Radio-Reference as the description in my .tsv file. The “Tag” field there is pretty generic; the “Alpha Tag” is a little better, but still kind of cryptic – especially on a system like the one near me, which has 800+ talkgroups. (On the other hand, “Alpha Tag” probably matches what the “official” system users actually see on the front of their radios.)
When you are first listening, you might want to have a text file or a piece of paper handy. You will probably hear some encrypted talkgroups; note their talkgroup IDs. Then, add those channels into the “blacklist” field in trunk.tsv – you can put more than one talkgroup in that cell, separating them with commas. If you wanted to ignore talkgroups 1001, 2002, and 3003, that cell would look like this:
1001,2002,3003
Save trunk.tsv and restart the scanner program and op25 will then skip those talkgroups. (There is an -n option to rx.py to ignore encrypted channels, but if you use that, op25 will still stop on an encrypted talkgroup for as long as someone is transmitting on that talkgroup. Putting the talkgroup in the blacklist makes op25 skip it immediately and keep checking for other transmissions.)
Thanks!
Thank you so much for putting this information out there. I’m almost completely new to Linux and was able to follow along very easily. I was able to successfully get OP-25 running on Ubuntu 18.04 LTS with a RTL-SDR v3 dongle. Thank you again for this excellent writeup.
Is there an way to get OP25 to work with multiple RTL-SDR dongles? The reason I ask that is that I monitor the Ohio MARCS P25 system where the frequencies can span 6 Mhz. I would like to constantly monitor the control channel with a single dongle and let the others take care of bouncing around.
The way it works today is that it will jump from the control channel to a listening channel to listen to a specific talk group. I generally hear one side of the conversation since the control channel cannot tell me then next channel for the reply in time.
Another user will reply to a call for that talk group but will appear on a different channel. I will miss that since the control channel isn’t constantly monitored. Three dongles would suffice in this situation.
I’ve been looking for many months but haven’t had much luck. The only think close would be trunk recorder, which is a path really don’t want to take due to its intense use of resources.
Did you ever figure this out? I was wondering the same thing.
Did it stop working for you on 2019.01.18? I just tried listening and I get errors in the stderr file. I went to make sure I was on the correct freq and it looks like the radioreference.com site updated on the 18th as well, which seems to be a huge coincidence.
I too am wondering if there is a way to have multiple dongles monitoring different frequency ranges?
I ran Unitrunker V2 on Ohio MARCS and it ran great with multiple dongles.
John, greetings from the Triangle. Your tutorials – especially this one on OP25 – were a great comfort during the recent storms. I recently bought an ADALM-PLUTO, and I’m finding a strange behavior – I can be zeroed right on the control channel, but the actual communication channels always seem to be too offset for me to recover audio. Have you seen such similar behavior on the Pluto?
I have to set my Pluto at q 5 and then if it gets hot in the room have to set it to q 6. It’s kind of drifty but playing around with it a bit you should find the magic range.
What a magnificent tutorial – *very* much needed – thanks again!
Thanks for this tutorial. I can now listen to my county’s Phase II TDMA with a nesdr smart on MATE 1.20.1. I had to lose the “2> stderr.2” from the launch script in order to get it to work for me.
I was also able to copy and paste the data from Radio Reference like Matt R. above.
John, check out my blog post about using your instructions to successfully get this working! Thanks for the info!
Outstanding write up. Thanks for sharing it here. It will only serve to help others get OP25 up and running with a Pi. I recently added a couple other blogs where I was playing around with DSDPlus and came to the conclusion that while DSDPlus is better eye candy, the superior decoder by a longshot is OP25. The fact you can run it on a Raspberry Pi is icing on the cake.
Can someone please tell me how to get Alhambra PD to work? The only 2 freuencies I need are 471.1375 and 471.1000 but I think it’s conventional phase I. Please help
Hello, I am using ubuntu 18.04 and i have been having trouble getting the line:
git clone
to facilitate. I have tried sudo apt-get install, etc, but no good. Previously i was using Ubuntu 16.04 and it ran flawlessly. Any Ideas ??
Regards
Oh, just love your blog. Simple is better and as a Robotics Engineer, I have found many mistakes by backing off original thoughts and Keeping It Simple !!
Kirk
Did you install git? sudo apt-get install git
You can also go to that GitHub page and download the zip file and unzip it where you want it.
Hi John, You are a masterful teacher. Thanks for assisting a WIN 10 guy with a functional installation on Ubuntu. With your assistance, I’ve got OP25 working in Virtualbox with the exception of the audio – the next project…
I’ve got this working on my raspberry pi 3.
Something cool that might benefit others is, if you’re lazy like me, set an alias for op25.sh
In Terminal:
sudo nano .bashrc
##OP25 alias
alias op25=’bash /home/pi/op25/op25.sh’
Close terminal and open it back up. You can now run your command by typing op25 as soon as the terminal opens, without changing directories.
CTRL+X, Y, Enter
after typing:
alias op25=’bash /home/pi/op25/op25.sh’
for some reason the CTRL+X, Y, Enter was missed when I tried to post comment.
Next time I launch OP25 on one of my Linux computers I’ll give that a try and then add it to the tutorial. Thanks!
I also added another alias that starts my services, but I’ll post that on Part 2 as the alias covers other items than covered here, Works well if you have to log in VNC to run your commands. .. I get to the point in the install that I send the rx.py line then I get errors and go no further…I get messages say things like source failure etc …and I deleted the last two commands but no joy
Here is a screen capture
I using windows 10 and a RTL 2832 type unit wchich works under SDRSharp.
Would really appreciate a little help if you can spare the time
Cheers
Andrew
Are you using a Virtual Machine of Ubuntu under Windows? I looked at your pic and I don’t think you are seeing your USB SDR device. If you are using Virtualbox you need to enable the USB device that is plugged in.
Soory .. didnt know I needed VBox.. installing know but seems more confusion on my part
You don’t need Virtualbox if you are using Linux already.
OK…. so without VB what do i need to do to see the RTL ..?
Sorry .. a slow process
A
Is some other program using it? have you tested the SDR under Linux? By using GQRX or some other program?
Its looking like I have some Ubuntu issue… took suggestion an installed GQRX.. no errors during install but get
XDG_RUNTIME_DIR not set, defaulting to ‘/tmp/runtime-useradd’ error
and a
QXcdConnection: could not connect to display error
so cant even run GQRX
Searching ….
I have OP25 running on a Pi3, can see the control channel processing TGIDs, decoding voice, and showing TG alias, but it only lasts for a few moments. The program will still be displaying the stream of calls, but stops decoding voice. I am just a few hundred yards from the prime site, so signal strength is not an issue.
I am really impressed with the audio decoding in OP25 but I cannot get it to last more than a few minutes, if that. Any suggestions?
What size is the power brick you are using? I strongly recommend a 2 amp or slightly higher brick.
Yes sir. I am using a 2.1a brick. I have messed with sampling rates and LNA and nothing keeps it going for more than 30 secs or so. I’m watching it change frequencies and display TGs as it should, but audio just stops dr oding.
not a good start
lenovo@lenovo:~$ git clone
Command ‘git’ not found, but can be installed with:
sudo apt install git
lenovo@lenovo:~$ sudo apt install git clone
[sudo] password for lenovo:
Reading package lists… Done
Building dependency tree
Reading state information… Done
E: Unable to locate package clone
E: Unable to locate package
E: Couldn’t find any package by glob ‘’
E: Couldn’t find any package by regex ‘’
lenovo@lenovo:~$
you just need to install git first
sudo apt install git
and then
git clone
up and going at step ; ./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2400000 -f 168.0934e6 -o 25000 -q -2 -T trunk.tsv -V -2 -U 2> stderr.2
seeing 4 or so voice frequencies updating but no audio coming through?
alsa plugin in audio settings is up, but i cannot hear anything
could it be the frequency drift on my sdr, it states a control channel for me as 168.100 on the website but im tuned to 168.0934 to get a good RX , could that throw out is tuning correctly to the frequency when it changes to grab the audio?
Pingback: Setting up OP25 Scanner Trunking on an Ubuntu Virtual Machine | RadioHobbyist.org
I am confused about control freq and talk groups for LARGE systems. My county, Shelby County Alabama is a part of the Alabama First Responders Network. Shelby County Has 5 different control frequencies, see .
Within the Shelby County designation, there are 40-50 talk groups. I obviously do not need to tune to ALL of these TG’s. Is each TG associated with a specific control channel or ALL control channels? My question is, how do I know which talk group is linked to which control channel, or does it matter?
This guy explains whitelists (same could be used for blacklists) better than here. Mostly whitelist is priority, where blacklist ignores those TGs.
What if you are trying to set up for a certain county in Zone 3 of the NC VIPER System? Anybody tried this before? I see the site frequencies for each site but nothing for the county in particular.
So I am tuned to STARCOM21 773.84375c but only want to monitor two TG, 2609 and 2676. Do I have to put all of the other TGs in the blacklist even if i’m using the TGID Tags File with only two TG like we have here in the instructions?
I had this running in one shot, awesome instructions!!!
very newbie here. can you tell me what I would need to use the Texas Wide Area Radio Network (TxWARN) Motorola??
hi,
mine run perfectly working, but how can the tgid from the user not shown, only the group call
It’s working! Only issue is that I wanted to only listen to certain talk groups, but I think I’m picking up pretty much my entire state because our Simulcast system works that way. How might I listen only to a few talk groups rather than all of them?
Update: Found it. Was looking for a whitelist
Running RTL-SDR v3 and just no luck getting nac – have played w/ sample rate, offset, gain, Q and it just never dislays… No problem using unitrunker so I know I have the right control frequency. rtl_test gives correct output, gqrx works; just can’t get the ./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2400000 -f489.0750e6 -o 25000 -q –2 to produce any lines. Using ubuntu 1804 – have tried multiple dongles, even (2) machines..
should have mentioned – trying to follow marin emergency radio authority. no problem w/ unitrunker 2 and dsdplus on a windows machine using 2 dongles
Trying tune MERA (Marin County) and get a GNU constellation plot that looks like a semicircle from +5 to +5 using control frequency 489.075. I know that is good because it works with Unitrunker. Also know that my system is set up properly because I am able to set up my command line and trunking tsv and to decode Golden Gate Bridge District at 771.331250. Does OP25 not work for Motorola Type II Smartzone?
If you add -l http:127.0.0.1:8080 to the end you can enable the web interface, which in my opinion looks better. Radio Reference is a huge help for finding control channel frequencies, NAC, and talk group IDs.
If your having a problem with Make giving an error during build. Please make note of this page. My observation appears to correct this. But I am still in the process of getting this up and running.
Update from last comment: If your having a problem with Make giving an error during build. Please make note of this page. My observation appears to correct this. But I am still in the process of getting this up and running.. Please note this has to do with recent OP25-Master.zip download Modified 16 June 2019 06∶04∶52 PM EDT
I followed all the build steps with a Pi3B and have properly tuned in a known Phase 1 control channel with about 20 dB S/N. I get an “Allocating 15 zero copy buffers” instantly upon running :
./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2400000 -f 850.600e6 -o 25000 -q 5
#5 graph confirms the control channel is tuned
#2 shows clusters in the NW and SW corner with the eastern half a continous arc rather than clusters.
Using device #0 Generic RTL2832U SN: 712733086766700]
I will try lowering the bandwidth from 2.4 Megs to 1 or 2 Megs
Anything else I can try?
Here’s a way to automatically name your stderr.2 log so they aren’t overwritten each time OP25 is run. Simply it just creates a variable called “today” with todays date and time and appends it to the log file name. This would be saved as a .sh and ran
#! /bin/sh
cd /home/michael/op25//op25/gr-op25_repeater/apps
today=`date ‘+%F_%I:%M:%S-%p’`;
./rx.py –args ‘rtl’ -N ‘LNA:47’ -o 25000 -q -2 -T trunk.tsv -V -2 -U 2> “$today”__log.2 -l http:0.0.0.0:8080 -n -d -300 -v 8 -t
Got this up and running. Is there any way to modify one of the files to output the frequency and talkgroup info to a simple 16×2 LCD panel? Would like to free up a display and make the whole setup portable with the LCD as the display.
Thanks so much for this awesome guide. Most of the local PD and Fire in Southwestern Va are analog but the State Police are on P25 Phase 1. I had been trying to get this to work for a while until I stumbled across this post. I had no issues getting up and running once I was here.
I did your initial instructions on the install then rebooted and cd into /op25/op25/gr-op25_repeater/apps
then tried your args to see if it runs. then it returns with
Traceback (most recent call last):
File “./rx.py”, line 52, in
import op25
ImportError: No module named op25
Is not working please help me.
you may have missed the install command:
cd op25
./install.sh
Using an NESDR, I can launch the first part to get the NAC
but when I try to launch with the trunk file, I get this error. anyone else see this?
./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2400000 -f 859.7625e6 -T trunk.tsv -V -2 -U
linux; GNU C++ version 7.3.0; Boost_106501; UHD_003.010.003.000-0-unknown
gr-osmosdr v0.1.x-xxx-xunknown (0.1.5git) gnuradio 3.7.11
built-in source types: file osmosdr fcd rtl rtl_tcp uhd plutosdr.
op25_audio::open_socket(): enabled udp host(127.0.0.1), wireshark(23456), audio(23456)
p25_frame_assembler_impl: do_imbe[1], do_output[0], do_audio_output[1], do_phase2_tdma[1], do_nocrypt[0]
Traceback (most recent call last):
File “./rx.py”, line 921, in
rx = rx_main()
File “./rx.py”, line 835, in __init__
self.tb = p25_rx_block(self.options)
File “./rx.py”, line 196, in __init__
self.open_usrp()
File “./rx.py”, line 762, in open_usrp
self.__set_rx_from_osmosdr()
File “./rx.py”, line 690, in __set_rx_from_osmosdr
self.__build_graph(self.src, capture_rate)
File “./rx.py”, line 323, in __build_graph
self.trunk_rx = trunking.rx_ctl(frequency_set = self.change_freq, debug = self.options.verbosity, conf_file = self.options.trunk_conf_file, logfile_workers=logfile_workers, meta_update = self.meta_update)
File “/home/db/op25/op25/gr-op25_repeater/apps/trunking.py”, line 659, in __init__
self.build_config_tsv(conf_file)
File “/home/db/op25/op25/gr-op25_repeater/apps/trunking.py”, line 741, in build_config_tsv
nac = int(fields[‘nac’], 0)
KeyError: ‘nac’
Here is my trunk file seutp —
Sysname Control Channel List Offset NAC Modulation TGID Tags File Whitelist Blacklist Center Frequency
Troop L 859.7625 0 0x3a1 CQPSK tompkins.tsv 859.7625
I had a similar error. I fixed it by removing the CR LF at the end of the trunk.tsv file.
Pingback: OP25 For P25 Phase 2 Digital Voice Decoding | VA3DBJ.ca
This is badass! I used VirtualBox on a Windows 10 box for the Ubuntu install. Took a couple extra steps to get it working but man, this is amazing! Thank you so much for the detailed instructions.
Thanks for the tutorial. Got it up and running on Linux Mint after my county switched to a P25 system from analog. I see a new scanner purchase in the not too distant future, but I couldn’t beat the cost of the RTL-SDR to find out what is or is not encrypted before spending a minimum of $350 on a new one.
Have changed the -q -2 to everything between (-5 thru +6) and can’t get NAC ??? I get the wave and spike that is right on the freq. I’ve set 853.0625 some of the setting produce the rolling oooooooo
GQRX work fine and I can hear control channel. Using NooElec NESDR Nano 2+ Tiny Black RTL-SDR USB Set (RTL2832U + R820T2)
Anyone know what else I can try to get the NAC I need to continue or can I get the NAC elsewhere. ?
Jeff, I think you and are are seeing the same problem. Which state and county are you in?
I got this working by following your Awesome instructions! Thank you so much. I’m having trouble with the bash script for starting tho. I’ll come BK tommorow and be more specific.
Hey John,
I know this is an older blog post but I wanted to focus your attention on a bug myself and many others have run across during the installation of OP25. I’m familiar and comfortable with Linux, but what follows is absolutely a layman’s interpretation of a complex issue regarding the compiling of OP25 via cmake and the included install.sh executable.
Later versions of cmake are encountering errors during the compile process. Specifically, this error:
make[2]: *** No rule to make target ‘op25/gr-op25_repeater/swig/op25_repeater_swig.py’, needed by ‘op25/gr-op25_repeater/swig/op25_repeater_swig.pyc’. Stop.
make[1]: *** [CMakeFiles/Makefile2:954: op25/gr-op25_repeater/swig/CMakeFiles/pygen_op25_gr_op25_repeater_swig_a9103.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
After compiling, either via install.sh or following OP25’s included compile instructions, running rx.py returns this error:
Traceback (most recent call last):
File “./rx.py”, line 52, in
import op25
ImportError: No module named op25
The fix for me and, from what I can tell, a few others, was to revert cmake to 3.10.3. I won’t try to explain the root of the problem; suffice it to say, commits later than 3.10.3 introduce and fail to correct an issue that impacts swig dependency parsing. It’s documented by both the devs for cmake and OP25.
Again, the fix for me was to uninstall cmake 3.13.x and build cmake 3.10.3 from source (only way I could get it to compile OP25 correctly – pointing cmake at the earlier version without “installing” it on the system wouldn’t fix the error). This page goes into the problem in more detail:
As this blog/tutorial is still called a “living” document, you might want to consider adding a note in the installation procedures indicating users can encounter this problem.
For reference:
NOOELEC NESDR SMART
RASPBERRY PI 4 MODEL B
RASPBIAN – CLEAN INSTALL WITH A DIST-UPGRADE, GQRX, AND RTL DRIVERS
The latest versions of both osmocom and boatbod versions of OP25 have an (experimental) “-X” command line option to automatically adjust tuning. Older rtl dongles needing significant ppm correction will probably still have to be set up somewhere close for tracking to be effective, but modern dongles should be largely plug an play.
Awesome! Thanks for the update!
Hi.
Is there any chance we could get a live CD or VM as I’ve followed all of the instructions and it simply does not work on Ubuntu 18.04.4 LTS
Even reading from a file does not work Errors like this….
user@user-virtual-machine:~/op25/op25/gr-op25_repeater/apps$ sudo ./rx.py –args ‘file’ -O pulse
linux; GNU C++ version 7.3.0; Boost_106501; UHD_003.010.003.000-0-unknown
FATAL: No file name specified.
Trying to fill up 1 missing channel(s) with null source(s).
This is being done to prevent the application from crashing
due to gnuradio bug #528.
Traceback (most recent call last):
File “./rx.py”, line 986, in
rx = rx_main()
File “./rx.py”, line 899, in __init__
self.tb = p25_rx_block(self.options)
File “./rx.py”, line 150, in __init__
sys.stderr.write(‘RTL Gain of %d set to: %.1f\n’ % (gain, self.src.get_gain(‘LNA’)))
UnboundLocalError: local variable ‘gain’ referenced before assignment
user@user-virtual-machine:~/op25/op25/gr-op25_repeater/apps$ sudo ./rx.py –args ‘file’ -i ‘cow’ -O pulse
Traceback (most recent call last):
File “./rx.py”, line 986, in
rx = rx_main()
File “./rx.py”, line 899, in __init__
self.tb = p25_rx_block(self.options)
File “./rx.py”, line 207, in __init__
self.open_file(options.input)
File “/usr/lib/python2.7/dist-packages/gnuradio/gr/hier_block2.py”, line 92, in __getattr__
return getattr(self._impl, name)
AttributeError: ‘top_block_sptr’ object has no attribute ‘open_file’
Windows programs like DSD+ work fine, Linux based apps always seem broken and require a 300 IQ just to get things working 🙁
I had to set my -S to 1000000 to get it to work, after that it was fine.
I am in Montgomery County, MD trying to use OP25 to monitor the police and fire system.
I’m a programmer, have good Linux skills, and considerable RF skills, so I’m ready to try anything.
The plaform is a Raspberry Pi 3b.
GQRX hears and shows a strong signal on the primary control channel frequency, 853.8625. There’s also a strong signal on alternate control channel 853.6875.
Also, I can turn in local FM, VHF ham radio, etc. stations reliably with GQRX. The audio is excellent. So my dongle appears to be fine.
Using a standalone scanner, I’ve verified the primary control channel frequency is the current control channel, 853.8625.
I’m trying to find the NAC by running:
./rx.py –args “rtl” -N ‘LNA:47’ -S 2400000 -f 853.8625e6 2>stderr.2
And that gives nothing on the screen except “Frequency 853.862500(0)” in the bottom left corner. This should give me the NAC and other info in the upper left of the screen, but that area is blank.
Even though I know the control channel is on 853.8625, I tried the same command but specified the alternate, 853.6875e6, as the control channel frequency. That gives me the following in the upper left corner:
NAC 0x8e2 WACN 0xbee00 SYSID 0x8e0 853.687500/808.687500 tsbks 114
That looks sort of good. But if I then use the secondary control channel and NAC 0x8E2 in the trunk.tsv file, the screen still does not show any voice activity.
The spectrum plot (option 1 plot) does show the peak for the control channel that I’ve selected.
And I still don’t know why I can’t get the NAC for the primary control channel to appear since I know it’s the control channel that is in use, based on watching my standalone scanner.
The stderr file does not show anything that seems abnormal. Here it is when specifying the primary control channel in the rx.py command line:
—————————————————-
gr-osmosdr 0.1.4 (0.1.4) gnuradio 3.7.13.4
built-in source types: file osmosdr fcd rtl rtl_tcp uhd]
metadata update not enabled
Allocating 15 zero-copy buffers
Flowgraph completed. Exiting
—————————————————-
So what I’m mainly looking for is the NAC for the system at this point. Once I get that to appear on the screen when specifying the primary control channel on the command line, everything else should hopefully fall into place.
Any suggestions would be appreciated.
Try this:
./rx.py –args “rtl” -N ‘LNA:47’ -S 2500000 -f 853.8625e6 -o 17e3 -q 0
play with the q value until you get a signal.
It turns out that the system that generated the NAC is a P25 in test using one of the alternate control channels. It is overlaid with the current operational system, which is Smartzone II running at 3600 baud. OP25 is not capabile of decoding a Smartzone II running at 3600 baud, so I’m going to have to use a different solution.
Update: OP25 has been enhanced to support Smartzone systems as of July 2020. See the most recent information on github.com.
Great guide…however I can’t get the GNUplot to work when i push the number 1. I am installed on a pi 3B+.
any help ???
Works perfectly on my pi 3B+ running Ubuntu Mate OS. Using sdr blogV3 and a small homeade discone antenna hanging on the gutter of my condo. The web interface is the icing on the cake. More sensitive than my Uniden Home Patrol 2 which I sold. Thanks for your great work on this!
Works great on my dedicated Linux Mint 19.3 12 year old HP machine with RTL-SDR V3. Using a 7 element 900 MHz Yagi with 50′ of 20 year old 9913. Seems to be immune to simulcast distortion (Albany County, NY – APCO-25)! That was the reason behind the Yagi (aimed at the closer tower with the side to the other 2 towers). Turns out an OMNI antenna works as well!
I am really new. I’m sure this is a dumb question but how do you go about installing an older version of cmake on ubuntu. I googled it extensively and have come up empty handed. I just know how to install the newest version. Thanks tp anyone that can help.
Download a pre-compiled binary from cmake’s website, or build it from source.
(Dont install it if you want to keep your systems version of cmake).
Then just edit the op25 install.sh script and change the line near the bottom that says:
cmake ../
to
~/where/you/put/cmake/binary ../
If you already tried installing with the newer cmake, then just edit the rebuild.sh script the same way instead.
Good luck.
I go thru all the steps with no errors. However when I run the last command indicated this is what happens. Any ideas as to what is going on? Thanx.
Wow, thank you for writing this up! BTW, I have it working on a Chromebook, using Linux.
I wrote up a quick explanation how to was able to get this working on a Chromebook. In case anyone is interested.
Great tutorial!!! First time using a sdr-rtl. I got op25 running on peppermint 10 first try. Thanks so much.
Does anyone have a decoder for the keyboard data from and to the cruisers ?
Please contact me at
After newbern.tsv is created (I used exactly what you used), then I inputted the line ./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2500000 -x 2 -f 769.80625 17e3 -T trunk.tsv -V -2 -U 2> stderr-stream0.2, it goes right to a command prompt. It does absolutely nothing. I did copy and paste the line and changed the frequency.
Any idea what would be happening?
Make sure the “cityname.tsv” you saved with your talk groups/tags is named exactly as you put it in your trunks.tsv. If you didn’t change the file extension when you saved it, it may have saved as cityname.tsv.csv.
Thanks you SO much! I can’t believe how easy this was to set up, thanks to your instructions. I’m a complete noob to this radio stuff, just got my rtl-sdr a couple of weeks ago, and just learned to follow the phase I signals with unitracker a couple of days ago. This works so much better, and I love how the alpha tag let’s you see which agency you’re listening to. I can’t imagine how long it would have taken me to fumble my way through figuring this out without your help.
You are welcome. It took me several sessions over the course of a YEAR to figure this all out. The minute I did I wrote the Barney style instructions and saved them for posterity mostly for myself so I could repeat the installation if I needed to. To date this has been my most visited and useful page on my blog.
I would like to add, on the op25.sh script you can just type “source ~/.bashrc” to reload it without having to restart your terminal.
And thanks again. I just passed this on to another guy who’s just getting into this and hadn’t heard of op25.
Great instructions. Thanks! Have it up and running on Pi 3B+. Running it side-by-side with DSD+ FastLane running on my Windows 10 PC so I can validate it. On the Pi I see it tracking the calls and decoding. However it doesn’t always get the audio that the Windows 10 PC software does. They are running on the same antenna system (a high gain TV beam antenna) and the signal trace is strong on both machines. Audio quality when it does come through on the Pi is great! Is there some setting that might be clipping part of the transmissions and blocking the audio?
this is great, both the blog and the developer of OP25. i’ve been listening to OP25 installed on rpi4 for almost 2 months now, and it is fantastic.
at first, i was amazed how simple it was ( and lately i found out how powerful it is), though i wasnt satisfied with the terminal version, i now move to web gui version, and change the whole screen black and white, just like the terminal.
web gui OP25 have bigger buttons, and i can zoom in to the scale i feel comfortable, so whenever i hear voice decoded, i can also see the TGID and the alphatag.
i also using priority feature on the alphatag file, everytime higher priority TG appears, OP25 will override the decoding to higher priority TG(s). blacklist also useful for me, to avoid certain TGs i dont wanna hear, i can do it temporarily by hitting blacklist button and enter the TG (reset after OP25 restarted) or permanently by entering TG(s) on the trunk.tsv
thank you John (and also boatbod) for this post on your blog, i believe you have helped so many people to know OP25, simple and powerful P25 trunktracker. cheers!
./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2500000 -x 2 -f 857.2625e6 -o 17e3 -q 2
AttributeError: ‘NoneType’ object has no attribute ‘get_gain_names’
I follow all the steps and can get everything to work until I add the .tsv file in. When I do that it does not show the correct control Channel at the top just 000000/000000. I have confirmed it’s saved as .tsv not tsv.csv. Tried putting a 0 in the offset. Tried it with out. Nothing! any suggestions?
Well I love this. Just wish I knew what I was doing to get it running. I did all the steps but no joy on running last command on getting things to work.
So when I run.
./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2500000 -f 773.95625e6 -o 17e3 -q -2 -T trunk.tsv -V -2 -U 2> stderr
All I get its its telling me options I need. I’m not going to paste it all in here its quit long.
pi@raspberrypi:~/op25/op25/gr-op25_repeater/apps $ ./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2500000 -f 773.95625e6 -o 17e3 -q -2 -T trunk.tsv -V -2 -U 2> stderr.2
Usage: rx.py [options]
Options:
-h, –help show this help message and exit
–args=ARGS device args
–antenna=ANTENNA select antenna
-a, –audio use direct audio input
-A, –audio-if soundcard IF mode (use –calibration to set IF freq)
-I AUDIO_INPUT, –audio-input=AUDIO_INPUT
pcm input device name. E.g., hw:0,0 or /dev/dsp
-i INPUT, –input=INPUT
Thats the short version. When I run it like this.
./rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2500000 -f 773.95625e6 -o 17e3
I get all the info I need. I did test it with the Gqrx and everything works okay. I also plugged in a USB audio card into the PI and its all work. I guess I should have started with that. I am using a PI4.
Anyway any help would great. Thanks for all the post here. I did skip some cause I wanted to get the the bottom and Im going to go back up and read more.
Thanks
Jay
Try this and of course change your freq and -q
/rx.py –args ‘rtl’ -N ‘LNA:47’ -S 2500000 -x 2 -f 857.2625e6 -o 17e3 -q 0 -T trunk.tsv -V -2 -U 2> stderr-stream0.2
Current op25.sh now only needs a control channel to work, you don’t even need to the NAC or tsv files. Find your control channel(s) on radioreference.com (like John’s guide tells you) and write it/them down. Launch the terminal, go to you to your user home directory with the cd command:
cd
git clone
cd op25
./install.sh
y
#You’ll want to restart before attempting to run op25, you can reboot from command line with:
reboot
cd ~/op25/op25/gr-op25_repeater/apps
#the next command sets control channel(s) in the op25.sh file for you:
./setTrunkFreq.sh 854.3875,858.9625
#make sure your SDR is plugged in to the computer before starting it up…or of course it won’t work.
./op25.sh
Thanks. I’ll test this later and update my guide. Awesome!
Holy Bejeebus!!, after three nights scratching my head I scrolled down to read this and tried it and it worked!! Now I am going to go buy some champagne. Thank You!!!!!!!!!!!!!!!!!!!!!! | https://www.hagensieker.com/wordpress/2018/07/17/op25-for-dummies/?replytocom=16872 | CC-MAIN-2021-21 | refinedweb | 8,710 | 75 |
An Array is a sequential collection of elements, of the same data type. They are stored sequentially in memory. An Array is a data structure that holds similar type of elements. The array elements are not treated as objects in c++ like they are in java. In this this article we would discuss Arrays In C++.
Arrays In C++
Imagine you are at a music record store and I tell you to arrange all the records under the label XYZ Records at one place one above the other. This sequential collection of records can be called an Array. An array is a sequential collection of elements of the same data type. In our example above, XYZ Records is the data type and all the records you collected have the same publishers. All the elements in an array are addressed by a common name.
This article on Arrays in C++ will focus these base pointers,
- Single Dimensional Array
- Initialization During Declaration
- Initialization By A User
- Accessing Array At Any Point
- Multi Dimensional Array
Let us start by understanding what are single dimensional arrays,
Single Dimensional Array
Syntax for declaring a Single Dimensional Array:
We have a data type that can be any of the basic data types like int, float or double. Array Name is the name of the array and we declare the size of the array. In our above example, the array will be,
XYZ Record recordArray[100];
Let’s consider another example:
int test[20];
The array test will hold the elements of type int and will have a size 20.
Arrays In C++: Array Size
Array size is given at the time of declaration of the array. Once the size of the array is given it cannot be changed. The compiler then allocates that much memory space to the array.
Consider the Example
int test[20];
In the example above, we have an array test, of type int. We have given the array size to be 20. This means that 20 consecutive memory locations will be left free for the array in the memory.
Array Index And Initialization
A number associated with each position in an array and this number is called the array index. Its starts from 0 and to the last element, that is the size of the array minus one. The minus one is there because we start counting from zero and not one. Array indices always begin from zero.
Consider this example, this is the age array.
Here the array contains the values 12,41,3,13,7 and the indices are 0,1,2,3,4,5. If we want to represent an element at index 4 it is represented as age[4] and the value 7 will be displayed.
By default, the array contains all zero values. Array initialization is done at the time of declaration. This can also be carried out later if the user enters the array value as and when needed.
Let us see how initialization works during declaration,
Initialization During Declaration
An array can be initialized during declaration. This is done by specifying the array elements at the time of declaration. Here the array size is also fixed and it is decided by us.
Consider the code,
#include<iostream> using namespace std; int main() { int arr[] = { 10, 20, 30, 40 } ; return 0; }
Explanation
In the above example, we create an array of type int and with the name arr. We directly specify the array elements. The size of the array is decided by counting the number of elements in our array. In this case, the size is 4.
Next in this article on Arrays in C++ lets us see how Initialization by a user works
Initialization By A User
In this method, we let the user decide the size of the array. In this case, we need a variable to hold the size of the array and a for loop to accept the elements of the array. We assign a random size at the time of declaration and use only as needed. The size at the start is usually at the higher side. We have a variable i to control the for loop.
Consider the example,
#include<iostream> using namespace std; int main() { int arr[50],n,i ; cout<<"Enter the size of array:"<<endl; cin>>n; cout<<"Enter the elements of array:"<<endl; for(i=0;i<n;i++) { cin>>arr[i]; } return 0; }
Output
Explanation
In the above program, we declare an array of size 50. We then ask the user to enter the number of elements he wishes to enter in this array. We then accept the array elements entered by the user.
Arrays In C++: Displaying the Array
Displaying the array also requires the for-loop. We traverse to the entire array and display the elements of the array.
Here is an example,
#include<iostream> using namespace std; int main() { int arr[50],n,i ; cout<<"Enter the size of array:"<<endl; cin>>n; cout<<"Enter the elements of array:"<<endl; for(i=0;i<n;i++) { cin>>arr[i]; } cout<<"Array elements are:"<<endl; for(i=0;i<n;i++) { cout<<arr[i]<<"t"; } return 0; }
Output
data-src=
Explanation
In the above program, we declare an array of size 50. We then ask the user to enter the number of elements he wishes to enter in this array. We then accept the array elements entered by the user. We then use a for loop again to display the array elements.
Moving on with this arrays in C++ article,
Accessing Array At Any Point
Accessing array elements is simple and is done by using the array index. Have a look at the code below.
#include<iostream> using namespace std; int main() { int arr[5],i ; arr[4]=2; arr[2]=17; arr[0]=17; cout<<"Array elements are:"<<endl; for(i=0;i<5;i++) { cout<<arr[i]<<"t"; } return 0; }
Output
data-src=
Explanation
In the program above, we have an array of size 5. We enter elements at different locations using array index. We print the array to get the above output.
By Default, all the array elements are zero.
What happens if we cross the array size?
In c++, if we try to access the elements out of bound, error may not be shown by the compiler but we will not get proper output.
This bring us to the final bit of this arrays in C++ article,
Multi Dimensional Array
Arrays of arrays are multi-dimensional arrays. This is because each element in a multi-dimensional array has an array of its own. We need n for loops to iterate through a multidimensional array depending on the dimensions.
Syntax For Declaring Multi Dimensional Arrays
Datatype arrayname[size1][size2]…..[size n]
int a[10][20];
Consider the example,
The size of the above array will be 10*20 that is 200 elements. Similarly, we can have two or three or even more dimensional arrays. Each dimension requires one for loop. So, the two-dimensional array requires two- and three-dimensional array requires three.
Consider the code
#include<iostream> using namespace std; int main() { int arr[3][2] = {{0,1}, {2,3}, {4,5}}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { cout << "Element:"; cout <<arr[i][j]<<endl; } } return 0; }t
Output
data-src=
Explanation
In the above code, we display a 3*2 matrix. This array has 3 rows and 2 columns. We have 2 for loops. Each responsible for one dimension of the array. The outer for loop takes care of rows and inner of columns.
Similarly, we can write a code for three-dimensional array and there will be three for loops and each dimension will be controlled by one for loop.
Thus we have come to an end of this article on ‘Arrays | https://www.edureka.co/blog/arrays-in-cpp/ | CC-MAIN-2019-35 | refinedweb | 1,313 | 63.09 |
I came late to personal computing, which was born with the MITS Altair in 1975.
The first PC I ever met — and wanted desperately, in an instant — was an Apple II, in 1977. It sold in one of the first personal computer shops, in Durham, NC. Price: $2500. At the time I was driving one of a series of old GM cars I bought for nothing or under 1/10th what that computer cost. So I wasn’t in the market, and wouldn’t buy my first personal computer until I lived in California, more than a decade later.
By ’77, Apple already had competition, and ran ads voiced by Dick Cavett calling the Apple II “The most personal computer.”
After that I wanted, in order, an Osborne, a Sinclair and an IBM PC, which came out in ’82 and, fully configured, went for more than $2000. At least I got to play with a PC and an Apple II then, because my company did the advertising for a software company making a game for them . I also wrote an article about it for one of the first issues of PC Magazine. The game was Ken Uston’s Professional Blackjack.
Then, in 1984, we got one of the very first Macs sold in North Carolina. It cost about $2500 and sat in our conference room, next to a noisy little dot matrix printer that also cost too much. It was in use almost around the clock. I think the agency had about 10 people then, and we each booked our time on it.
As the agency grew, it acquired more Macs, and that’s all we used the whole time I was there.
So I got to see first hand what Dave Winer is driving at in MacWrite and MacPaint, a coral reef and What early software was influential?
In a comment under the latter, I wrote this:
One thing I liked about MacWrite and MacPaint was their simplicity. They didn’t try to do everything. Same with MacDraw (the first object- or vector- based drawing tool). I still hunger for the simplicity of MacDraw. Also of WriteNow, which (as I recall) was written in machine, or something, which made it very very fast. Also hard to update.
Same with MultiPlan, which became (or was replaced by) Excel. I loved the early Excel. It was so simple and easy to use. The current Excel is beyond daunting.
Not sure what Quicken begat, besides Quickbooks, but it was also amazingly fast for its time, and dead simple. Same with MacInTax. I actually loved doing my taxes with MacInTax.
And, of course, ThinkTank and MORE. I don’t know what the connection between MORE and the other presentation programs of the time were. Persuasion and PowerPoint both could make what MORE called “bullet charts” from outlines, but neither seemed to know what outlining was. Word, IMHO, trashed outlining by making it almost impossible to use, or to figure out. Still that way, too.
One thing to study is cruft. How is it that wanting software to do everything defeats the simple purpose of doing any one thing well? That’s a huge lesson, and one still un-learned, on the whole.
Think about what happened to Bump. Here was a nice simple way to exchange contact information. Worked like a charm. Then they crufted it up and people stopped using it. But was the lesson learned?
Remember the early Volkswagen ads, which were models of simplicity, like the car itself? They completely changed advertising “creative” for generations. Somewhere in there, somebody in the ad biz did a cartoon, multi-panel, showing how to “improve” those simple VW ads. Panel after panel, copy was added: benefits, sale prices, locations and numbers, call-outs… The end result was just another ugly ad, full of crap. Kind of like every commercial website today. Compare those with what TBL wrote HTML to do.
One current victim of cruftism is Apple, at least in software and services. iTunes is fubar. iCloud is beyond confusing, and is yet another domain namespace (it succeeds .mac and .me, which both still work, confusingly). And Apple hasn’t fixed namespace issues for users, or made it easy to search through prior purchases. Keynote is okay, but I still prefer PowerPoint, because — get this: it’s still relatively simple. Ugly, but simple.
Crufism in Web services, as in personal software, shows up when creators of “solutions” start thinking your actual volition is a problem. They think they can know you better than you know yourself, and that they can “deliver” you an “experience” better than you can make for yourself. Imagine what it would be like to stee “service” world we’re in now, and we’re in it because we’re just consumers of it, and not respected as producers.
The early tool-makers knew we were producers. That’s what they made those tools for. That’s been forgotten too.
I wrote that in an outliner, also by Dave.
Interesting to see how far we’ve come, and how far we still need to go.
Bonus link, on “old skool”. | http://blogs.harvard.edu/doc/2013/01/29/old-skool-influential-software/ | CC-MAIN-2016-22 | refinedweb | 860 | 75.1 |
GPU Monitoring
Here is how to poll the status of your GPU(s) in a variety of ways from your terminal:
Watch the processes using GPU(s) and the current state of your GPU(s):
watch -n 1 nvidia-smi
Watch the usage stats as their change:
nvidia-smi --query-gpu=timestamp,pstate,temperature.gpu,utilization.gpu,utilization.memory,memory.total,memory.free,memory.used --format=csv -l 1
This way is useful as you can see the trace of changes, rather than just the current state shown by
nvidia-smiexecuted without any arguments.
To see what other options you can query run:
nvidia-smi --help-query-gpu.
-l 1will update every 1 sec (`–loop. You can increase that number to do it less frequently.
-f filenamewill log into a file, but you won’t be able to see the output. So it’s better to use
nvidia-smi ... | tee filenameinstead, which will show the output and log the results as well.
if you’d like the program to stop logging after running for 3600 seconds, run it as:
timeout -t 3600 nvidia-smi ...
For more details, please, see Useful nvidia-smi Queries.
Most likely you will just want to track the memory usage, so this is probably sufficient:
nvidia-smi --query-gpu=timestamp,memory.used,memory.total --format=csv -l 1
Similar to the above, but show the stats as percentages:
nvidia-smi dmon -s u
which shows the essentials (usage and memory). If you would like all of the stats, run it without arguments:
nvidia-smi dmon
To find out the other options, use:
nvidia-smi dmon -h
Nvtop stands for NVidia TOP, a (h)top like task monitor for NVIDIA GPUs. It can handle multiple GPUs and print information about them in a htop familiar way.
It shows the processes, and also visually displays the memory and gpu stats.
This application requires building it from source (needing
gcc,
make, et al), but the instructions are easy to follow and it is quick to build.
nvidia-smilike monitor, but a compact one. It relies on pynvml to talk to the nvml layer.
Installation:
pip3 install gpustat.
And here is a usage example:
gpustat -cp -i --no-color
Accessing NVIDIA GPU Info Programmatically
While watching
nvidia-smi running in your terminal is handy, sometimes you want to do more than that. And that’s where API access comes in handy. The following tools provide that.
pynvml
nvidia-ml-py3 provides Python 3 bindings for nvml c-lib (NVIDIA Management Library), which allows you to query the library directly, without needing to go through
nvidia-smi. Therefore this module is much faster than the wrappers around
nvidia-smi.
The bindings are implemented with
Ctypes, so this module is
noarch - it’s just pure python.
Installation:
- Pypi:
pip3 install nvidia-ml-py3
- Conda:
conda install nvidia-ml-py3 -c fastai
This library is now a
fastai dependency, so you can use it directly.
Examples:
Print the memory stats for the first GPU card:
from pynvml import * nvmlInit() handle = nvmlDeviceGetHandleByIndex(0) info = nvmlDeviceGetMemoryInfo(handle) print("Total memory:", info.total) print("Free memory:", info.free) print("Used memory:", info.used)
List the available GPU devices:
from pynvml import * nvmlInit() try: deviceCount = nvmlDeviceGetCount() for i in range(deviceCount): handle = nvmlDeviceGetHandleByIndex(i) print("Device", i, ":", nvmlDeviceGetName(handle)) except NVMLError as error: print(error)
And here is a usage example via a sample module
nvidia_smi:
import nvidia_smi nvidia_smi.nvmlInit() handle = nvidia_smi.nvmlDeviceGetHandleByIndex(0) # card id 0 hardcoded here, there is also a call to get all available card ids, so we could iterate res = nvidia_smi.nvmlDeviceGetUtilizationRates(handle) print(f'gpu: {res.gpu}%, gpu-mem: {res.memory}%')
py3nvml
This is another fork of
nvidia-ml-py3, supplementing it with extra useful utils.
note: there is no
py3nvml conda package in its main channel, but it is available on pypi.
GPUtil
GPUtil is a wrapper around
nvidia-smi, and requires the latter to function before it can be used.
Installation:
pip3 install gputil.
And here is a usage example:
import GPUtil as GPU GPUs = GPU.getGPUs() gpu = GPUs[0] print("GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal))
For more details see:
For more details see:
GPU Memory Notes
Unusable GPU RAM per process
As soon as you start using CUDA, your GPU loses some 300-500MB RAM per process. The exact size seems to be depending on the card and CUDA version. For example, on GeForce GTX 1070 Ti (8GB), the following code, running on CUDA 10.0, consumes 0.5GB GPU RAM:
import torch torch.ones((1, 1)).cuda()
This GPU memory is not accessible to your program’s needs and it’s not re-usable between processes. If you run two processes, each executing code on
cuda, each will consume 0.5GB GPU RAM from the get going.
This fixed chunk of memory is used by CUDA context.
Cached Memory
pytorch normally caches GPU RAM it previously used to re-use it at a later time. So the output from
nvidia-smi could be incorrect in that you may have more GPU RAM available than it reports. You can reclaim this cache with:
import torch torch.cuda.empty_cache()
If you have more than one process using the same GPU, the cached memory from one process is not accessible to the other. The above code executed by the first process will solve this issue and make the freed GPU RAM available to the other process.
It also might be helpful to note that
torch.cuda.memory_cached() doesn’t show how much memory pytorch has free in the cache, but it just indicates how much memory it currently has allocated, with some of it being used and may be some being free. To measure how much free memory available to use is in the cache do:
torch.cuda.memory_cached()-torch.cuda.memory_allocated().
Reusing GPU RAM
How can we do a lot of experimentation in a given jupyter notebook w/o needing to restart the kernel all the time? You can delete the variables that hold the memory, can call
import gc; gc.collect() to reclaim memory by deleted objects with circular references, optionally (if you have just one process) calling
torch.cuda.empty_cache() and you can now re-use the GPU memory inside the same kernel.
To automate this process, and get various stats on memory consumption, you can use IPyExperiments. Other than helping you to reclaim general and GPU RAM, it is also helpful with efficiently tuning up your notebook parameters to avoid
CUDA: out of memory errors and detecting various other memory leaks.
And also make sure you read the tutorial on
learn.purge and its friends here, which provide an even better solution.
GPU RAM Fragmentation
If you encounter an error similar to the following:
RuntimeError: CUDA out of memory. Tried to allocate 350.00 MiB (GPU 0; 7.93 GiB total capacity; 5.73 GiB already allocated; 324.56 MiB free; 1.34 GiB cached)
You may ask yourself, if there is 0.32 GB free and 1.34 GB cached (i.e. 1.66 GB total of unused memory), how can it not allocate 350 MB? This happens because of memory fragmentation.
For the sake of this example let’s assume that you have a function that allocates as many GBs of GPU RAM as its argument specifies:
def allocate_gb(n_gbs): ...
And you have an 8GB GPU card and no process is using it, so when a process is starting it’s the first one to use it.
If you do the following sequence of GPU RAM allocations:
# total used | free | 8gb of RAM # 0GB | 8GB | [________] x1 = allocate_gb(2) # 2GB | 6GB | [XX______] x2 = allocate_gb(4) # 6GB | 2GB | [XXXXXX__] del x1 # 4GB | 4GB | [__XXXX__] x3 = allocate_gb(3) # failure to allocate 3GB w/ RuntimeError: CUDA out of memory
despite having a total of 4GB of free GPU RAM (cached and free), the last command will fail, because it can’t get 3GB of contiguous memory.
Except, this example isn’t quite valid, because under the hood CUDA relocates physical pages, and makes them appear as if they are of a contiguous type of memory to pytorch. So in the example above it’ll reuse most or all of those fragments as long as there is nothing else occupying those memory pages.
So for this example to be applicable to the CUDA memory fragmentation situation it needs to allocate fractions of a memory page, which currently for most CUDA cards is of 2MB. So if less than 2MB is allocated in the same scenario as this example, fragmentation will occur.
Given that GPU RAM is a scarce resource, it helps to always try free up anything that’s on CUDA as soon as you’re done using it, and only then move new objects to CUDA. Normally a simple
del obj does the trick. However, if your object has circular references in it, it will not be freed despite the
del() call, until
gc.collect() will not be called by python. And until the latter happens, it’ll still hold the allocated GPU RAM! And that also means that in some situations you may want to call
gc.collect() yourself.
If you want to educate yourself on how and when the python garbage collector gets automatically invoked see gc and this.
Peak Memory Usage
If you were to run a GPU memory profiler on a function like
Learner
fit() you would notice that on the very first epoch it will cause a very large GPU RAM usage spike and then stabilize at a much lower memory usage pattern. This happens because the pytorch memory allocator tries to build the computational graph and gradients for the loaded model in the most efficient way. Luckily, you don’t need to worry about this spike, since the allocator is smart enough to recognize when the memory is tight and it will be able to do the same with much less memory, just not as efficiently. Typically, continuing with the
fit() example, the allocator needs to have at least as much memory as the 2nd and subsequent epochs require for the normal run. You can read an excellent thread on this topic here.
pytorch Tensor Memory Tracking
Show all the currently allocated Tensors:
import torch import gc for obj in gc.get_objects(): try: if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)): print(type(obj), obj.size()) except: pass
Note, that gc will not contain some tensors that consume memory inside autograd.
Here is a good discussion on this topic with more related code snippets.
GPU Reset
If for some reason after exiting the python process the GPU doesn’t free the memory, you can try to reset it (change 0 to the desired GPU ID):
sudo nvidia-smi --gpu-reset -i 0
When using multiprocessing, sometimes some of the client processes get stuck and go zombie and won’t release the GPU memory. They also may become invisible to
nvidia-smi, so that it reports no memory used, but the card is unusable and fails with OOM even when trying to create a tiny tensor on that card. In such a case locate the relevant processes with
fuser -v /dev/nvidia*and kill them with
kill -9.
This blog post suggests the following trick to arrange for the processes to cleanly exit on demand:
if os.path.isfile('kill.me'): num_gpus = torch.cuda.device_count() for gpu_id in range(num_gpus): torch.cuda.set_device(gpu_id) torch.cuda.empty_cache() exit(0)
After you add this code to the training iteration, once you want to stop it, just cd into the directory of the training program and run
touch kill.me
Multi-GPU
Order of GPUs
When having multiple GPUs you may discover that
pytorch and
nvidia-smi don’t order them in the same way, so what
nvidia-smi reports as
gpu0, could be assigned to
gpu1 by
pytorch.
pytorch uses CUDA GPU ordering, which is done by computing power (higher computer power GPUs first).
If you want
pytorch to use the PCI bus device order, to match
nvidia-smi, set:
export CUDA_DEVICE_ORDER=PCI_BUS_ID
before starting your program (or put in your
~/.bashrc).
If you just want to run on a specific gpu ID, you can use the
CUDA_VISIBLE_DEVICES environment variable. It can be set to a single GPU ID or a list:
export CUDA_VISIBLE_DEVICES=1 export CUDA_VISIBLE_DEVICES=2,3
If you don’t set the environment variables in shell, you can set those in your code at the beginning of your program, with help of:
import os; os.environ['CUDA_VISIBLE_DEVICES']='2'.
A less flexible way is to hardcode the device ID in your code, e.g. to set it to
gpu1:
torch.cuda.set_device(1) | https://docs.fast.ai/dev/gpu.html | CC-MAIN-2020-05 | refinedweb | 2,150 | 54.73 |
Took 88 ms and the "Accepted Solutions Runtime Distribution" doesn't show any faster Python submissions. The "trick" is to not check all the time whether we have reached the end but to handle it via an exception. "Easier to ask for forgiveness than permission."
The algorithm is of course Tortoise and hare.
def hasCycle(self, head): try: slow = head fast = head.next while slow is not fast: slow = slow.next fast = fast.next.next return True except: return False
Starting fast a step ahead of slow is brilliant. It allows you to use "while slow is not fast:" loop
Because there's only two conditions that the correct code should return False:
- when the linked list is empty.
- when there's no cycle in the linked list. Because the cycle could only happen at the end of the list, this condition also means that the last node in the list has a Null "node.next" property and an assignment such as fast = fast.next.next will fail.
I don't quite get your explanation, especially this:
"the cycle could only happen at the end of the list"?
If there's a cycle, then there's no end.
Anyway, I'd say why I did it is speed. I could use LBYL instead, i.e., use explicit extra tests checking whether next nodes actually exist before trying to access them, but here I chose EAFP. Python will check for access errors anyway, so additionally checking it myself would be a waste of time.
And a meta-reason I did that: Probably the LBYL-way had already been posted, and I don't post when I have nothing new to add to the discussion.
While I absolutely loved your idea, catching all exceptions is considered a bad practice. I think you should at least change it to:
except AttributeError as e:
With this behaviour, you can at least be sure that you are returning False only if the expected exception was raised.
@nirnaor In real life/work that's good, but here and in interviews, personally I think it's unnecessary clutter.
@StefanPochmann said in Except-ionally fast Python:
except:
return False
Can you please elaborate on 'except: return False'
I understood that if there is a cycle, then 'return True' gets triggered, but how does the 'except: return False' get triggered?
What if the list looks like 1,1,1,1,1,1,1,1,2,1,1,2,3. In this case, your code will return True at the second value, but we can see this list is not a cycle.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/16098/except-ionally-fast-python | CC-MAIN-2017-34 | refinedweb | 448 | 72.87 |
You can subscribe to this list here.
Showing
5
results of 5
per freem wrote:
>?
plt.plot([0,1], [2,3], '--', dashes=(10,20))
The dashes kwarg sets a Line2D parameter. See
Eric
>
> thanks.
>
> ------------------------------------------------------------------------------
> The Planet: dedicated and managed hosting, cloud storage, colocation
> Stay online with enterprise data centers and the best network in the business
> Choose flexible plans and management services without long-term contracts
> Personal 24x7 support from experience hosting pros just a phone call away.
>
> _______________________________________________
> Matplotlib-users mailing list
> Matplotlib-users@...
>?
thanks.
Moving to the devel list, since this concerns an internal API of
matplotlib. Thanks to Sourav for reporting this and to Eric for sending
the note to me.
Eric Firing <efiring@...> writes:
> Sourav K. Mandal wrote:
>> I have a simple problem: when outputting to PDF or SVG, alpha blending
>> does not work for the lines drawn by "contour". However, alpha blending
>> does work for the regions given by "contourf".
>
> You are right, this is a real bug, verified in svn.
The contour function creates a LineCollection, which gets drawn via
draw_path_collection, which the pdf backend inherits from backend_bases.
The default draw_path_collection (or _iter_collection really)
communicates the alpha of the *face color* only by setting the alpha
attribute of the GraphicsContext:
if rgbFace is not None and len(rgbFace)==4:
gc0.set_alpha(rgbFace[-1])
rgbFace = rgbFace[:3]
The alpha of the line only gets communicated via the fourth component of
the rgb attribute of the GraphicsContext, and currently the pdf backend
doesn't do anything with it.
I think this could be resolved in a number of ways, none of which is
obviously the perfect solution:
1. Add a check in _iter_collection for gc0._rgb having an alpha
component, similar to the current check for rgbFace, and set the
alpha attribute from that one too. (What if both rgbFace and gc0._rgb
have an alpha component?)
2. Make each backend's GraphicsContext set the alpha attribute from the
color. (If the alpha attribute is already set, how should they be
combined? Multiply, take the minimum, or what?)
3. Either get rid of the alpha attribute on the GraphicsContext and use
only rgba tuples within backends, or turn it into two attributes
(e.g. alphaFace and alphaStroke). (What to do with the frontend's
single alpha attribute?)
By the way, I have never really understood why rgbFace is given
separately from the GraphicsContext. Is this just an evolutionary
remnant or is there a deeper meaning for it?
--
Jouni K. Seppänen
Am Freitag, 29. Januar 2010 21:00:04 schrieb Sebastian Busch:
> Florian Lindner wrote:
> > Hello,
> >
> > I try to use LaTeX in my plot....
> >
> > florian@...:~> cat .matplotlib/matplotlibrc
> > text.usetex : true
> >
> > My plotting code looks like:
> >
> > Ma = arange(1.0, 5.0, 0.01)
> > Ts = [T(i) for i in Ma] # BTW: Is there a way to spare this line?
> not sure what T is. you could try T(Ma); you can do that of course also
> directly in the plot command
T is a python function:
def T(Ma):
fp = fluidproperties.IdealGas()
fp.Ma = Ma
return NormalShock(fp).fp_out().T / fp.
plot(Ma, T(Ma), label=r'$\frac{T2}{T1}$') does not work. The plot window appears, but no plot.
> > plot(Ma, Ts, label=r'/frac{T2}{T1}')
> should be backslash and math mode:
> plot(Ma, Ts, label=r'$\frac{T2}{T1}$')
> legend()
> show()
>
> > and that's all, no plot window appears, the script is finished.
>
> you did not show() !
Actually I did it. I stripped the code before pasting it here, my fault. But not it works, thanks!
Florian
Hi
I am using "verts" in the matplotlib scatter function and managed to
create many new symbols for scatter plots. One I cannot make is a
spiral-like symbol (logarithmic spiral) because it does connect the
first and last point of the verts series of x,y points I am defining. Is
there a way to avoid that? (so that the spiral-curve stays "open")
thanks!
Eric | http://sourceforge.net/p/matplotlib/mailman/matplotlib-users/?viewmonth=201001&viewday=30 | CC-MAIN-2014-49 | refinedweb | 661 | 66.84 |
Headercontribution can be added to many things ... 2010/7/31 Mark Doyle <markjohndo...@googlemail.com>: > Ah ok, I'll test that. I never thought of just adding it to the Page. > > > What, if any, is the difference between this and adding the behaviour to the > WebPage which is a kind of Component? > > > On Fri, Jul 30, 2010 at 7:03 PM, Martin Makundi < > martin.maku...@koodaripalvelut.com> wrote: > >> Hi! >> >> You could try this: >> >> public class HomePage extends WebPage implements IHeaderContributor { >> �...@override >> public void renderHead(IHeaderResponse response) { >> response.renderOnLoadJavascript(javascript) >> } >> >> >> ** >> Martin >> >> 2010/7/30 Mark Doyle <markjohndo...@googlemail.com>: >> > Firstly, I'm having some trouble finding a decent behaviour tutorial. If >> > anybody knows of one post a link up. >> > >> > Now, the problem I am having is creating a behaviour that adds some JS to >> > the head and sets an onLoad method. The JS project instructs users to >> add: >> > >> > <body onload="jsfunctionhere ( options, callback );"> >> > >> > but I'm not sure how Wicket supports this. >> > >> > Any ideas? >> > >> > Cheers >> > >> >> --------------------------------------------------------------------- >> | https://www.mail-archive.com/users@wicket.apache.org/msg54330.html | CC-MAIN-2021-39 | refinedweb | 164 | 60.92 |
Posted 03 Oct 2009
Link to this post
public IQueryable RetrieveCultures()
{
var query = (from q in scope.Extent<Resource>()
select new
{
q.Culture
}).Distinct();
return query;
}
Posted 04 Oct 2009
Link to this post
how can i get distinct ?
what is the right linq expression and how can i return my result set from function (what is the right cast to handle error that i tell above)?
is there any body to give me a sample function that return a result set that are dustinct ?
Posted 05 Oct 2009
Link to this post
i say my quesion in other side,
my Resource Class structure is like below :
[Telerik.OpenAccess.Persistent(IdentityField = "FId")]
public class Resource
{
private int FId;
private string FName;
private string FDefaultValue;
private string FValue;
private string FCulture;
private ModuleType FModuleType;
private ObjectType FObjectType;
private string FNote;
}
i need a function that return all culture as distinct,
my mean is ( select distinct Culture from Resource ) in TSql or ( (from q in db.Resource select new {q.Culture}).Distinct(); ) in Linq
and now my problem is :
a function with linq in open access that return distinct result set
public IQueryable RetrieveCultures()
{
var query = (from q in scope.Extent<Resource>()
select q.Culture).Distinct();
return query;
}
/HG
Posted 07 Oct 2009
Link to this post | http://www.telerik.com/forums/distinct | CC-MAIN-2017-30 | refinedweb | 215 | 61.26 |
#include <Surf.h>
#include <Surf.h>
List of all members.
Definition at line 28 of file Surf.h.
Definition at line 33 of file Surf.C.
free up triangle mesh memory.
Definition at line 156 of file Surf.C.
References ResizeArray< int >::clear, ResizeArray< float >::clear, f, ind, n, numtriangles, and v.
Referenced by DrawMolItem::change_rep.
return 1 on success, 0 on fail takes the probe radius and the array of x,y,z,r values.
Definition at line 35 of file Surf.C.
References ResizeArray< int >::append, ResizeArray< float >::append3x3, f, ind, n, NULL, num, numtriangles, tri_degenerate, v, vmd_delete_file, VMD_FILENAME_MAX, vmd_getuid, vmd_random, vmd_system, vmd_tempfile, and z.
facets.
Definition at line 33 of file Surf.h.
Referenced by clear, and compute.
facet-to-atom index map.
Definition at line 34 of file Surf.h.
normals.
Definition at line 32 of file Surf.h.
number of triangles in the facet list.
Definition at line 30 of file Surf.h.
vertices.
Definition at line 31 of file Surf.h. | http://www.ks.uiuc.edu/Research/vmd/doxygen/classSurf.html | CC-MAIN-2020-05 | refinedweb | 167 | 63.46 |
I spent an inordinate amount of time trying to figure out how put my ATTiny85 to sleep and then wake it up when the state of a pin changes. So I’ll document my test code in case anyone else goes searching for a simple example.
The reference I ended up using is:
Unfortunately, even after reading through the forum thread the final working code was evidently never posted. However, there was enough here for me to figure out the problem and get it running.
The following code is very simple. It flashes the LED quickly to let you know the program is started. It then sets up for sleep mode and goes to sleep. When the button is pushed, it awakes, flashes the LED once and goes back to sleep.
#include <avr/sleep.h> #include <avr/interrupt.h> const int switchPin = 3; const int statusLED = 2; void setup() { pinMode(switchPin, INPUT); digitalWrite(switchPin, HIGH); pinMode(statusLED, OUTPUT); // Flash quick sequence so we know setup has started for (int k = 0; k < 10; k = k + 1) { if (k % 2 == 0) { digitalWrite(statusLED, HIGH); } else { digitalWrite(statusLED, LOW); } delay(250); } // for } // setup void sleep() { GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts PCMS } void loop() { sleep(); digitalWrite(statusLED, HIGH); delay(1000); digitalWrite(statusLED, LOW); }
One additional comment: in my actual program, I will need to awake if either of two buttons is pressed. To handle this, I simply add these additional statements below their near twins:
PCMSK |= _BV(PCINT4); // Use PB4 as interrupt pin PCMSK &= ~_BV(PCINT4); // Turn off PB4 as interrupt pin
Thanks for posting this, it really helped me. I think I’ve been following the same forum posts as you but I don’t have as good of a grasp of AND/OR’ing registers as you do, so seeing the code like this is perfect.
The regular Arduino PinChangeInt library is 3kb but your solution is only a few lines, much better for the ATtiny!
On uCs with limited memory, it is not uncommon to need to forego the complete library implementation of something and raid the library for the minimalistic functionality necessary to accomplish the needed task.
Other examples include LCD (quite piggy), random (brings in 700-900 bytes of overhead, which makes it almost unusable on an ATTiny2x with just 2K of flash, but for “random-ish”, there are other things you can do that aren’t as costly), long and floating point operations (which can sometimes be circumvented by changing how you perform math operations and what sort of precision you really need), and delay().
Delay brings in about 200 bytes of timer code that you can save by doing the following:
myDelay( int seconds )
{
while ( seconds– )
{
delayMicroseconds( 1000 );
}
}
This won’t be quite as precise, but for most purposes (“wait ‘x’ seconds before re-arming”), is more than sufficient, and the memory saved on the uC can be used for something more critical.
Long math is slow enough that even on an 8MHz (no external crystal necessary) ATTiny8x, driving a pin high, delaying a fixed time (with delaymicroseconds()), driving the pin low, delaying, and doing long math to decrement a counter in a for loop results in a noticeable “click” in the output. See the code in Determining the delay and number of iterations Using an int before entering the loop avoids that,
As I develop a programs, I test the builds and note the build size (for a given target, so size is apples-to-apples: if you change uC targets, binary sizes can change significantly), then note these either within comments within the module, or in the git commit comments (changes are pushed to a git repo regularly). Doing so, you easily visualize how much some changes add to your code size, and that helps a lot when you’re working with limited program space.
Excellent insight, Sean! I love it.
Even though I consider myself an experienced programmer (15 years professionally), all my skill is in very-high-level languages on machines megabytes/gigabytes/terabytes of memory and storage, so shifting designs to focus on individual bytes is a huge — but rewarding — change in focus. Saving 200 bytes by rolling your own delay() function is something that would have never occurred to me.
I started programming in the late 70’s in what would have been considered high-level then (Fortran and COBOL) but we still had to watch every byte we used. Learning to program microcontrollers has been like going back to my programming roots. Every byte, and every instruction counts and there aren’t any fancy debugging tools. 🙂
I started programming in assembler on Z80 (CP/M) followed by 6502 CPUs (Apple and Atari), and there you had at best 64KB of memory total for the entire system, including the OS (and the ROM). Things improved with the x86, though having gotten used to writing compact code, all that extra memory often went unused (often, one used extra memory to buffer things for increased performance, but because every PC had a different memory config, apps needed to run on the lower configs if you wanted them to be usable by a large audience).
Despite developing using higher level languages (C, C++, Perl, Ruby (ugh, did I just vomit a little?), etc) for most things these days, memory consumption still remains important. Poorly written OOP code can chew through memory. Some languages are versatile – I’ve found PHP to be nice for web dev, but dang, it’s memory representation of some structures is gross. The venerable 8051 uC is still in fairly common use, and while it only has 16 bit addressing (64KB addressable space), it has different banks of memory (data, and program being the chief ones in use), so program is in 64K, data can be in a separate 64K. Using external address line switching and linker trickery, you can bank switch ROM to increase program size on the 8051. It’d been years since I did any 8051 dev, but as an ASIC at my employer utilizes the 8051 core, I recently got back to it for some projects, though otherwise most of my work is on an ARM based embedded system.
I’ve used the ATTiny24V for some projects – it has just 2K of flash. I have some ATTiny13A uCs (which sport just 1K of flash), but have yet to use them in anything (and, arguably, they’re not so much cheaper than the ’85 that it really makes sense to use them, outside of some lower voltage capabilities).
I’m eager to check out the ATTiny43U. 4K flash, and it has an integrated boost converter capability: it can drive itself off of a sub 1.5V battery *AND* reportedly drive some external loads once bootstrapped. Obviously though, it has a different pinout than its x4 and x5 ATTiny siblings, so won’t be a drop-in design. For some of my own projects, I have to use a boost module I designed, which charges an UltraCap, but I don’t have a control in place to shut off the boost when the Cap is above a target voltage (that’s what I planned to use the ATTiny13A’s for) – integrating this directly into the uC is really attractive.
Personally, my next step with the AVR is to switch or tweak development toolchains – the Arduino IDE is entirely too simplistic and limited — as it is, I set the option to use an external editor, and just use the IDE to launch the compiler and drive the binary through my programmer devices (AVRisp or Arduino-as-ISP with a ICSP ZIF shield I made). The gnu toolchain (c/c++ compiler, assembler, library tools, and linker – though the versions distributed in the Arduino IDE are fairly dated), is still underneath the IDE, so it’s a matter of generating standard makefiles for projects and building libs with assembler, then the IDE can be ditched. AVR Studio 6.x is an alternative, but sadly, it’s purely a windows offering.
Pingback: Low Power ATTiny85 Experiment | Big Dan the Blogging Man
Hello, thank you for your code. Can i use the same code for an Attiny84 ? Thanks.
Looking at the datasheet, (), I think it would work.
I do not think you would hurt the 84 if it doesn’t work.
I’m using the code on an ’84 currently and I can confirm it works.
84 and 85 should differ only in the number of I/O (and their various capabilities), so the sleep code should be fine. Other members of the AVR family (such as the Tiny13A or 24) may not support all of the same Watchdog intervals, but those aren’t employed here in Dan’s example (a watchdog timout would be how you could sleep and wake periodically to check something, not just in response to an external event).
It’s always cool to see others jump in and help. Thanks guys!
This was great! Definately saved me a couple of hours, thanks!
2 small points to mention:
1. I use Proteus for simulation and it doesn’t like delaymicroseconds() for whatever reason. Yes, It is buggy but it was worth the money…I’ve used it to develop dozens of projects.
2. I adding a boolean (bRelease) initialized HIGH so you only trigger on button closure, not both close and open:
sleep(); // sleep until change of state
if (bReleased) { // is button in released state (open)
bReleased = LOW; // button is now in pressed state (closed)
digitalWrite(LED, HIGH); // pulse LED
delay(100);
digitalWrite(LED, LOW);
}
else { // button was in presse state so has been released
bReleased = HIGH; // so set flag and go take a nap
}
Pingback: AtTiny85 put in sleep mode and awaken through a 4N35 optocoupler | curiosityBikes
Pingback: Arduino ile Attiny85 Programlama Guncel | Genel | Burak Öztürk
Pingback: [ASK] arduino - ATtiny85 (Sparfun Clone/Trinket), detect/read operation voltage | Some Piece of Information
Hey thanks for the simple and concise code, just what a beginner like me was looking for for my project!!
Zach
Thank you for the great tutorial. I got this to work with the ATTiny84 by making small edits. Here’s my code:
void sleep() {
GIMSK |= _BV(PCIE0); // Enable Pin Change Interrupts
PCMSK0 |= _BV(PCINT3); // Use PB3 as interrupt pin
PCMSK0 |= _BV(PCINT4); // Use PB
PCMSK0 &= ~_BV(PCINT4); // Use PB4 as interrupt pin
sleep_disable(); // Clear SE bit
ADCSRA |= _BV(ADEN); // ADC on
sei(); // Enable interrupts
} // sleep
Switched the PCIE to PCIE0 and PCMSK to PCMSK0.
Pingback: ARDUINO: ATTINY85 AS AN ARDUINO AND SLEEP MODE – Simple-EE
I did combined the codes it was provided by Imginit . It Works for my ATTiny44-20PU (Mouser P/N 556-ATTINY44-20PU) using Arduino UNO as ISP. Wake up 17.3mA(330ohm) or 5.5mA(10K); Sleep current 630uA.
I am analog person in Silicon-Valley USA for many years and never touch any code until three months ago. It is just for fun beside my work.
As we all know, this code sets sleep mode by the the internal delay(xxxxxx). Could any one help modify it makes both sleep and wake by external interrupt (momentary switch)?
Thank you for all.
Thank you for the posting! It Works for my ATTiny44-20PU (Mouser P/N 556-ATTINY44-20PU) using Arduino UNO as ISP just a small edit.
Wake up 17.3mA(330ohm) or 5.8mA(10K); Sleep current 20uA.
I am analog person in Silicon-Valley USA for many years and never touch any code until three months ago. It is just for fun beside my work.
As we all knew, this code sets sleep mode by the the internal processor. Could any one help modify it makes both sleep and wake by external interrupt (momentary switch)?
Thank you for all.
void sleep() {
GIMSK |= _BV(PCIE0); // Enable Pin Change Interrupts
PCMSK
}
Pingback: Atduino: go to sleep tiny ATtiny | Tahium
Pingback: Arduino: go to sleep tiny ATtiny – All Great Offers Today
I’ve been trying out your code and unfortunately, when I wash flashing the uC for the second time it bricked, it repeated twice under the same conditions and I’ve managed to recover only one of them. I think it could be related to “digitalWrite(switchPin, HIGH);” in the setup, it doesn’t see the external oscilator and the output is always high.
Did anyone experience this ? Does anyone know the proper configuration to unbrick the attiny ? | https://bigdanzblog.wordpress.com/2014/08/10/attiny85-wake-from-sleep-on-pin-state-change-code-example/ | CC-MAIN-2017-39 | refinedweb | 2,071 | 56.89 |
After much abstract thought (very well received! thank you! :-)) it’s time to get back to some good old C#, or you’ll think I’ve gone soft 🙂
Say that you have a Web application protected via claims-based identity. Say that your application occasionally reaches out to a backend service, and that the service output (or even the ability of calling the service to begin with) depends on the current user of the Web application.
Sounds familiar? The need to flow identity through the layers of a solution is an extremely common one. The solution we’ve been offering through WIF, the ActAs flow, is extremely powerful but, as it turns out, also not the easiest thing to implement.
In this post I am going to describe a “low-tech” solution to the problem which can only be applied when very specific requirements are met, and is not nearly as powerful as full-fledged ActAs, but has the advantage of being substantially simpler to implement.
Flowing Identity Through Layers
I have written extensively about ActAs in the past (yes, I was already using a tablet in 2008; in fact, I was using one at least since 2004) and in the book; I also often spoke about it during breakouts (one of the most detailed explanations can be found here, from minute 54 on). I won’t repeat what I wrote then, but rather than sending you off to read tons of background material I’ll set a bit of context here.
The idea behind the ActAs approach to the problem described earlier in the post is pretty simple: when it needs to call the backend service, the Web application requests a token to the appropriate STS by presenting both its own application credentials and the token that the user presented in order to authenticate with the Web app itself (commonly referred to as the bootstrap token). The STS can then verify that the request is actually coming from the (well-known) Web application, and verify that the user is actually engaging with the Web app at the moment; hence, the STS can apply whatever logic it deems appropriate to manufacture (or not) a token that will fully reflect the situation (claims about the user, etc) and that is scoped precisely to the backend service.
That is a fantastic way of handling delegation though solution layers, far more robust and expressive than the classic trusted subsystem approach. In the most generic case, in which frontend and backend are operated by different & distinct owners, that is the right way of crossing the boundary between the two.
However, this is also quite complicated to set up. In WIF we made significant effort to support the scenario through the object model (CreateChannelActingAs, CreateChannelWithIssuedTokens, etc) however there are many moving parts you need to tame. Not every STS supports ActAs (ACS2.0, for one, doesn’t), creating your own ActAs STS entails grokking some pretty subtle concepts (like specifying which token handler will be used to process the user tokens) and various others. Troubleshooting ActAs scenarios is not the most fun you can have on Friday nights.
However in my experience the thing that developers have a hard time understanding is why can’t one just reuse with the backend service the same token that was presented by the user to authenticate with the Web application. It would be so simple! In fact, in the general case one cannot assume that that would work. In this post I give a long list of things that would prevent that approach from working in the most general case; here I’ll summarize with a simple analogy.
Imagine that you walk in a laundry shop and you leave there a bunch of shirts and a leather jacket; you write a bank check payable to the shop and you walk.
Say that the laundry takes care of the shirts in-house, but outsources the processing of leather goods to a specialized shop. Now, the laundry cannot pay the other shop by presenting the check they got from you, because the check is payable by the laundry shop only! Map the laundry shop to the frontend, the leather shop to the backend, the check to the token and the “payable to” field to the audience restriction element and the reason you can’t usually reuse tokens will be clear.
That said: not every laundry shop outsources leather goods processing! Say that the shirt and leather processing are simply assigned by different departments/cost centers of the same shop. In that case they would be both able to cash the check, which means that the check itself might move from the admin of the department who picked up the order to the admin of the leather processing center, and everything would still be fine. There you go: we found the special case in which reusing tokens might be a possibility.
Let’s map our analogy back to the digital world. If both frontend and backend are simply different aspects of the same solution, and belong to the same owner, then one could consider the differences between the two as mere implementation details. In identity terms: if the frontent and the backend belong to the same realm, then a token meant for one is also scoped for the other and vice versa. You’ll have to be careful that tokens delivered to the frontend cannot be stolen across sessions, and if you don’t want anybody to call the backend directly you better ensure that it is not publicly addressable, but in absence of further constraints in this case it should be OK for the frontent to invoke the backed by flowing the bootstrap token.
Even if people intuitively gravitated toward the token reuse approach, one of the technical reasons for which it was not implemented very often is what I was used to call protocol refraction. Just like light has different propagation characteristics in different mediums, in the WS-* world a token meant for a passive flow would be a bearer token and one for an active leg would be a holder-of-key, hence the token meant for the frontend would not have been fit for the backend. Well, that was 2008. In 2013, chances are that your backend will be implemented as REST services: and REST services are perfectly happy with bearer tokens.
The final barrier to a successful implementation was the sheer size of the tokens at play. Being in SAML format, a typical Web sign-in token would usually be too big to travel in HTTP header. Well, enter the JSON Web Token (JWT). With ACS you can do a classic WS-Federation web sign-on flow which carries a JWT instead of the canonical SAML. As long as the above restrictions hold and you are in the right scenario, that constitutes a great bootstrap token that is perfect to be used for invoking a REST service.
Got it? I like to call this approach the “prrom man”’s ActAs. Tha is not meant to be derogatory, it just expresses the fact that this approach tries to solve the same problem that we would have normally addressed with ActAs. Although it does not have the same generality and expressive power of ActAs (not even close), it does require with significantly less resources and, provided that your scenario allows for it (do you clean your leather in-house or do you outsource it?) it gets the job done,
An Example
Blah, blah, blah. I know, right? That’s called logorrhea, and I have it since I was little. Enough with the blabber, let’s hit Visual Studio and see how it’s done.
- Create a blank solution (I called mine “PoorMansActAs”).
- Add a new project of type “ASP.NET MVC 4 Web Application” as a frontent – I called mine “Frontend”. I picked the “Intranet Application” sub-type as it is more compact than others but still has enough surface to be a good starting point.
- Add a new project of type “ASP.NET MVC 4 Web Application”, “Web API” as a backend – you guessed right, I called mine “Backend”.
That sets the stage. Below I am going to go in the details of how to set up frontent and backend to implement the poor man’s actas flow. Also: I have noticed that lately in my posts I have left a lot as “exercise for the reader”, referring to published samples. Here I’ll try to be a bit more descriptive, and paste & comment code snippets even if those are already available elsewhere.
The Frontend
Let’s start by making our frontend outsource authentication to ACS and process JWT tokens. Thanks to the identity and access tool for VS 2012, this is going to be super-easy. Right click on the project, pick Identity ad Access… and choose ACS. Note: later we’ll use the email claim, hence you might want to select only identity providers that make it available via ACS (like Facebook).
Very good. By default, ACS wills end us a SAML token. We want to change that. Let’s hit the Windows Azure portal, select the ACS namespace of choice, pick the RP that the VS tool created for us and edit it as follows:
The main things to observe in the screen above are:
- The realm value. I have chosen a generic URI, which represents the logical identifier of my solution as a whole (as opposed to reusing the address of the frontend or the backend, the default choice). One day I’ll likely write a long rant about realm != return URL, but for today that’s enough 🙂
- The token format. I changed it ot JWT.
From now on ACS will do the right thing and send us JWTs. The next step is to teach to our application how to digest them! Right click on the solution and go to the Manage NuGet Packages,.. entry.
Search for identitymodel.tokens and you’ll land on the NuGet for the JWT handler. Don’t do like Kyle, do read the license terms and if you’re OK with them hit I Accept to install the package.
Great! Now you have the assembly with the right types available. head to the web.config and add few lines to take advantage of the JWT token handler.
1: <system.identityModel>
2: <identityConfiguration saveBootstrapContext="true" >
3: <audienceUris>
4: <add value="urn:poormansactassample" />
5: </audienceUris>
6: <securityTokenHandlers>
7: <add type="Microsoft.IdentityModel.Tokens.JWT.JWTSecurityTokenHandler, Microsoft.IdentityModel.Tokens.JWT" />
8: <securityTokenHandlerConfiguration>
9: <certificateValidation certificateValidationMode="PeerTrust"/>
10: </securityTokenHandlerConfiguration>
11: </securityTokenHandlers>
12: <issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
13: <trustedIssuers>
14: <add thumbprint="C1677FBE7BDD6B131745E900E3B6764B4895A226"
15:
16: </trustedIssuers>
17: </issuerNameRegistry>
18: </identityConfiguration>
19: </system.identityModel>
20: <system.identityModel.services>
21: <federationConfiguration>
22: <cookieHandler requireSsl="false" />
23: <wsFederation passiveRedirectEnabled="true"
24: issuer=""
25:
26: </federationConfiguration>
27: </system.identityModel.services>
28: configuration>
The tool filled in almost everything you need. the only lines you have to add/modify are
Line 2: you want to opt in for saving the bootstrapContect. This will come in handy later, when we’ll call the backend service
Line 4: the tool autogenerated a realm for you, hence an expected audience value. You want to change that value to the realm we set in ACS.
Lines 6 to 11: this is boilerplate code to add the JWT handler in the handlers list.
Line 25: as for line 4, we need to update the realm to what we set in ACS
That’s it for the code meant to enabling JWT-based web sign-on. You still need to install in the trusted people the certificate needed to verify ACS’ token signatures. See here (and specifically “Using the JWT Handler With WIF Applications”) for hints on how to do that.
If you want you can give the project a spin now, just to verify that the sig-in works. We’ll get back to this project later to add the logic to perform the call to the backend.
The Backend
We need to add the JWT handler NuGet to the backend project as well. Done that, let’s add some logic to the Web API project to expect and validate incoming tokens via the OAuth bearer calling style. As shown in all the JWT/AAL samples, we do that by implementing a single DelegatingHandler that deserializes and validates the token.
Let’s head to the global.asax and start with the following:
1:internal class TokenValidationHandler : DelegatingHandler
2:{
3:
4:
5: private static bool TryRetrieveToken(HttpRequestMessage request, out string token)
6: {
7: token = null;
8: IEnumerable<string> authzHeaders;
9: if (!request.Headers.TryGetValues("Authorization", out authzHeaders) || authzHeaders.Count() > 1)
10: {
11: return false;
12: }
13: var bearerToken = authzHeaders.ElementAt(0);
14: token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
15: return true;
16: }
this very basic code retrieves the token, if any, from the http Authorization header.
The real meat is in the following method:
1: protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
2: {
3: HttpStatusCode statusCode;
4: string token;
5:
6: if (!TryRetrieveToken(request, out token))
7: {
8: statusCode = HttpStatusCode.Unauthorized;
9: return Task<HttpResponseMessage>.Factory.StartNew(() =>
new HttpResponseMessage(statusCode));
10: }
11:
12: try
13: {
14: X509Store store = new X509Store(StoreName.TrustedPeople,
StoreLocation.LocalMachine);
15: store.Open(OpenFlags.ReadOnly);
16: X509Certificate2 cert = store.Certificates.Find(
X509FindType.FindByThumbprint,
"C1677FBE7BDD6B131745E900E3B6764B4895A226",
false)[0];
17: store.Close();
18:
19:
20: JWTSecurityTokenHandler tokenHandler =
new JWTSecurityTokenHandler();
21: TokenValidationParameters validationParameters =
new TokenValidationParameters()
22: {
23: AllowedAudience = "urn:poormansactassample",
24: ValidIssuer = "",
25: SigningToken = new X509SecurityToken(cert)
26: };
27:
28: Thread.CurrentPrincipal =
tokenHandler.ValidateToken(token, validationParameters);
29:
30: return base.SendAsync(request, cancellationToken);
31: }
32: catch (SecurityTokenValidationException e)
33: {
34: statusCode = HttpStatusCode.Unauthorized;
35: }
36: catch (Exception)
37: {
38: statusCode = HttpStatusCode.InternalServerError;
39: }
40: return Task<HttpResponseMessage>.Factory.StartNew(() =>
new HttpResponseMessage(statusCode));
41: }
42: }
What’s happening here? Quick walkthrough:
Line 6: retrieve the token via the method defined earlier
Lines 14 to 17: retrieve the X509 certificate used for verifying ACS’ token signatures
Lines 20 to 26: initialize a new JWT handler with validating parameters including the expected audience (the realm), the expected issuer and the just-retrieved certificate
Line 28: validate the token; if successful, create a ClaimsPrincipal and assing it to the current thread for the main API logic to have access to it
OK, it’s still security, but as protocol/security code goes I’d daresay this is pretty straightforward,
Now: we need to get this puppy in the We API pipeline. We do so by adding it to the HttpConfiguration:
1:static void Configure(HttpConfiguration config)
2:{
3: config.MessageHandlers.Add(new TokenValidationHandler());
4:}
We just need to call Configure in Application_Start, and we’re all set.
Alrighty. We could do all sorts of interesting things with claims in our Web API, but here I’d just like to do something that proves we did have access to them. I’ll ignore every common decency and return the value of the email claim without doing any error checking.
1: // GET api/values/5
2: public string Get(int id)
3: {
4: return ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
5: //return "value";
6: }
Perfect! Our API is all ready to be securely invoked. Let;s get back to the frontend and make it happen.
Flowing the Caller’s Identity
Back to the frontend. Let’s pick one of the default actions in the home controller and add the necessary logic to retrieve the bootstrap token and use it to invoke the backend service. There you go:
1:public ActionResult About()
2:{
3:
4: BootstrapContext bc =
ClaimsPrincipal.Current.Identities.First().BootstrapContext
as BootstrapContext;
5: JWTSecurityToken jwt = bc.SecurityToken as JWTSecurityToken;
6:
7: string rawToken = jwt.RawData;
8:
9: HttpWebRequest request =
WebRequest.Create("") as HttpWebRequest;
10: request.Method = "GET";
11: request.Headers["Authorization"] = "Bearer " + rawToken;
12: request.ContentType = "application/json";
13:
14: string responseTxt = String.Empty;
15: using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
16: {
17: var reader = new StreamReader(response.GetResponseStream());
18: responseTxt = reader.ReadToEnd();
19: response.Close();
20: }
21:
22: ViewBag.Message =
"I just called the backend, and I got back " + responseTxt;
23:
24: return View();
25:}
What’s happening here:
Line 4: we retrieve the bootstrap context. For details, see this post.
Line 5: we cast the bootstrapcontext content to a JWT
Line 7: we retrieve the JWT in encoded form, ready to be put on the wire
Lines 9, 10 and 12: we prepare an HttpWebRequest to invoke the backed service
Line 11: we add the bootstrap token in the appropriate header
Lines 14-20: we invoke the service and retrieve the results
Line 22: we surface the result in the UI
That’s all you need. Hit F5; authenticate with the frontend; hit about and observe that the frontend successfully called the backend using the bootstrap token.
Wrapup
In the general case, if you need to make delegated calls between layers of your solution you should consider using ActAs.
That said: if you own both frontend and backend, frontend and backend can truly be considered components of the same app, your backed is REST, your web sign-in token format allows for it, you are OK with your backed to be callable without going though the frontend (or there are “physical” barriers in place to prevent that) then the poor man’s ActAs can provide a simpler – albeit more limited – alternative. Have fun!
P.S.: kudos to my wife for the laundry example, my original example was pretty lame! 🙂 | https://blogs.msdn.microsoft.com/vbertocci/2013/01/09/using-the-jwt-handler-for-implementing-poor-mans-delegationactas/ | CC-MAIN-2017-22 | refinedweb | 2,930 | 52.49 |
Had a question about an enumerated set of constant values.
"Where do I put these constants?" they asked. It was clear what they wanted. This is another variation on their personal quest which can be called "I want Python to have CONST or Final." It's kind of tedious when a person asks -- repeatedly -- for a feature that's not present in the form they want it.
"Use Enum," I said.
"Nah," they replied. "It's Yet Another Abstraction."
Wait, what?
This is what I learned from rest of their nonsensical response: There's an absolute upper bound on abstractions, and Enum is one abstraction too many. Go ahead count them. This is too many.
Or.
They simply rejected the entire idea of learning something new. They wanted CONST or Final or some such. And until I provide it, Python is garbage because it doesn't have constants. (They're the kind of person that needs to see CONST minutes_per_hour = 60 in every program. When I ask why they don't also insist on seeing CONST one = 1 they seem shocked I would be so flippant.)
YAA. Seriously. Too many layers.
As if all of computing wasn't a stack of abstractions on top of stateful electronic circuits.
Tuesday, February 12, 2019
Tuesday, February 5, 2019
Python Enhancement Proposal -- Floating an Idea
Consider the following code
Let's look at something a little more complex.:
def max(m: int, n: int) -> int: if m >= n: return m elif n >= m: return n else: raise Exception(f"Design Error: {vars()}")There's a question about else: clause and the exception raised there.
- It's impossible. In this specific case, a little algebra can provide that it's impossible. In more complex cases, the algebra can be challenging. In some cases, external dependencies may make the algebra impossible.
- It's needless in general. An else: would have been better than the elif n >= m:. The problem with else: is that a poor design, or poor coordination with the external dependencies, can lead to undetectable errors.
def ackermann(m: int, n: int) -> int: if m < 0 or n < 0: raise ValueError(f"{m} and {n} must be non-negative") if m == 0: return n + 1 elif m > 0 and n == 0: return ackermann(m - 1, 1) elif m > 0 and n > 0: return ackermann(m - 1, ackermann(m, n - 1)) else: raise Exception(f"Design Error: {vars()}"):
- Scale. For simple cases, with not too many branches and not too many variables, the algebra is manageable. As the branches and variables grow, the analysis becomes more difficult and more subject to error.
- Dependencies. For some cases, this kind of branching can be refactored into a polymorphic class hierarchy, and the decision-making superficially simplified. In other cases, there are multiple, disjoint states and multiple conditions related to those states, and the reasoning becomes more prone to errors.
The noble path is to use abstraction techniques to eliminate them. This is aspirational in some cases. While it's always the right thing to do, we need to check our work. And testing isn't always sufficient.
The noble path is subject to simple errors. While we can be very, very, very, very careful in our design, there will still be obscure cases which are very, very, very, very, very subtle. We can omit a condition from our analysis, and our unit tests, and all of our colleagues and everyone reviewing the pull request can be equally snowed by the complexity.
We have two choices.
- Presume we are omniscient and act accordingly: use else: clauses as if we are incapable of error. Treat all complex if-elif chains as if they were trivial.
- Act more humbly and try to detect our failure to be omniscient.
If we acknowledge the possibility of a design error, what exception class should we use?
- RuntimeError. In a sense, it's an error which didn't occur until we ran the application and some edge case cropped up. However. The error was *always* present. It was a design error, a failure to be truly omniscient and properly prove all of our if-elif branches were complete.
- DesignError. We didn't think this would happen. But it did. And we need debugging information to see what exact confluence of variables caused the problem.
I submit that DesignError be added to the pantheon of Python exceptions. I'm wondering if I should make an attempt to write and submit a PEP on this. Thoughts? | https://slott-softwarearchitect.blogspot.com/2019/02/ | CC-MAIN-2021-39 | refinedweb | 751 | 65.73 |
This document is for Django's SVN release, which can be significantly different from previous releases. Get old docs here: Django 1.0
Internationalization¶
Django has full support for internationalization of text in code and templates. Here’s how it works.
Overview¶
The goal of internationalization is to allow a single Web application to offer its content and functionality in multiple languages.
You, the Django developer, can accomplish this goal by adding a minimal amount you do need internationalization: three steps¶
-¶
Translation strings specify “This text should be translated.” These strings can appear in your Python code and templates. It’s your responsibility to mark translatable strings; the system can only translate strings it knows about..
Lazy translation¶')
Pluralization¶
Use the function django.utils.translation.ungettext() to specify pluralized messages.
ungettext takes three arguments: the singular translation string, the plural translation string and the number of objects.
This function is useful when your need you Django application to be localizable to languages where the number and complexity of plural forms is greater than the two forms used in English ('object' for the singular and 'objects' for all the cases where count is different from zero, irrespective of its value.)
For example:
from django.utils.translation import a a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid' error when running django-admin.py compilemessages or a KeyError Python exception at runtime.
In template code¶
Translations original text will be returned unchanged. This is useful when "stubbing out" content that will require translation in the future:
<title>{% trans "myvar" noop %}</title>
Internally, inline translations use an ugettext call. %}
When you use the pluralization feature and bind additional values to local variables apart from the counter value that selects the translated literal to be used, have in mind that the blocktrans construct is internally converted to an ungettext call. This means the same notes regarding ungettext variables apply.
Each RequestContext has access to three translation-specific variables:
- LANGUAGES is a list of tuples in which the first element is the language code and the second is the language name (translated into the currently active locale).
- LANGUAGE_CODE is the current user's preferred language, as a string. Example: en-us. (See 3. How Django discovers language preference, below.)
- LANGUAGE_BIDI is the current locale's direction. If True, it's a right-to-left language, e.g.: Hebrew, Arabic. If False it's a left-to-right language, e.g.: English, French, German etc.).
Working with lazy translation objects¶).
The allow_lazy() decorator¶.
2. How to create language files¶. See the relevant LocaleMiddleware note for more details..
A note to Django veterans
The old tool bin/make-messages.py has been moved to the command django-admin.py makemessages to provide consistency throughout Django.:
- The root directory of your Django project.
- The root directory of your Django app.
- The root django directory (not a Subversion checkout, but the one that is linked-to via $PYTHONPATH or is located somewhere on that path). This is only relevant when you are creating a translation for Django itself, see Submitting and maintaining translations. you need to use the special 'dj:
-.
A note to Django veterans
The old tool bin/compile-messages.py has been moved to the command django-admin.py compilemessages to provide consistency throughout Django.
Working on Windows?
If you're using Windows and need to install the GNU gettext utilities so django-admin compilemessages works see gettext on Windows for more information.
3..Changed in Django 1.0: Please, see the release notes
In Django version 0.96 and before, the cookie's name is hard-coded to django_language. In Django 1,0, The cookie name.
Using translations in your own projects¶ Django-provided Using settings without setting DJANGO_SETTINGS_MODULE,).
The set_language redirect view¶¶
Adding translations to JavaScript poses some problems:
- JavaScript code doesn't have access to a gettext implementation.
- JavaScript code doesn't have access to .po or .mo files;.
Using the JavaScript translation catalog¶).
Creating JavaScript translation catalogs¶.
Specialties of Django translation¶:
Download the following zip files from the GNOME servers or from one of its mirrors
- gettext-runtime-X.zip
- gettext-tools-X.zip
X is the version number, we recomend using. | http://docs.djangoproject.com/en/dev/topics/i18n/%3Ffrom=olddocs | crawl-002 | refinedweb | 705 | 50.73 |
Description
Flowex is a mix of FBP and so-called Railway Oriented Programming (ROP) approach. Flowex DSL allows you to easily create "pipelines" of Elixir GenStages.
Flowex alternatives and similar packages
Based on the "Actors" category.
Alternatively, view Flowex alternatives based on common mentions on social networks and blogs.
poolboy9.9 0.0 Flowex VS poolboyA hunky Erlang worker pool factory
exactor9.1 0.0 Flowex VS exactorHelpers for simpler implementation of GenServer based processes
pooler8.7 0.0 Flowex VS poolerAn OTP Process Pool Application
sbroker7.2 0.0 Flowex VS sbrokerSojourn-time based active queue management library
exos5.9 0.1 Flowex VS exosExos is a simple Port Wrapper : a GenServer which forwards cast and call to a linked Port.
workex5.8 0.0 Flowex VS workexLoad control in BEAM processes.
dflow3.4 0.0 Flowex VS dflowDalmatiner flow processing library.
Event Socket Outbound2.5 1.4 Flowex VS Event Socket OutboundAn Elixir FreeSWITCH's Event Socket Outbound
pool_ring0.5 0.0 Flowex VS pool_ringcreate a pool based on a hash ring
mon_handler0.4 0.0 Flowex VS mon_handlerElixir GenServer used to monitor a GenEvent event handler
Director0.2 0.0 Flowex VS Directormoved to - Director is a production-ready supervisor and manager for Erlang/Elixir processes that focuses on speed, performance and flexibility.
SockErl0.1 0.0 Flowex VS SockErlmoved to - Sockerl is an advanced Erlang/Elixir socket framework for TCP protocols and provides fast, useful and easy-to-use API for implementing servers, clients and client connection pools.
Load-Balancer0.1 0.0 Flowex VS Load-Balancermoved to - Load-Balancer for spreading Erlang/Elixir messages.
Scout APM: A developer's best friend. Try free for 14-days
Do you think we are missing an alternative of Flowex or a related project?
Popular Comparisons
README
Flowex
Railway Flow-Based Programming.
Flowex is a set of abstractions built on top Elixir GenStage which allows writing program with Flow-Based Programming paradigm.
I would say it is a mix of FBP and so-called Railway Oriented Programming (ROP) approach.
Flowex DSL allows you to easily create "pipelines" of Elixir GenStages.
Dedicated to my lovely girlfriend Chryścina.
Resources
- Railway Flow-Based Programming with Flowex - post
- Flowex: Flow-Based Programming with Elixir GenStage - presentation
- Flow-based programming with Elixir - presentation
- Flow-Based REST API with Flowex and Plug - post
- Multi language FBP with Flowex - presentation
- Multi-language Flowex components - post
- Flow-Based REST API with Flowex and Plug - post
Contents
- Installation
- A simple example to get the idea
- More complex example for understanding interface
- Flowex magic!
- Run the pipeline
- How it works
- Error handling
- Pipeline and pipe options
- Synchronous and asynchronous calls
- Bottlenecks
- Module pipes
- Data available in pipes
- Starting strategies
- Debugging with Flowex.Sync.Pipeline
- Contributing
Installation
Just add
flowex as dependency to the
mix.exs file.
A simple example to get the idea
Let's consider a simple program which receives a number as an input, then adds one, then multiplies the result by two and finally subtracts 3.
defmodule Functions do def add_one(number), do: number + 1 def mult_by_two(number), do: number * 2 def minus_three(number), do: number - 3 end defmodule MainModule do def run(number) do number |> Functions.add_one |> Functions.mult_by_two |> Functions.minus_three end end
So the program is a pipeline of functions with the same interface. The functions are very simple in the example.
In the real world they can be something like
validate_http_request,
get_user_from_db,
update_db_from_request and
render_response.
Furthermore, each of the function can potentially fail. But for getting the idea let's stick the simplest example.
FBP defines applications as networks of "black box" processes, which exchange data across predefined connections by message passing.
To satisfy the FBP approach we need to place each of the function into a separate process. So the number will be passed from 'add_one' process to 'mult_by_two' and then 'minus_three' process which returns the final result.
That, in short, is the idea of Flowex!
More complex example for understanding interface
Let's define a more strict interface for our function. So each of the function will receive a predefined struct as a first argument and will return a map:
def add_one(%{number: number}, opts) do %{number: number + 1, a: opts.a} end
The function receives a structure with
number field and the options map with field
a and returns map with new number.
The second argument is a set of options and will be described later.
Let's rewrite the whole
Functions module in the following way:
defmodule Functions do defstruct number: nil, a: nil, b: nil, c: nil def add_one(%{number: number}, %{a: a}) do %{number: number + 1, a: a} end def mult_by_two(%{number: number}, %{b: b}) do %{number: number * 2, b: b} end def minus_three(%{number: number}, %{c: c}) do %{number: number - 3, c: c} end end
The module defines three functions with the similar interface.
We also defined as struct
%Functions{} which defines a data-structure being passed to the functions.
The main module may look like:
defmodule MainModule do def run(number) do opts = %{a: 1, b: 2, c: 3} %Functions{number: number} |> Functions.add_one(opts) |> Functions.mult_by_two(opts) |> Functions.minus_three(opts) end end
Flowex magic!
Let's add a few lines at the beginning.
defmodule FunPipeline do use Flowex.Pipeline pipe :add_one pipe :mult_by_two pipe :minus_three defstruct number: nil, a: nil, b: nil, c: nil def add_one(%{number: number}, %{a: a}) do %{number: number + 1, a: a} end # mult_by_two and minus_three definitions skipped end
We also renamed the module to
FunPipeline because we are going to create "Flowex pipeline".
Flowex.Pipeline extend our module, so we have:
pipemacro to define which function evaluation should be placed into separate GenStage;
error_pipemacro to define function which will be called if error occurs;
start,
supervised_startand
stopfunctions to create and destroy pipelines;
callfunction to run pipeline computations synchronously.
castfunction to run pipeline computations asynchronously.
- overridable
initfunction which, by default, accepts
optsand return them
Let's start a pipeline:
opts = %{a: 1, b: 2, c: 3} pipeline = FunPipeline.start(opts) #returns %Flowex.Pipeline{in_name: :"Flowex.Producer_#Reference<0.0.7.504>", module: FunPipeline, out_name: :"Flowex.Consumer_#Reference<0.0.7.521>", sup_pid: #PID<0.136.0>}
What happened:
- Three GenStages have been started - one for each of the function in pipeline. Each of GenStages is
:producer_consumer;
- One additional GenStage for error processing has been started (it is also
:producer_consumer);
- 'producer' and 'consumer' GenStages for input and output have been added;
- All the components have been placed under Supervisor.
The next picture shows what the 'pipeline' is. [alt text](figures/fun_pipeline.png "FunPipeline")
The
start function returns a
%Flowex.Pipeline{} struct with the following fields:
- module - the name of the module
- in_name - unique name of 'producer';
- out_name - unique name of 'consumer';
- sup_name - unique name of the pipeline supervisor
Note, we have passed options to
start function. This options will be passed to each function of the pipeline as a second argument.
There is
supervised_start function which allows to place pipeline's under external supervisor.
See details in Starting strategies section.
Run the pipeline
One can run calculations in pipeline synchronously and asynchronously:
callfunction to run pipeline computations synchronously.
castfunction to run pipeline computations asynchronously.
FunPipeline.call/2 function receive a
%Flowex.Pipeline{} struct as a first argument and must receive a
%FunPipeline{} struct as a second one.
The
call function returns a %FunPipeline{} struct.
FunPipeline.call(pipeline, %FunPipeline{number: 2}) # returns %FunPipeline{a: 1, b: 2, c: 3, number: 3}
As expected, pipeline returned
%FunPipeline{} struct with
number: 3.
a,
b and
c were set from options.
If you don't care about the result, you should use
cast/2 function to run and forget.
FunPipeline.cast(pipeline, %FunPipeline{number: 2}) # returns :ok
Run via client
Another way is using
Flowex.Client module which implements GenServer behavior.
The
Flowex.Client.start\1 function receives pipeline struct as an argument.
Then you can use
call/2 function or
cast/2. See example below:
{:ok, client_pid} = Flowex.Client.start(pipeline) Flowex.Client.call(client_pid, %FunPipeline{number: 2}) # returns %FunPipeline{a: 1, b: 2, c: 3, number: 3} #or Flowex.Client.cast(client_pid, %FunPipeline{number: 2}) # returns :ok
How it works
The following figure demonstrates the way data follows:
[alt text](figures/pipeline_with_client.png "How it works")
Note:
error_pipe is not on the picture in order to save place.
The things happen when you call
Flowex.Client.call (synchronous):
selfprocess makes synchronous call to the client gen_server with
%FunPipeline{number: 2}struct;
- the client makes synchronous call 'FunPipeline.call(pipeline, %FunPipeline{number: 2})';
- the struct is wrapped into
%Flowex.IP{}struct and begins its asynchronous journey from one GenStage to another;
- when the consumer receives the Information Packet (IP), it sends it back to the client which sends it back to the caller process.
The things happen when you
cast pipeline (asynchronous):
selfprocess makes
castcall to the client and immediately receives
:ok
- the client makes
castto pipeline;
- the struct is wrapped into
%Flowex.IP{}struct and begins its asynchronous journey from one GenStage to another;
- consumer does not send data back, because this is
cast
Error handling
What happens when error occurs in some pipe?
The pipeline behavior is like Either monad. If everything ok, each 'pipe' function will be called one by one and result data will skip the 'error_pipe'.
But if error happens, for example, in the first pipe, the
:mult_by_two and
:minus_three functions will not be called.
IP will bypass to the 'error_pipe'. If you don't specify 'error_pipe' flowex will add the default one:
def handle_error(error, _struct, _opts) do raise error end
which just raises an exception.
To specify the 'error' function use
error_pipe macro:
defmodule FunPipeline do use Flowex.Pipeline # ... error_pipe :if_error def if_error(error, struct, opts) do # error is %Flowex.PipeError{} structure # with :message, :pipe, and :struct fields %{number: :oops} end #... end
You can specify only one error_pipe!
Note: The 'error_pipe' function accepts three arguments.
The first argument is a
%Flowex.PipeError{} structure which has the following fields:
:message- error message;
:pipe- is
{module, function, opts}tuple containing info about the pipe where error occured;
:struct- the input of the pipe.
Pipeline and pipe options
In addition to specifying options when starting pipeline one can pass component's options to the
pipe macro.
And remember about pipeline's
init function which can add or override options.
The flow is the following:
The options passed to
start function are available in pipeline
init function. The function can merge additional options. Then
opts passed to
pipe macro are merged.
So there are three levels that options pass before appearing in component:
- pipeline
startfunction;
- pipeline
initfunction;
- pipe
opts.
Let's consider an example:
defmodule InitOptsFunPipeline do use Flowex.Pipeline defstruct [:from_start, :from_init, :from_opts] pipe :component, opts: %{from_opts: 3} def init(opts) do # opts passed to start function is available here Map.put(opts, :from_init, 2) end def component(_data, opts) do # here all the options is available opts end end
Suppose we've started the pipeline with options
%{from_start: 1}.
init function adds
:from_init option. Then
:from_opts are merged.
The test below illustrates what is going on:
describe "function pipeline" do let :pipeline, do: InitOptsFunPipeline.start(%{from_start: 1}) let :result, do: InitOptsFunPipeline.call(pipeline(), %InitOptsFunPipeline{}) it "returns values from different init functions" do expect(result()) |> to(eq %InitOptsFunPipeline{from_start: 1, from_init: 2, from_opts: 3}) end end
Synchronous and asynchronous calls
Note, that
call function on pipeline module or
Flowex.Client is synchronous. While communication inside the pipeline is asynchronous:
[alt text](figures/pipeline_sync_async.png "Sync and async")
One might think that there is no way to effectively use the pipeline via
call/2 method.
That's not true!
In order to send a large number of IP's and process them in parallel one can use several clients connected to the pipeline: [alt text](figures/many_clients.png "Group of clients")
Bottlenecks
Each component of pipeline takes a some to finish IP processing. One component does simple work, another can process data for a long time. So if several clients continuously push data they will stack before the slowest component. And data processing speed will be limited by that component.
Flowex has a solution! One can define a number of execution processes for each component.
defmodule FunPipeline do use Flowex.Pipeline pipe :add_one, count: 1 pipe :mult_by_two, count: 3 pipe :minus_three, count: 2 error_pipe :if_error, count: 2 # ... end
And the pipeline will look like on the figure below: [alt text](figures/complex_pipeline.png "Group of clients")
Module pipes
One can create reusable 'pipe' - module which implements init and call functions.
Each module must define a struct it works with. Only fields defined it the stuct will be passed to
call function.
defmodule ModulePipeline do use Flowex.Pipeline defstruct [:number, :a, :b, :c] pipe AddOne, count: 1 pipe MultByTwo, count: 3 pipe MinusThree, count: 2 error_pipe IfError, count: 2 end #pipes defmodule AddOne do defstruct [:number] def init(opts) do %{opts | a: :add_one} end def call(%{number: number}, %{a: a}) do %{number: number + 1, a: a} end end defmodule MultByTwo do defstruct [:number] def init(opts) do %{opts | b: :mult_by_two} end def call(%{number: number}, %{b: b}) do %{number: number * 2, b: b} end end defmodule MinusThree do defstruct [:number] def init(opts) do %{opts | c: :minus_three} end def call(%{number: number}, %{c: c}) do %{number: number - 3, c: c} end end defmodule IfError do defstruct [:number] def init(opts), do: opts def call(error, %{number: _number}, _opts) do %{number: error} end end
Of course, one can combine module and functional 'pipes'!
Data available in pipes
If your pipeline consists of function pipes only, each function will receive pipeline struct as an input.
The situation is a little more complex with module pipes.
Each module defines its own struct and data will be cast to that struct.
Map returned from the
call function will be merged to the previos data.
Let's consider an example:
defmodule DataAvailable do use Flowex.Pipeline defstruct [:top, :c1, :foo] pipe Component1 pipe :component2 pipe Component3 def component2(%__MODULE__{top: top}, _opts) do %{top: top + 2, c3: 2} end end defmodule Component1 do defstruct [:top, :c1] def init(opts), do: opts def call(%__MODULE__{c1: c1, top: top}, _opts) do %{top: top + c1, bar: :baz} end end defmodule Component3 do defstruct [:c3, :top] def init(opts), do: opts def call(%__MODULE__{c3: c3, top: top}, _opts) do %{top: top + c3, c3: top - c3, foo: :set_foo} end end
And suppose we passed
%DataAvailable{top: 100, c1: 1} to
DataAvailable.call function.
Data in IP before calling first pipe is
%{c1: 1, foo: nil, top: 100}.
Before entering the first pipe the data will be cast to
%Component1{c1: 1, top: 100}.
The returned value of first pipe is merged to IP data, so the data is
%{bar: :baz, c1: 1, foo: nil, top: 101}.
Function
component2 receives
%DataAvailable{c1: 1, foo: nil, top: 101} structure and returned value
%{c3: 2, top: 103} is merged with previous data,
so IP data is
%{bar: :baz, c1: 1, c3: 2, foo: nil, top: 103}
Last component receives
%Component3{c3: 2, top: 103}, returns
%{c3: 101, foo: :set_foo, top: 105} and data is
%{bar: :baz, c1: 1, c3: 101, foo: :set_foo, top: 105}.
Before returning data from pipeline they are casted to
DataAvailable structure, so final result is
%DataAvailable{c1: 1, foo: :set_foo, top: 105}}
Starting strategies
Using
start/1 function one can start pipelines in any process. Pipelines will be alive while the process is alive.
The
supervised_start function accepts supervisor
pid as the first argument and
opts as the second argument.
And starts pipeline's supervisor under predefined supervisor process.
In general there are three ways to start pipelines in your project:
- Start pipelines in arbitrary supervised process: ```elixir defmodule PipelineGenServer do use GenServer
def init(_opts) do pipeline_one = PipelineOne.start pipeline_two = PipelineTwo.start
{:ok, %{pipeline_one: pipeline_one, pipeline_two: pipeline_two}}
end end
You can also store pipeline structure in Agent or Application environment. 2. Start one pipeline per application. In that case pipeline supervisor will be the main supervisor in the application: ```elixir defmodule OnePipelinePerApp do use Application def start(_type, _opts) do pipeline = PipelineOne.start Application.put_env(:start_flowex, :pipeline, pipeline) {:ok, pipeline.sup_pid} end end
- Start several pipelines inside one application using
supervised_startfunction. In that case pipeline supervisors will be placed under application supervisor: ```elixir defmodule TwoPipelinesPerApp do use Application
def start(_type, _opts) do {:ok, supervisor_pid} = Supervisor.start_link([], strategy: :one_for_one, name: :multi_flowex_sup)
pipeline_one = PipelineOne.supervised_start(supervisor_pid) pipeline_two = PipelineTwo.supervised_start(supervisor_pid) Application.put_env(:start_flowex, :pipeline_one, pipeline_one) Application.put_env(:start_flowex, :pipeline_two, pipeline_two) {:ok,supervisor_pid}
end end
You can find the examples in ['Start-Flowex']() project ## Debugging with Flowex.Sync.Pipeline If you are faced with some error that is hard to debug or an error that causes GenServers to crash, you may find the `Flowex.Sync.Pipeline` module useful. Adding one `Sync` word will completely change the behavior. ```elixir defmodule FunPipeline do use Flowex.Sync.Pipeline # The same code as before # ... end
Interface remains the same but all the code will be evaluated in one simple GenServer. So all you pipes will be evaluated synchronously in separate process. Use this option only for debug purposes.
Contributing
Contributions are welcome and appreciated!
Request a new feature by creating an issue.
Create a pull request with new features or fixes.
Flowex is tested using ESpec. So run:
mix espec | https://elixir.libhunt.com/flowex-alternatives | CC-MAIN-2021-43 | refinedweb | 2,886 | 55.64 |
While working on a feature for snapd, we had a need to perform a “secure bind mount”. In this context, “secure” meant:
- The source and/or target of the mount is owned by a less privileged user.
- User processes will continue to run while we’re performing the mount (so solutions that involve suspending all user processes are out).
- While we can’t prevent the user from moving the mount point, they should not be able to trick us into mounting to locations they don’t control (e.g. by replacing the path with a symbolic link).
The main problem is that the mount system call uses string path names to identify the mount source and target. While we can perform checks on the paths before the mounts, we have no way to guarantee that the paths don’t point to another location when we move on to the mount() system call: a classic time of check to time of use race condition.
One suggestion was to modify the kernel to add a MS_NOFOLLOW flag to prevent symbolic link attacks. This turns out to be harder than it would appear, since the kernel is documented as ignoring any flags other than MS_BIND and MS_REC when performing a bind mount. So even if a patched kernel also recognised the MS_NOFOLLOW, there would be no way to distinguish its behaviour from an unpatched kernel. Fixing this properly would probably require a new system call, which is a rabbit hole I don’t want to dive down.
So what can we do using the tools the kernel gives us? The common way to reuse a reference to a file between system calls is the file descriptor. We can securely open a file descriptor for a path using the following algorithm:
- Break the path into segments, and check that none are empty, ".", or "..".
- Open the root directory with open("/", O_PATH|O_DIRECTORY).
- Open the first segment with openat(parent_fd, "segment", O_PATH|O_NOFOLLOW|O_DIRECTORY).
- Repeat for each of the remaining file descriptors, closing parent descriptors as needed.
Now we just need to find a way to use these file descriptors with the mount system call. I came up with two strategies to achieve this.
Use the current working directory
The first idea I tried was to make use of the fact that the mount system call accepts relative paths. We can use the fchdir system call to change to a directory identified by a file descriptor, and then refer to it as ".". Putting those together, we can perform a secure bind mount as a multi step process:
- fchdir to the mount source directory.
- Perform a bind mount from "." to a private stash directory.
- fchdir to the mount target directory.
- Perform a bind mount from the private stash directory to ".".
- Unmount the private stash directory.
While this works, it has a few downsides. It requires a third intermediate location to stash the mount. It could interfere with anything else that relies on the working directory. It also only works for directory bind mounts, since you can’t fchdir to a regular file.
Faced with these downsides, I started thinking about whether there was any simpler options available.
Use magic /proc symbolic links
For every open file descriptor in a process, there is a corresponding file in /proc/self/fd/. These files appear to be symbolic links that point at the file associated with the descriptor. So what if we pass these /proc/self/fd/NNN paths to the mount system call?
The obvious question is that if these paths are symbolic links, is this any different than passing the real paths directly? It turns out that there is a difference, because the kernel does not resolve these symbolic links in the standard fashion. Rather than recursively resolving link targets, the kernel short circuits the process and uses the path structure associated with the file descriptor. So it will follow file moves and can even refer to paths in other mount namespaces. Furthermore the kernel keeps track of deleted paths, so we will get a clean error if the user deletes a directory after we’ve opened it.
So in pseudo-code, the secure mount operation becomes:
source_fd = secure_open("/path/to/source", O_PATH); target_fd = secure_open("/path/to/target", O_PATH); mount("/proc/self/fd/${source_fd}", "/proc/self/fd/${target_fd}", NULL, MS_BIND, NULL);
This resolves all the problems I had with the first solution: it doesn’t alter the working directory, it can do file bind mounts, and doesn’t require a protected third location.
The only downside I’ve encountered is that if I wanted to flip the bind mount to read-only, I couldn’t use "/proc/self/fd/${target_fd}" to refer to the mount point. My best guess is that it continues to refer to the directory shadowed by the mount point, rather than the mount point itself. So it is necessary to re-open the mount point, which is another opportunity for shenanigans. One possibility would be to read /proc/self/fdinfo/NNN to determine the mount ID associated with the file descriptor and then double check it against /proc/self/mountinfo. | https://blogs.gnome.org/jamesh/ | CC-MAIN-2018-22 | refinedweb | 856 | 61.67 |
5 Oct 08:01 2012
Re: predictCoding() return empty Granges
Hervé Pagès <hpages@...>
2012-10-05 06:01:26 GMT
2012-10-05 06:01:26 GMT
Hi Rebecca,(). * > rowData values names(1): paramRangeID > colnames(2): sample1_aln.sorted.bam sample2_aln.sorted.bam > colData names(1): Samples > >> txdb > TranscriptDb object: > | Db type: TranscriptDb > | Supporting package: GenomicFeatures > | Data source: TAIR 10 > | Genus and Species: Arabodpsis > | miRBase build ID: NA > | transcript_nrow: 35386 > | exon_nrow: 207465 > | cds_nrow: 197160 > | Db created by: GenomicFeatures package from Bioconductor > | Creation time: 2012-09-28 16:43:28 -0700 (Fri, 28 Sep 2012) > | GenomicFeatures version at creation time: 1.9.37 > | RSQLite version at creation time: 0.11.1 > | DBSCHEMAVERSION: 1.0 > >> Athaliana > Arabidopsis genome > | > | organism: Arabidopsis thaliana (Arabidopsis) > | provider: TAIR > | provider version: 04232008 > | release date: NA > | release name: dumped from ADB: Mar/14/08 > | > | sequences (see '?seqnames'): > | chr1 chr2 chr3 chr4 chr5 chrC chrM > | > | (use the '$' or '[[' operator to access a given sequence) We provide 2 BSgenome packages for Arabidopsis: a very old one BSgenome.Athaliana.TAIR.04232008 with chromosome names and lengths: > seqlengths(Athaliana) chr1 chr2 chr3 chr4 chr5 chrC chrM 30432563 19705359 23470805 18585042 26992728 154478 366924 and a somewhat less old one: BSgenome.Athaliana.TAIR.TAIR9 with chromosome names and lengths: > seqlengths(Athaliana) Chr1 Chr2 Chr3 Chr4 Chr5 ChrM ChrC 30427671 19698289 23459830 18585056 26975502 366924 154478 They correspond to 2 different assemblies of course. 2 things: (1) The code I showed you in the previous thread for renaming the sequence names of your TranscriptDb object was assuming that you were using the less old BSgenome package: seqlevels(txdb) <- sub("^c", "C", seqlevels(txdb)) However it seems that you are using the very old one (where chr names are "chr*"), and that your txdb chr names are "Chr*", so you would actually need to do something like: seqlevels(txdb) <- sub("^C", "c", seqlevels(txdb)) (2) However, and this is much more important than (1): it seems that your VCF and TranscriptDb objects are based on the TAIR10 assembly. So it makes no sense to use anything else but a BSgenome package that contains the exact same assembly. Otherwise it's very likely that most of the predictions returned by predictCoding() will be wrong! Unfortunately at the moment we don't provide a BSgenome package for TAIR10 (nobody requested one so far). I'll try to make one in the next couple of weeks. I'll also remove BSgenome.Athaliana.TAIR.04232008 from the devel branch (BioC 2.12). Cheers, H. > >> sessionInfo() > R version 2.15.1 (2012-06-22) > Platform: x86_64-unknown-linux-gnu (64-bit) > > locale: > [1] C > > attached base packages: > [1] stats graphics grDevices utils datasets methods base > > other attached packages: > [1] BSgenome.Athaliana.TAIR.04232008_1.3.18 > BSgenome_1.26.0 > VariantAnnotation_1.4.0 > [4] Rsamtools_1.10.1 > Biostrings_2.26.0 > GenomicFeatures_1.10.0 > [7] AnnotationDbi_1.20.0 > Biobase_2.18.0 > GenomicRanges_1.10.0 > [10] IRanges_1.16.2 > BiocGenerics_0.4.0 > vimcom_0.9-2 > [13] setwidth_1.0-0 > colorout_0.9-9 > > loaded via a namespace (and not attached): > [1] DBI_0.2-5 RCurl_1.95-0.1.2 RSQLite_0.11.2 > XML_3.95-0.1 biomaRt_2.14.0 bitops_1.0-4.1 > [7] parallel_2.15.1 rtracklayer_1.18.0 stats4_2.15.1 > tools_2.15.1 zlibbioc_1.4.0 > > any ideas? thank you. > > Rebecca > > > On Thu, Oct 4, 2012 at 1:18 PM, Hervé Pagès <hpages@...> wrote: > >> Hi Rebecca, >> >> >> On 10/04/2012 12:10 PM, sun wrote: >> >>> Hi All, >>> >>> I am going to use "coding <- predictCoding(vcf, txdb, >>> seqSource=Athalian >>> >> > > [[alternative HTML version deleted]] > > > > _______________________________________________ >: | http://permalink.gmane.org/gmane.science.biology.informatics.conductor/43933 | CC-MAIN-2015-11 | refinedweb | 590 | 62.88 |
Hello Friends, In this tutorial, I am going to show you some Interview Questions and Answers on NET.
Interview Questions and Answers for .Net Beginners.
1- What’s the advantage of using System.Text.StringBuilder over System.String?
Ans- StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
2- Is it possible to store multiple data types in System.Array?
Ans- No.
3 -What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
Ans- System.Array.CopyTo() performs a deep copy of the array, the System.Array.Clone() is shallow.
4- How can you sort the elements of the array in descending order?
Ans- By calling Sort() and then Reverse() methods.
5- What’s the .NET datatype that allows the retrieval of data by a unique key?
Ans- HashTable.
6- What’s class SortedList underneath?
Ans- A sorted HashTable.
7- Will finally block get executed if the exception had not occurred?
Ans- Yes.
8- Can multiple catch blocks be executed?
Ans- No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
9- Why is it a bad practice.
10- What’s a delegate?
Ans- A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
11- What’s a multicast delegate?
Ans- It’s a delegate that points to and eventually fires off several methods.
12- How’s the DLL Hell problem solved in .NET?
Ans- Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32) but also the version of the assembly.
14- What are the ways to deploy an assembly?
Ans- An MSI installer, a CAB archive, and XCOPY command.
15- What’s a satellite assembly?
Ans- When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
16- What namespaces are necessary to create a localized application?
Ans- System.Globalization, System.Resources.
17- What’s the difference between // comments, /* */ comments and /// comments?
Ans- Single-line, multi-line and XML documentation comments.
18- What’s the difference between <c> and <code> XML documentation tag?
Ans- Single line code example and multiple-line code example.
19- Is XML case-sensitive?
Ans- Yes, so <Student> and <student> are different elements.
20- What debugging tools come with the .NET SDK?
Ans – CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
21- What does the This window show in the debugger?
Ans- It points to the object that’s pointed to by this reference. Object’s instance data is shown.
22- What does assert() do?
Ans- In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
23- What’s the difference between the Debug class and Trace class?
Ans- Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
24- for fine-tuning the tracing activities.
25-Where is the output of TextWriterTraceListener redirected?
Ans- To the Console or a text file depending on the parameter passed to the constructor.
26- How do you debug an ASP.NET Web application?
Ans- Attach the aspnet_wp.exe process to the DbgClr debugger.
27- What are three test cases you should go through in unit testing?
Ans- Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
28- Can you change the value of a variable while debugging a C# application?
Ans- Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
29- Explain the three services model (three-tier application).
Ans- Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
30- backwards compatibility to ODBC engines.
31- What’s the role of the DataReader class in ADO.NET connections?
Ans- It returns a read-only dataset from the data source when the command is executed.
32- What is the wildcard character in SQL?
Ans- Let’s say you want to query the database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
33- Explain ACID rule of thumb for transactions.
Ans-).
34- What connections does Microsoft SQL Server support?
Ans- Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
35- Which one is trusted and which one is untrusted?
Ans- Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted since SQL Server is the only verifier participating in the transaction.
36- Why would you use untrusted verification?
Ans- Web Services might use it, as well as non-Windows applications.
37- What does the parameter Initial Catalog define inside Connection String?
Ans- The database name to connect to.
38- What’s the data provider name to connect to Access database? Microsoft.Access.
Ans- Microsoft.Access.
39- What does Dispose method do with the connection object? Deletes it from the memory.
Ans- What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.
Conclusion:
Hope you liked this post about Interview Questions and Answers on.NET. I will appreciate your feedback, Comments and suggestions.
View More:
Interview Questions And Answers on Oops-Part 1
Thank You. | https://debugonweb.com/2017/07/interview-questions/ | CC-MAIN-2021-04 | refinedweb | 1,000 | 60.82 |
This is a quick way of locating which scenes, from an archive of data, contain a point you are interested in.
First make a list of all available scenes
ls data/S1/2017/??/??/*/*vv*img > all_scenes.txt
Then use gdalbuildvrt to make a VRT file containing all scenes as a separate band (assumes scenes only have a single band).
gdalbuildvrt -input_file_list all_scenes.txt \ -separate -o s1_all_scenes.vrt
Use gdallocation info with ‘-lifonly’ flag to the scene the point we are interested in (1.5 N, 103 E) is within and redirect to a text file.
gdallocationinfo -lifonly -wgs84 s1_all_scenes.vrt \ 103 1.5 > selected_scenes.txt
This will show if within the bounding box of the scene. To find scenes which have data can use gdallocationinfo again but with the ‘-valonly’ flag and save the values to a text file.
gdallocationinfo -valonly -wgs84 s1_all_scenes.vrt \ 103 1.5 > selected_scenes_values.txt
Can then subset the original list of files with the values file using Python:
import numpy # Read in data to numpy arrays scenes = numpy.genfromtxt("selected_scenes.txt", dtype=str) values = numpy.genfromtxt("selected_scenes_values.txt") # Select only scenes where the value is not 0 scenes_data = scenes[values != 0] # Save to text file numpy.savetxt("selected_scenes_data.txt", scenes_data, fmt="%s")
If you have a very large archive of data and need to find which scenes intersect a point often, having a spatial database with the scene outlines would be a better approach. However, if it isn’t something you do often this quick approach using only the GDAL utilities and a bit of Python is worth knowing. | https://spectraldifferences.wordpress.com/category/general-remote-sensing/ | CC-MAIN-2018-26 | refinedweb | 264 | 58.79 |
09 April 2010 17:57 [Source: ICIS news]
LONDON (ICIS news)--Lotte Chemical UK has restarted its 500,000 tonne/year purified terephthalic acid (PTA) plant in Wilton, UK, after a 13-month shutdown, a company source said on Friday.
“We are up-and-running and on-spec... We will start shipping [PTA] next week as we steadily increase rates,” said Nick King, the company’s PTA commercial director.
King added that the company’s 150,000 tonne/year polyethylene terephthalate (PET) unit, located at the same site, was still on schedule to start up on 15 April.
He said it as an “opportune moment” to bring Lotte’s manufacturing facilities in ?xml:namespace>
The downstream PET sector had experienced tightness for much of the year, largely due to a lack of imported material and delays in shipments from
Targets of plus €30/tonne ($40/tonne) for April PTA were heard, despite the fact that this month’s price for feedstock paraxylene (PX) is yet to be confirmed.
March PTA levels settled at €727-757/tonne FD (free delivered) NWE (northwest
The target set in December 2009 was to restart the PTA plant at the beginning of April, but the asset transfer agreement was only signed by previous owners, Artenius
Lotte also needed final approval from the EU before it could proceed with plans for its newly acquired
So it was not until 1 March that a crew had been recruited and preparation for the restart could begin, he said.
Lotte Chemical UK, a subsidiary of KP Chemical, bought Artenius
Artenius
($1 = €0.75)
For more on PTA, PET | http://www.icis.com/Articles/2010/04/09/9349677/lotte-chemical-uk-restarts-wilton-pta-after-a-13-month-outage.html | CC-MAIN-2014-52 | refinedweb | 269 | 60.28 |
table of Contents
- Introduction
- Equality comparison of value types and reference types
- Functions related to equality comparison
stringand
System.Uriequivalent comparison
- Generic interface
IEquatable<T>
- Custom comparison method
- For example
- to sum up
Introduction
Recently, I was reading the book "C # in a nutshell". You can see that although the .NET framework has some shortcomings and deficiencies, its overall design is relatively good. Here, this article intends to elaborate on the comparison between two objects from the C # language.
Equality comparison of value types and reference types
In C #, we know that for different data types, the comparison is different. The most typical is that the value type compares whether the two values are equal, while the reference type compares whether the two reference the same object. The following example shows the difference between the two.
int v1 = 3, v2 = 3; object r1 = v1; object r2 = v1; object r3 = r1; Console.WriteLine($"v1 is equal to v2: {v1 == v2}"); // true Console.WriteLine($"r1 is equal to r2: {r1 == r2}"); // false Console.WriteLine($"r1 is equal to r3: {r1 == r3}"); // true
In this example, the type
int is a value type, and its variables
v1 and
v2 are both 3. It can be seen from the output that the two are indeed equal. However, for the reference type of
object , even if the same
int data is converted (boxed by
int data), the two are not the same reference, so they are not equal (that is, line 6). But for
r3 , they are all references to
r1 , so
r3 and
r1 are equal.
Although the value type comparison is compared by value, the reference type is compared by whether or not the same data is referenced. However, there are some special cases. Typical examples are strings and
System.Uri . Although these two types of data types are reference types (essentially classes), their results in equality judgments are similar to value types.
string s1 = "test"; string s2 = "test"; Uri u1 = new Uri(""); Uri u2 = new Uri(""); Console.WriteLine($"s1 is equal to s2: {s1 == s2}"); // true Console.WriteLine($"u1 is equal to u2: {u1 == u2}"); // true
As you can see, these two data types break the rules given earlier. Although the comparison between the two classes of
string and
System.Uri is similar, the behavior of the two implementations is not the same. Then the specific process of how different data types compare, and how to customize the comparison method will be discussed in subsequent sections. But let's first look at how equality logic is handled in C #.
Functions related to equality comparison
In the C # language system, you can know that the class
Object is the root class for all data types. From
Object .NET Core 3.0, you can see that there are four functions related to equivalence judgment, two of which are class member methods and two are class static member methods, as follows:
public virtual bool Equals(object? obj); public virtual int GetHashCode(); public static bool ReferenceEquals(object? objA, object? objB); public static bool Equals(object? objA, object? objB);
It can be noted that this is not exactly the same as in other materials. The only difference is that the parameter type passed in is
object? Instead of
object . This is mainly a nullable reference type introduced in C # in version 8.0. The nullable reference type is not the focus of this article, and it can be treated as an
object here.
Here we introduce these four functions one by one:
- Class member method
Equals. The function of this method is to compare the currently used object with the passed in object, and if they are consistent, they are considered equal. The method is set to
virtual, which means it can be overridden in subclasses.
- Class member method
GetHashCode. This method is mainly used in hash processing, such as hash tables and dictionary classes. For this function, it has a basic requirement that if two objects are deemed equal, they will return the same hash value. For different objects, this function does not require different hash values to be returned, but hopes to return different hash values as much as possible so that different object data can be distinguished during hash processing. Like the above method, it can also be overridden in subclasses because of the
virtualkeyword modification.
- Static member method
ReferenceEquals. This method is mainly used to determine whether two references point to the same object. You can also see in the source code that its essence is a sentence:
return objA == objB;Since this method is static, it cannot be overridden.
- Static member method
Equals. For this method, you can also see from the source code, first determine whether the two references are the same, and if they are not the same, then use the object method
Equalsdetermine whether they are equal. Similarly, because this method is static, it cannot be overridden.
string and
System.Uri equivalent comparison
Okay, let's go back to the original question. Why does
string and
System.Uri behave differently from other reference types, but are similar to value types? In fact, strictly speaking, the comparison of
string and
System.Uri objects is similar to the value type, but the internal details of the two are not the same.
For
string , in most cases, a string will only be saved once in a copy of the program. No matter how many string variables are created, as long as their values are the same, they will be referenced to the same memory address. So for the comparison of strings, it is still a comparison reference, but most of the same value is referred to the same object.
System.Uri different. For such class objects, how many new objects are created will open up a corresponding number of memory spaces on the heap and store data. However, when comparing, the comparison method is to first compare the references and then compare the values. That is, when the two are not referring to the same object, they are compared for equality ( source code ).
string s1 = "test"; string s2 = "test"; Uri u1 = new Uri(""); Uri u2 = new Uri(""); Console.WriteLine($"s1 is equal to s2 by the reference: {Object.ReferenceEquals(s1, s2)}"); // true Console.WriteLine($"s1 is equal to s2: {s1 == s2}"); // true Console.WriteLine($"u1 is equal to u2 by the reference: {Object.ReferenceEquals(u1, u2)}"); // false Console.WriteLine($"u1 is equal to u2: {u1 == u2}"); // true
The above example shows that both string variables point to the same data object (the
ReferenceEquals method is to determine whether two references refer to the same object, and you can see that the return value is
true ). For
System.Uri , the two variables do not point to the same object. However, in the subsequent equality judgment, they are still equal. At this time, it can be seen that the two are judged to be equal based on their values.
Generic interface
IEquatable<T>
As can be seen from the above example, whether two objects are equal in C # is basically determined by the
Equals method. However, the
Equals method is not a panacea, and this is especially true in value types.
Because the
Equals method requires that the parameter type passed in is
object . If the method is applied to a value type, it will cause the value type to be cast to the
object type, that is, boxed once. Boxing and unboxing are generally time consuming and easily reduce efficiency. In addition, the
object type means that this class of objects can be judged equal to any other class of objects, but in general, the premise of judging whether two objects are equal must be objects of the same class.
The solution adopted by C # is to use the generic interface
IEquatable<T> .
IEquatable<T> mainly contains two methods, as shown below:
public interface IEquatable<T> { bool Equals(T other); }
Compared with
Object.Equals(object? obj) , its internal function is a generic method. If a class or a structure implements this interface, then when the
Equals method is called, according to the principle of the most suitable type, First call the
Equals(T other) method in
IEquatable<T> . This avoids boxing of value types.
Custom comparison method
Sometimes, in order to better simulate real-life scenarios, we need to customize the comparison between two individuals. In order to implement such a comparison method, there are usually three steps to be completed:
- Override
Equals(object obj)and
GetHashCode()methods;
- Overloaded operators
==and
!=;
- Implement the
IEquatable<T>method;
For the first point, these two functions must be rewritten. For the implementation of
Equals(object obj) , if you implement the method in the generic interface, you can consider calling this method directly here.
GetHashCode() used to distinguish different objects as much as possible, so if two objects are equal, their hash values should also be equal, so there will be better performance in hash tables and dictionary classes.
It is not necessary for the second and third points, but in general, for better use, these two points need to be overloaded.
As you can see, all three points involve the logic of comparison. Generally speaking, we tend to put the core logic of comparison in a generic interface. For other methods, we can call the methods in the generic interface.
For example
Here, we give a small example. Imagine a scenario in which machine learning is becoming more and more popular, and talking about machine learning cannot be separated from matrix operations. For a matrix, we can use a two-dimensional array to save it. In the field of mathematics, we judge whether two matrices are equal. It is to judge whether each element in the two matrices is equal, which is the way of judging value types. In C #, since the two-dimensional array is a reference type, using the equality judgment directly cannot achieve this goal. Therefore, we need to modify its judgment method.
public class Matrix : IEquatable<Matrix> { private double[,] matrix; public Matrix(double[,] m) { matrix = m; } public bool Equals([AllowNull] Matrix other) { if (Object.ReferenceEquals(other, null)) return false; if (matrix == other.matrix) return true; if (matrix.GetLength(0) != other.matrix.GetLength(0) || matrix.GetLength(1) != other.matrix.GetLength(1)) return false; for (int row = 0; row < matrix.GetLength(0); row++) for (int col = 0; col < matrix.GetLength(1); col++) if (matrix[row,col] != other.matrix[row,col]) return false; return true; } public override bool Equals(object obj) { if (!(obj is Matrix)) return false; return Equals((Matrix)obj); } public override int GetHashCode() { int hashcode = 0; for (int row = 0; row < matrix.GetLength(0); row++) for (int col = 0; col < matrix.GetLength(1); col++) hashcode = (hashcode + matrix[row, col].GetHashCode()) % int.MaxValue; return hashcode; } public static bool operator == (Matrix m1, Matrix m2) { return Object.ReferenceEquals(m1, null) ? Object.ReferenceEquals(m2, null) : m1.Equals(m2); } public static bool operator !=(Matrix m1, Matrix m2) { return !(m1 == m2); } } Matrix m1 = new Matrix(new double[,] { { 1, 2, 3 }, { 4, 5, 6 } }); Matrix m2 = new Matrix(new double[,] { { 1, 2, 3 }, { 4, 5, 6 } }); Console.WriteLine($"m1 is equal to m2 by the reference: {Object.ReferenceEquals(m1, m2)}"); // false Console.WriteLine($"m1 is equal to m2: {m1 == m2}"); //true
The logical implementation of the comparison is in
Equals(Matrix other) . In this method, first determine whether two matrices refer to the same two-dimensional array, then determine whether the number of rows and columns is equal, and finally determine according to each element. The whole core logic is here. For
Equals(object obj) and
== and
!= , Call
Equals(Matrix other) directly. Note that when the
== symbol is overloaded, you cannot directly use
m1==null to determine whether the first object is empty, otherwise it will call the
== operator overload function in an infinite loop. If you need to make a reference judgment in this function, you can use the static method
ReferenceEquals in the
Object class to judge.
to sum up
In general, the equality comparison in C # refers to a rule: the value type compares whether the value is equal, and the reference type compares whether the two refer to the same object. In addition, this article also introduces some functions and interfaces related to equality judgment. The function of these functions and interfaces is to build a framework for equality comparison. Through these functions and interfaces, not only can we use the default comparison rules, but we can also customize the comparison rules. At the end of this article, we also give an example to simulate the use of custom comparison rules. With this example, we can clearly see the implementation of custom comparison. | http://www.itworkman.com/85998.html | CC-MAIN-2020-50 | refinedweb | 2,107 | 64.2 |
DEBSOURCES
Skip Quicknav
sources / ngspice / 32.2+ds-1 /
Remarks about the source of ngspice in relation of the DFSG
-----------------------------------------------------------
NGSpice before version 28 has used some licenses that are not considered as
compatible with the DFSG (Debian Free Software Guidelines [1][2]). Especially
the used SPICEDOC, CIDERLICENSE and the Educational Community License version
1.0 aren't redistributable within Debian main.
Most parts of the NGSpice release 27 has solved such issues as upstream has
done a re-licensing of source code parts to the New BSD license.
Nevertheless some parts of ngspice wasn't DFSG clean and lacking license
information.. By asking upstream which parts are not re-licensed (until
version 27) to the New BSD license it turned out that the following parts of
the source code are left:
./doc
./src/ciderlib
./src/spicelib/devices/adms
The conversion about clearing the licensing situation for NGSpice 27 can be
found here:
By releasing version 28 of NGSpice the above mentioned source code parts had
been re-licensed to the New BSD license or even dropped from the source.
This means the source of NGSpice starting with version 28 is DFSG compatible.
We need to filter out some folders/files due no relevance for Debian while
importing source code tarballs.
./visualc
./visualc-shared
./doc/manual.pdf
If you found any issue related to used licenses in NGSpice please don't
hesitate to get in contact with the packaging/maintaining team. Please contact
the team by sending a email to <pkg-electronics-deve@alioth-lists.debian.org>.
[1]
[2]
Source code management within Debian
------------------------------------
This package is maintained with git-buildpackage(1). It follows DEP-14
for branch naming (e.g. using debian/sid for the current version
in Debian unstable).
It uses pristine-tar(1) to store enough information in git to generate
bit identical tarballs when building the package without having
downloaded an upstream tarball first.
When working with patches it is recommended to use "gbp pq import" to
import the patches, modify the source and then use "gbp pq export
--commit" to commit the modifications.
The changelog is generated using "gbp dch" so if you submit any
changes don't bother to add changelog entries but rather provide
a nice git commit message that can then end up in the changelog.
It is recommended to build the package with pbuilder using:
gbp buildpackage --git-pbuilder
For information on how to set up a pbuilder environment see the
git-pbuilder(1) manpage. In short:
DIST=sid git-pbuilder create
gbp clone
cd ngspice
gbp buildpackage --git-pbuilder
-- Carsten Schoenert <c.schoenert@t-online.de> Sat, 14 Jun 2019 19:51:07 +0200 | https://sources.debian.org/src/ngspice/32.2+ds-1/debian/README.source/ | CC-MAIN-2020-34 | refinedweb | 444 | 52.19 |
Hi !
I was going to write a test that asserts that my home page
controller’s index action is available for guests:
class RootControllerTest < Test::Unit::TestCase
def test_guest_access_granted_to_home_page
get :index
assert_response :success
end
end
Obviously, this test fails. If I change the dev DB, I can test in the
browser, and it works fine. But, the test DB does not contain the
necessary permissions and roles.
I added this to test/test_helper.rb:
unless Object.const_defined?(‘PermissionSynchronized’)
$stderr.puts “Synchronizing permissions”
Permission.sychronize_controllers
PermissionSynchronized = true
end
which ensures my permissions are created for the test environment.
The only thing missing is now roles. How should I map them ? Should
I write a SQL copy of the dev DB to the test DB ?
This is my first exposure to UserEngine.
Thanks for any help ! | https://www.ruby-forum.com/t/userengine-and-the-test-environment/55006 | CC-MAIN-2020-50 | refinedweb | 134 | 60.92 |
Steve Greenland <steveg@moregruel.net> writes: > I think the idea of a namespace for usernames used by packages is a good > idea, but rather than "debian-", we should take this to the LSB folk, so > that we can get it done once. It may be worth considering using the technique that Dan Bernstein advocates for these sorts of users, namely pre-pending those names with a single capital letter. There's a fair bit of discussion about this particular technique and why it was chosen at <>. LSB may not want to use the same letters, but some sort of prefix like "L" for LSB-standardized accounts could work. The capital letter approach has the advantage of keeping names short (so ls and friends don't look odd) and being quite legal in account names, but still looking significantly "weird" to users. It does have the drawback that you could end up with accounts that differ only in case, which means that MTAs would probably have to be checked to make sure that they do the right thing. -- Russ Allbery (rra@stanford.edu) <> | https://lists.debian.org/debian-devel/2003/11/msg02321.html | CC-MAIN-2014-15 | refinedweb | 182 | 66.27 |
02:35 PM
Hi,
I'm trying to build a script that will open a file of phone numbers, 1 per line. It then reads in each line and add each line to an array. I add the array to the context.
def msisdnList = [] new File("C:\\Users\\Jerry\\Documents\\MVNO\\soapui\\msisdn_99.txt").eachLine { f -> if (f != null ) { msisdnList.add(f) //log.info f } } if (msisdnList.size() < 1) { testRunner.fail("No request msisdn") } context.put('msisdnList', msisdnList)
In the next step, i check i can read the array, which works fine:
log.info "MSISDN: ${context.get('msisdnList').last()}"
In the failing step, i try a soap request which (envelope and header skipped) like this:
<ADD_SOC_REQUEST> <MSISDN>${context.get('msisdnList').last()}</MSISDN> <SOC>SMPGL2</SOC> </ADD_SOC_REQUEST>
running this, I get error because what goes out is
<MSISDN></MSISDN>
Does substitution work in SOAP request?
Thanks.
08-12-2017 06:17 AM
Can you try one thing ?
Inplace of putting all those directly in the Soap request.
1-Just add a data generator before the Soap request.
2-Add a Template in the data generator .
3-Add this in the Template.
<ADD_SOC_REQUEST> <MSISDN>${context.get('msisdnList').last()}</MSISDN> <SOC>SMPGL2</SOC> </ADD_SOC_REQUEST>
4-Run the data generator .
5-Now call & add the template key in the Soap request & run the step.
Hope it will work .
08-14-2017 06:54 AM
I am looking for a SoapUI solution. As far as I can see, the data generator is part of SoapUI PRO. I don't have $599 to solve this problem!
Is this possible on SoapUI Open Source?
08-14-2017 07:11 AM - edited 08-14-2017 07:17 AM
You don't have $599 to solve this problem! sorry to hear that . I thought you are using PRO version .
You will get the solution soon by any expert.
yesterday
More info about the context variable
Can you set a property value from the list then use that property in a request?
context.testCase.setPropertyValue( "MyProp", context.get('msisdnList').last() ) | https://community.smartbear.com/t5/SoapUI-Open-Source/soap-request-doesn-t-replace-variable/m-p/147695 | CC-MAIN-2017-34 | refinedweb | 340 | 62.04 |
Working with Threads in Java parallel, also known as concurrent programming.
Threads in Java
Before starting the practical explanation of Thread, understand that these are subdivisions of the processes. Each process has several threads (lines of instructions), so we can share parts of our process (Java program) to work in parallel.
The threads are in our day-to-day, in all the experiments in our computer. When we are listening to music and looking at facebook at the same time, we are conducting a parallel processing, even if it is transparent to the user.
In a Java program we want to run two or more threads at the same time, ie, two or more internal procedures of the program at the same time. To simplify the explanation of threads in Java, let’s take a practical example.
Imagine you have one procedure that consumes a lot of processor time, let’s assume the following example of a calculation that makes queries to a Web Service:
Procedure without common thread
public void CalculateTotalReceived () { //Receives about 70 thousand); }
The above procedure seems simple (in fact it is simple), a list with about 70 thousand records are received. For each record value and sum is picked up. After this, capture a value for adjustment percentage (captured from a WebService which can take time to respond), and recalculates the value added. Finally returns the result via WebService.
Note here that, the procedure here would take few minutes, and will not return anything to the user and just an internal communication between Web Services keep happening. We can not stop the application to perform the above procedure. Well imagine if you’re doing a simple registration and have to wait for about 5 minutes to complete the above processing.
The solution then is to make this procedure to run concurrently, ie while the user is performing the record, the above procedure is also performed, and probably when he has finished the registration, the above procedure has also ended.
In the code below we use the same code, but using the concept of threads. We will create a thread for a specific block of code through the class java.lang.Thread.
There is an interface called Runnable that has a run method. Inside the run method, you should include the procedures you want to run in parallel, so we put all the above code within a method run. Runnable is just a contract, we need some class that implements and does the work of “parallelization”, and that class is the Thread class.
Using Thread
public void CalculateTotalReceived () { new Thread () { @ Override public void run () { // Receives about 70thousand); } }.start (); }
When we do “.Start ();” we are already starting the parallel processing, and releasing the program to be executed by any other thread. So assimilating the following idea:
- If you want your program does not “lock the user” for that particular procedure or is taking a long time to execute, then use Thread.
- If you want your class to be processed in parallel, but it already extends another, you can choose to implement the Runnable, which is the standard interface for Thread. For best practice, implement Runnable instead of extending Thread.
- Pay attention to another very important point: The programmer has no control over the processor scheduler. This means that the processes are executed in parallel, you have no way of knowing what is execution order of these.
In the example below we put 2 counters to run in parallel, you will realize that the results may differ each time you run, or even from computer to computer.
Test Counters with Thread
package net.javabeat; public class MyTest { static int i = 0; public static void main (String [] args) { new Thread (t1). start (); new Thread (t2). start (); } private static void countMe (String name) { i++; System.out.println ( "Current Counter is:" + i + ", updated by:" + name); } private static Runnable t1 = new Runnable () { public void run () { try { for (int i = 0;i <5; i ++) { countMe ( "t1" ); } } catch (Exception e) {} } }; private static Runnable t2 = new Runnable () { public void run () { try { for (int i = 0;i <5; i++) { countMe ( "t2" ); } } catch (Exception e) {} } }; }
I’ll leave it up to you to test the above code and see what the outcome, because each computer may have a different order of execution,hence the ouptut may vary.
Summary
Use the resources of concurrent programming with care and only in the moments that really need it. Do not use Runnable in all codes thinking that your program will be faster, however, a process may need other resources. So carefully review the need to use this powerful feature . If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook. | http://www.javabeat.net/threads-java/ | CC-MAIN-2015-35 | refinedweb | 786 | 59.84 |
. Others, such as JavaScript, Classic ASP and PHP (without any frameworks attached), make users do a lot more work to keep their code base manageable.
One of the features that was included with C#/VB.NET is the idea of name-spaces, which are not necessarily a requirement to write object-oriented code, however do a a great job of creating a hierarchical class structure and generally keeping your classes, methods, enumerations, etc in non-spaghetti-code state.
What is a namespace?
A namespace can best be described as a collection of classes and enumerations.
An Example
Typically, you would want to put classes and enums together in a namespace that are related. For example, if you were considering making some C# code to represent the organization structure of a library, you might have a namespace for the library as a whole, then have sub-namespaces for different aspects of the library, such as the materials that can be rented out in a library, the library’s staff members, and its facilities.
Here’s what a hierarchical structure of namespaces might look like in a Library in C#
You’ll notice that name spaces can be hierarchically organized and that name spaces can contain both classes and enumerations. They can also hold delegates, interfaces and structs. They cannot directly include methods, which must be contained within a class.
Referencing a Class in a Namespace
If you were to create the class that we just made above and put it into a C# application (most likely in the app_code folder), this is how you would create some of the classes above:
AdministrationBuilding – Library.Facilities.AdministrationBuilding thisBuilding = new Library.Facilities.AdministrationBuilding();
Journal – Library.Materials.Periodicals.Journal thisJournal = new Library.Materials.Periodicals.Journal();
BookType – Library.Materials.BookType thisType = new Library.Materials.BookType();
Making Good use of the Using Declaration
If you plan to make use of a namespace a lot on a particular form, web-form, or any other C#/VB file, you can import the namespace directly on the page much in the way that you might import one of the inherited namespaces under the “System” class.
When doing development, if you wanted to create a DataTable object, you would probably want to add “using System.Data;” to the top of your page so that you can reference the variable type by just using “DataTable ThisTable” rather than “System.Data.DataTable ThisTable”.
You can also do this with your own namespaces.
Here’s how you would import the “periodicals” namespace in C# — using Library.Materials.Periodicals;
Here’s how you would import the “periodicals” namespace in VB.NET — Imports Library.Materials.Periodicals
Now, instead of creating a journal like we did above, we could simply write “Journal thisJournal = new Journal();” to create a new object of type Journal.
Here are a few other good resources on Namespaces:
- Creating and using Namespaces in VB.NET and C# (VB.NET Heaven)
- Using Namespaces (MSDN)
- Namespaces in C# (C Sharp Help)
Namespaces get really important when you start reflecting as well. When you dynamically instantiate classes, or spin the classes in an assembly to pick off attributes, it’s handy to isolate them in their own namespace.
Also, we use the namespace to drive the file location. We organize our class files into a folder tree, each folder named for a namespace segment. We you get 50+ classes, it makes it much easier to find the right file.
Thanks for the insight Deane!
Why do we create namespace? if we can simply add a class and define functions in them. Please explain more, I am a beginner. | http://adventuresindevelopment.com/2010/03/23/how-to-make-use-of-namespaces-in-c-and-visual-basic-net/comment-page-1/ | CC-MAIN-2018-09 | refinedweb | 602 | 55.13 |
Oval() point placement
Hi there,
I'm curious as to why the output from
oval()has on-curves on angled extrema rather than traditional 0/90 extreme points? Sometimes I build patterns, export to PDF, and then work with them in Illustrator—but this point structure makes it more difficult. Screenshot in Illustrator below.
Thanks,
Ryan
I dont’t know why the extremes are angled…
here’s a way to get the desired result by modifying
oval:
def twist(func, angle): def wrapper(x, y, w, h): with savedState(): translate(x + w/2, y + h/2) rotate(angle) func(-w/2, -h/2, w, h) return wrapper oval = twist(oval, 45)
when working with
BezierPath, it’s possible to rotate the shape:
B = BezierPath() B.oval(x, y, w, h) B.rotate(45, (x + w/2, y + h/2))
hope this helps!
I don't know why but my wild guess is it has todo with drawing ovals at more extreme w, h ratios, when the points are on the extremes you will need a pushing point in the middle to nice curve back.
@gferreira you method only works for circles...
the drawBot RoboFont extension has points on the extremes, cause the context is type... see
see the big difference when the oval is getting thinner...
def straightOval(x, y, w, h): c = 0.55 hx = w * c * .5 hy = h * c * .5 path = BezierPath() path.moveTo((x + w * .5, y)) path.curveTo((x + w * .5 + hx, y), (x + w, y + h * .5 - hy), (x + w, y + h * .5)) path.curveTo((x + w, y + h * .5 + hy), (x + w * .5 + hx, y + h), (x + w * .5, y + h)) path.curveTo((x + w * .5 - hx, y + h), (x, y + h * .5 + hy), (x, y + h * .5)) path.curveTo((x, y + h * .5 - hy), (x + w * .5 - hx, y), (x + w * .5, y)) path.closePath() drawPath(path) x, y, w, h = 10, 10, 8.0, 146.0 oval(x, y, w, h) straightOval(x + w + 10, y, w, h) | https://forum.drawbot.com/topic/243/oval-point-placement | CC-MAIN-2020-16 | refinedweb | 337 | 86.6 |
2691/what-are-peers-and-how-a-user-enrolls-into-a-specific-peer
In fabric, there is an admin, he manages the entities (the users, the peers..) that will be the part of the system. The admin also enrol an admin user for each organization, or he enrols the peers and users for each organization.
After enrolling each entity, the registry is done. When you do a registry aginst the certificate authority(CA), the CA generates a pair of keys, which is issued by the CA root. The user and the peer are thus enrolled to the CA. You need a peer to communicate with other peers and the orderer.
Also, you need a user to call the peer to genrate the transactions. When you create a channel, you have to define who is going to take part on it, i.e. you define which peers are going to interact among them. if your peer is not defined in the channel configuration, the acces for it will be restricted.
This can be done by specifying desired permissions for each org or orderer in the configtx.yaml file. The structure is as follows:
Channel:
Policies:
Readers
Writers
Admins
Here you have to set the Read, Write and Admin configuration by mentioning the name of the member.
Complete description here.
Hyperledger peers neither mine the block nor ...READ MORE
Is your transaction actually called 'OrderPlaced' (in ...READ MORE
To answer your first query.. Blockchain is ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
I know it is a bit late ...READ MORE
Hashgraph uses Superior distributed ledger technology. Hashgraph ...READ MORE
On higher level comparison, there are quite ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/2691/what-are-peers-and-how-a-user-enrolls-into-a-specific-peer?show=2698 | CC-MAIN-2022-27 | refinedweb | 321 | 67.25 |
If you’re trying to come up with an error response model for your API, but are finding it difficult to settle on a format that is simple, yet future-proofed; look no further!
In this article, I expound the virtues of the ‘Problem Details’ RFC standard and why I believe it’s a no-brainer to use it for your project rather than trying to reinvent the wheel.
I explain the key aspects of the standard and provide code samples to help you understand how you can implement it in your application.
Why use a standard?
Aside from helping you to avoid agonising over the exact format of your API error model, it makes sense to use a standard model for a number of other reasons.
For a start, why waste time rethinking the structure of your error response for every new API you create? Basing your error model on a solid standard will save you valuable time. It’s like making use of design patterns and one of the key reasons that we use patterns is to avoid solving the same problem multiple times.
Let’s also consider this from an API client point of view. Why should developers who are integrating with our APIs have to rewrite their error handling logic for every new API we provide? It makes much more sense to keep things consistent for the client’s sake too.
I believe it is highly valuable to relay error data to clients in a way that is both human-readable and machine-readable. By choosing this path we will make it straightforward for developers to implement error handling for our API and we will make it possible for future systems to respond to errors intelligently by working to a standard format.
Problems Details explained
Problem Details for HTTP APIs is an RFC standard. It describes an API error response format that is both machine-readable and easy to understand for humans.
To make this more concrete, let’s look at an example error response taken from the RFC.
HTTP/1.1 403 Forbidden Content-Type: application/problem+json Content-Language: en { "type": "", "title": "You do not have enough credit.", "detail": "Your current balance is 30, but that costs 50.", "instance": "/account/12345/msgs/abc", "balance": 30, "accounts": ["/account/12345", "/account/67890"] }
As you can see, the preferred format of the response is JSON. According to the RFC, the standard parts that make up the error response model are
type,
title,
status,
detail and
instance.
Let’s look at the various fields within the model to see what they are intended for. I have adapted the descriptions below which are based on the official RFC descriptions.
type
A URI reference that identifies the problem type. The specification encourages that the type provided should be human-readable using HTML. If the member is not present its value is assumed to be
"about:blank".
title
A short, human-readable summary of the problem type. It SHOULD NOT change from occurrence to occurrence of the problem, except for the purposes of localisation.
status
The HTTP status code generated by the server.
detail
A human-readable explanation that is specific to this occurrence of the problem.
instance
A URI reference that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced.
The good parts
One of the things I particularly like about the standard is that it clearly describes a base error model containing the properties that you must support. However, it also provides you with scope to extend the model should you need to.
The RFC permits what are known as ‘problem-specific extensions’. These allow you to expand on the basic model with any additional members that make sense for your application. The
balance and
account fields from the RFC sample located at the beginning of the previous section are examples of extension members.
In regards to the standard members of the model, my preference is to take a pragmatic approach.
For example, let’s consider the
type property. For most of the projects I am working on, it isn’t practical to have a webpage dedicated to each type of possible error. Given that the standard specifically states that the value is assumed to be
"about:blank" if it is not present, I usually leave this member out.
The
title and
detail members are straightforward to implement and I always make sure that an appropriate HTTP
status code is returned for every possible error.
Note that the colon (:) character is used to separate the URN into its constituent parts.
In this example, the URN can be broken down as follows.
urn
The standard URN prefix.
companyname
The Namespace Identifier (Company).
api
The first part of the Namespace Specific String (i.e. the API for our ‘company’).
error
The second part of the Namespace Specific String (i.e. this URN describes an error).
protocol
The third part of the Namespace Specific String (i.e. this is a generic HTTP protocol error as opposed to a custom one).
badRequest
The fourth part of the Namespace Specific String (i.e. the HTTP status code in JSON format).
f29f57d7-e1f8-4643-b226-fa18f15e9b71
The fifth part of the Namespace Specific String (i.e. a unique GUID which we can use for cross-referencing in our logs).
Of course, the structure of this URN can be adjusted to suit your own particular needs. However, I feel that the example described above is universal in many respects. If logged, this URN string would help us to identify what kind of error we are looking at very quickly.
Codifying the standard
Now, let’s look at how to implement the Problem Details pattern in an API application.
In my code examples, I’m using C# within an ASP.NET Web API project.
First of all, let’s consider what the base definition of the Problem Details model looks like as a class in code.
/// <summary> /// A machine-readable format for specifying errors in HTTP API responses based on. /// </summary> public class ProblemDetails { #region Properties /// <summary> ///". /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Type { get; set; } /// <summary> /// A short, human-readable summary of the problem type. /// It SHOULD NOT change from occurrence to occurrence /// of the problem, except for purposes of localization(e.g., using proactive content negotiation; /// see[RFC7231], Section 3.4). /// </summary> public string Title { get; set; } /// <summary> /// The HTTP status code([RFC7231], Section 6) generated by the origin server for this occurrence of the problem. /// </summary> public int? Status { get; set; } /// <summary> /// A human-readable explanation specific to this occurrence of the problem. /// </summary> public string Detail { get; set; } /// <summary> /// A URI reference that identifies the specific occurrence of the problem. /// It may or may not yield further information if dereferenced. /// </summary> public string Instance { get; set; } #endregion }
As you can see, the base model represents most of the members as a
string. I’m using the JSON.NET library to signify that the
Type property should not be serialised if a value has not been specified for it.
Note that if you’re using ASP.NET Core there is a
ProblemDetails class built into the framework. The code I’m using above is based on this built-in class.
Next, let’s extend the standard
ProblemDetails class with our own custom members.
// <summary> /// A machine-readable format for specifying errors in HTTP API responses based on. /// Contains 'extended members' which are allowable in accordance with the official RFC. /// </summary> public class ApiProblemDetails : ProblemDetails { #region Properties /// <summary> /// The API Error Code, represented as a string value. /// </summary> public string Code { get; set; } /// <summary> /// The API Error Category, represented as a string value. /// </summary> public string Category { get; set; } /// <summary> /// A collection of model Validation Errors relating to the API request. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public ICollection<ValidationError> ValidationErrors { get; set; } #endregion }
In the
ApiProblemDetails class above we add a
Code property to represent our own custom error code. The value for this could be
"resourceNotFound" as an example. You can make this a numeric code if you prefer. Personally, I’ve decided to make it a string/enum to avoid the quandary regarding the categorisation of custom error codes i.e. should you divide your error codes into client and server errors like HTTP does?
Here is an enumeration of possible
ApiErrorCode values which can be extended to suit your application.
/// <summary> /// Possible API Error Codes. /// </summary> public enum ApiErrorCode { None, ResourceInvalid, ResourceNotFound }
The
Category property allows us to separate standard
protocol (HTTP) errors from custom errors which are specific to our application e.g.
"custom" or
"yourProductName".
Lastly, the
ValidationErrors property provides a way for us to pass a list of validation errors to the client whenever an invalid model has been supplied to POST/PUT operations etc.
The
ValidationError class simply holds the
Name of the invalid model property and the
Description of the validation error.
/// <summary> /// Represents a model Validation Error. /// </summary> public class ValidationError { #region Properties /// <summary> /// The Name of the invalid model property. /// </summary> public string Name { get; set; } /// <summary> /// The Description of the model error. /// </summary> public string Description { get; set; } #endregion }
This concludes our tour of the error model classes. We’ve taken the standard Problem Details model and extended it, making it a little more flexible with our own extension members.
For your project, the base model may be enough to meet your requirements. However, I believe that the additional members we’ve looked at complement the structure of the base model nicely. They give us a way to let our clients know when something very specific happens. This removes our sole reliance on HTTP status codes which can sometimes be too generic.
Building a framework
I’ve created a sample Web API project and made it available on GitHub. The project implements the Problem Details pattern as described in the section above and demonstrates a framework for handling application errors globally.
The key classes within the project which you should check out, are discussed below.
ApiException
To make it simpler for us to trigger API error responses I’ve created an
ApiException class that encapsulates everything that we need to generate a Problem Details error response.
We can throw an
ApiException at any time from our API Controllers and the error will be caught and processed by a custom global ‘Exception Handler’. An appropriate Problem Details error response will then be generated and returned to the client.
Here is an example of throwing an
ApiException from an API Controller action.
// Fire an error and return a 'Not Found' status if there are no Todos. throw new ApiException(HttpStatusCode.NotFound, ApiErrorCode.ResourceNotFound);
Note that by specifying
ApiErrorCode.ResourceNotFound we provide the client with the means to differentiate between general
404 HTTP errors and cases where the resource itself cannot be found.
ApiExceptionHandler
We can handle an
ApiException (or any other type of exception) globally within an ASP.NET Web API project by deriving a class from the
ExceptionHandler base class.
Within the
ApiExceptionHandler class, we create, log and return the Problem Details error response.
ApiValidationActionFilter
In order to handle model validation errors automatically and reduce noise in our API Controller code, I’ve implemented a custom ‘Action Filter’. The filter checks the ‘Model State’ automatically and throws an
ApiException if there are any problems, with the validation errors passed along for convenience.
This is how the
ValidationError collection gets populated and passed back to our clients.
ApiErrorInstanceUrn
To simplify the generation of the URN for our
Instance property, I’ve created a class that encapsulates the parts which make up the URN and the logic for generating and formatting it.
Some other classes which you may find interesting within the project are as follows.
ApiErrorFactory
ApiExceptionLogger
HttpStatusCodeExtensions
Note that the ‘Action Filters’, ‘Handlers’ and ‘Loggers’ mentioned above are all registered globally within the
Register method of the
WebApiConfig class.
If you want to try the project out in your own development environment, after cloning the repo and running the application, type the following into the address bar of your web browser to see an example error response.
This should yield the following JSON output.
{ "code": "resourceNotFound", "category": "custom", "title": "Not Found", "status": 404, "detail": "The item you are looking for cannot be found.", "instance": "urn:jc:api:error:custom:resourceNotFound:1269d728-1170-42e1-8805-d1b9870bd7f7" }
Note that the port number (54283) in the above URL may be different on your machine, so be sure to adjust it accordingly.
Conclusion
I really believe that the standardisation of error responses is a great thing for both API producers and consumers. It helps both parties focus on what matters, with the comfort of knowing that errors are being handled in a uniform manner.
In my opinion, the Problem Details standard offers both simplicity and flexibility and is a great basis for creating an error response model. The ability to extend the model when needed provides assurance that it can be adapted to suit future requirements.
I strongly encourage you to try adopting the Problem Details standard for your next project.
I hope you enjoyed this post! Comments are always welcome and I respond to all questions.
If you like my content and it helped you out, please check out the button below 🙂
Sridhar Krishnamurthy
Thank you. Most of us tend to backseat ‘error reporting’ and botch up the error/exception data model therein.July 26, 2021
Jonathan Crozier
Yes, it is vital to carefully consider your API error handling format upfront. I’m glad you found the post helpful.July 27, 2021 | https://jonathancrozier.com/blog/base-your-api-error-response-model-on-a-solid-standard-with-the-problem-details-rfc | CC-MAIN-2021-49 | refinedweb | 2,273 | 55.95 |
I am trying to use Xamarin UITest locally on an iOS app, running an iOS Simulator, but I cannot get any tests to run on the iOS Simulator.
When I run the tests, they do fail (even my "Assert.Pass()" test)
What is meant by the "important properies" message? When I tried to add ".PreferIdeSettings()" to the ConfigureApp chain, it doesn't compile.
Also, on the first TODO, there is mention of "right click Test Apps, select Add App Project", but I cannot find this in my Xamarin Studio Unit Tests windows (which only lets me run, stop and view test results)
[SetUp] public void BeforeEachTest () { // // TODO: If the iOS app being tested is included in the solution then open // the Unit Tests window, right click Test Apps, select Add App Project // and select the app projects that should be tested. app = ConfigureApp .iOS // TODO: Update this path to point to your iOS app and uncomment the // code if the app is not included in the solution. // .AppBundle ("../../../iOS/bin/iPhoneSimulator/Debug/UITester.iOS.app") .AppBundle ("../../../Touch.Container/bin/iPhoneSimulator/Debug/MyContainer.exe") .DeviceIdentifier("<deviceID>") .EnableLocalScreenshots() .StartApp (); app.Repl (); }
01-06-2015 09:16:21.724 -05:00 - 4 - iOS test running Xamarin.UITest version: 0.7.1
01-06-2015 09:16:21.792 -05:00 - 72 - Skipping IDE integration as important properies are configured. To force IDE integration, add .PreferIdeSettings() to ConfigureApp.
Not sure why you cannot see Test Apps in the Unit Tests window. Xamarin Studio will look at the referenced assemblies and show the Test Apps item if it finds Xamarin.UITest is referenced. You should be able to workaround this by adding a normal reference from the UITest project to your main iOS project. Then you will need to edit the .csproj file and set the property on that reference to false.
The
Skipping IDE integration as important properies are configuredmessage is just saying that the UITest startup code in your BeforeEachTest method is overriding Xamarin Studio's settings. If you create a new iOS solution you will see a UITest project already configured to use the main iOS project. In this UITest the startup code will be something similar to:
With the above code Xamarin Studio will use the currently selected iOS simulator when running the UITests. You should also be able to do the same thing with the PreferIdeSettings () method.
Thank you, Matt. Unfortunately, when I try to add a reference to my iOS app, the project is "greyed out" with:
(Incompatible target framework: Xamarin.iOS, Version=1.0)
Ah, yes. The UITest project is targeting .NET framework whilst the iOS project does not so you cannot do that from within Xamarin Studio. So if you cannot do that from the Unit Tests window then you would have to manually edit the .csproj file which is a bit of a pain.
Not sure why you are not seeing a Test Apps tree item in the Unit Tests window. With Xamarin Studio 5.9.1 installed and an iOS project open that does not have a UITest project I can add a new UITest project to the solution. Then the Unit Tests window will show a Test Apps item once all the tree nodes are expanded. Before select the Add App Project I would add the Xamarin.TestCloud.Agent NuGet package to the original iOS project, then you should be able to add a reference to it using the Add App Project.
With a new UITest project created the Test Apps item should be available in the Unit Tests window. Xamarin Studio will show the Test Apps item if the project has a reference to the Xamarin.UITest assembly, which it should by default if you have created a new UITest project from one of the project templates.
Thank you so much for your analysis and guidance. I started over with a different iOS app.
I am now seeing the "Test Apps" item in the Unit Tests Window (In Xamarin Studio 5.9.2, build 2)
Furthermore, following your instructions to add the Xamarin Test Cloud Agent to the iOS app, I was able to "Add App Project" (prior to putting the Test Cloud Agent on my app "container" project, the iOS project was not available as a checkbox, so I did, indeed, need that Test Cloud Agent in the target app)
Now, when I run tests my Mac prompts for admin pw ("Instruments" wants access), which I granted. Do you get that everytime?
I seem to be making progress (I am new to Xamarin UITesting and trying to get some iOS tests with Tap, Wait, EnterText etc. to help me learn)
My goal for this stage was to keep it local (not use the TestCloud) and also to use C# and not Calabash/Ruby.
When I run my tests now I get:
SetUp : System.Exception : Unable to contact test backend running in app. A common cause is that the app is not properly linked with Calabash. Please verify that it includes the Calabash component.
Does this mean it's trying to run on TestCloud?
I do not get a prompt from Instruments asking for my admin credentials on my Mac.
The unable to test backend running in app message is probably because the iOS app was deployed to the simulator at some point in the past when Xamarin.TestCloud.Agent was not being referenced by. There is a limitation with the version of Xamarin.UITest that is installed out of the box with Xamarin Studio 5.9 where it does not replace the iOS app in the simulator. To fix this you can either reset the simulator, one of the menu options from the iOS simulator is Reset Content and Settings, or alternatively you can update your NuGet packages for Xamarin.UITest and TestCloud.Agent. With Xamarin.UITest 0.8.0 the application should be re-deployed each time to the simulator so you do not need to reset the simulator.
You will only be using Test Cloud if you have selected Run in Test Cloud and that will try to upload the app and then open a browser on Test Cloud for the final configuration.
I tried both suggestions (re-set my iOS Simulator/update the Xamarin.UITest package to 0.8.0 which is where it currently sits). Still getting these errors when I run my tests:
SetUp : System.Exception : Unable to contact test backend running in app. A common cause is that the app is not properly linked with Calabash. Please verify that it includes the Calabash component.
and
SetUp : System.Exception : The app bundle in /Users/steverawlins/Source/TRUNK/Samples/ViewChoices/Touch.Container/bin/iPhoneSimulator/Debug/TouchContainer.app does not seem to be properly linked with Calabash. Please verify that it includes the Calabash component.
Must I install Calabash as a prerequisite? I'm installing the Calabash gems now, per Xamarin/Calabash
No you do not need to install Calabash separately. If the main iOS app project is referencing the Xamarin.TestCloud.Agent NuGet package then that will have provide the needed Calabash.dll.
I added
Xamarin.Calabash.Start();to my iOS App's AppDelegate FinishedLaunching
And now the repl launches.
Oh, yes, sorry I forgot about that. The project templates in Xamarin Studio automatically add that startup code. They add it with an #ifdef so that it is only included in Debug builds. Apple will reject the app if it uses Calabash so normally it is disabled for release builds.
Thank you, Matt. My UITests are running now, locally on Simulator.
Because the target-app (the project I'm testing) was not created by a template, it didn't have the test hook. I understand now that the main prog needs to call Calabash (and that it can be conditionally compiled).
Urk... I think I even read that somewhere in Xamarin doc.
Anyway, THANK YOU for your help. My UI unit-tests are now executing using Tap, Text, Clear, WaitFor, Flash, Back() etc. and that's exciting because it's taken me some effort to get this far.
Just commenting that this is still a bug. I am using Xamarin Studio 5.9.7 (build 22) and my unit test project is Xamarin UITest 1.1.1 and NUnit Version 2.6.4. iOS app and unit test projects created with templates. I do not see "Test Apps" in my Unit Test window and cannot add references to by iOS project from unit test project.
@thedigitalsean - My only guess is that the project was created in Visual Studio so the reference to Xamarin.UITest. You might be hitting a bug in Xamarin Studio 5.9.7 where the Test Apps folder is not displayed due to the reference being created in Visual Studio. The Test Apps folder is displayed if the project has a reference to Xamarin.UITest.
If you have a reference that starts with "Xamarin.UITest, Version=..." then Xamarin Studio does not detect Xamarin.UITest and does not display the Test Apps folder. An example is shown below:
The workaround is to modify the Include attribute so it looks like:
This bug is fixed in Xamarin Studio 5.10.
Thanks for the help. However, I develop exclusively on a Mac so this cannot be Visual Studio related. My reference to UITest is already in the format you suggest:
....\packages\Xamarin.UITest.1.1.1\lib\Xamarin.UITest.dll
The project was originally created in July/August with an older version of Xamarin Studio. I deleted the UITest project due to this bug and am now trying to re-add it. The manual adding of the reference that you suggested at the beginning of this post is the only thing that has worked. I still don't get the "Test Apps" in the Unit Test window.
Not sure what problem you are hitting. Xamarin Studio checks the project to see if it references Xamarin.UITest and then will display Test Apps in the Unit Test window.
If you create a new iOS project does it display?
Does removing and then re-adding the Xamarin.UITest NuGet package cause it to be displayed?
Any exceptions in the IDE log (Help - Open Log Directory)?
Here is some additional data. Not sure if it helps. When I add the reference manually in the csproj file with
<ProjectReference Include="path to csproj"> <Project> {GUID} </Project> <ReferenceOutputAssembly>False</ReferenceOutputAssembly> <Private>False</Private> </ProjectReference>
The References show up in the References directory but it is unable to resolve any namespaces defined in the project. So my project does not compile.
If I remove the ReferenceOutputAssembly line, then a Red X appears beside the project name in the References directory. However, the namespaces will resolve and the project will compile. I got excited for a second but then all my tests fail with:
Can you open a bug on bugzilla and attach a simple example project that you can reproduce the problem, the IDE logs and the information from Xamarin Studio - About Xamarin Studio - Show Full Details.
Since we have a enterprise license, the info has been sent along with 2 sample projects to Xamarin support.
@thedigitalsean I do know from experience that the call to repl() screws everything up. It causes a big delay as I believe this to be a blocking call and my test stays in the virtual void. You might try putting the repl calling into a test
I appreciate the help @mattward and @NicholasTurner . After further investigation it turns out I was the issue. The Test Apps menu was in fact showing up. I have also learned that the run time problems I had was because I was trying to use Xamarin.UITest to run traditional NUnit unit tests in addition to the UI integration tests. To that end, I was trying to instantiate classes defined in my iOS project and unit test them. Unfortunately even though Xamarin.UITest runs in NUnit, you cannot do that.
My reason for trying this is because it is more than a little disappointing that there is no built-in way to run iOS/Android NUnit tests with Xamarin that can be automated and integrates with Xamarin Studio. The current NUnit project created with Xamarin Studio template requires the developer to manually click through a UI in the simulator for testing and debug and the results are not reported back in xml or integrated into Xamarin Studio.
Since I work in a regulated industry, I do not have the option of just running UI integration tests and skipping unit testing. So I was able to dig up some old blogs and an open source project called Touch.Unit (and, more specifically, Touch.Server) and put something together that at least allows me to run the unit tests from the command line and get my results back in xml. I'll leave the links here for anyone that may come across this post in the future:
This post gave the big picture and was especially helpful to me since we use Atlassian products:
I had to fork Touch.Unit because there is an issue where with iOS 9 I needed to specify the sdk version. I have a pull request to get it integrated but here is the base project:
my modifications:
Next, I added these lines in the AppDelegate of my test project.
Then I compile and run TouchServer with:
mono --debug /path/to/Touch.Unit/Touch.Server/bin/Debug/Touch.Server.exe -launchsim=path/to/ios/unit/test/project/bin/iPhoneSimulator/Debug/your-project.app -autoexit -logfile=TestResults.xml -sdk=9.0 -port=16384
Other helpful links:
After removing some of the unneeded header text, I can integrate the TestResults.xml in my Continous Integration system and we're happy. Now, my only wish was that Xamarin could set this up in Xamarin Studio and these results could be integrated more into the development environment when ran locally. Or at least Xamarin could provide a general guide on how to do. | https://forums.xamarin.com/discussion/comment/159824/ | CC-MAIN-2019-39 | refinedweb | 2,339 | 65.42 |
6.6. Convolutional Neural Networks (LeNet)¶
We are now ready to put all of the tools together to deploy your first fully-functional convolutional neural network. In our first encounter with image data we applied a Multilayer Perceptron to pictures of clothing in the Fashion-MNIST data set. Each image in Fashion-MNIST consisted of a two-dimensional \(28 \times 28\) matrix. To make this data amenable to multilayer perceptrons which anticapten pictures.
Fig. 6.8 Data flow in LeNet 5. The input is a handwritten digit, the output a probabilitiy over 10 possible outcomes. mini-batch. In other words, we take this 4D input and tansform it into the 2D input expected by fully-connected layers: as a reminder, the first dimension indexes the examples in the mini-batch’s going on inside LeNet may have taken a bit of work, you can see below that implementing it in a modern deep learning library is remarkably simple. Again, we’ll rely on the Sequential class.
In [1]:
import sys sys.path.insert(0, '..') import d2l import mxnet as mx from mxnet import autograd, gluon, init, nd from mxnet.gluon import loss as gloss, nn import time, we feed a single-channel example of size \(28 \times 28\) into the network and perform a forward computation layer by layer printing the output shape at each layer to make sure we understand what’s happening here.
In [2]:
X = nd.random.uniform(shape=.
Fig. 6.9 Compressed notation for LeNet5
6.6.2. Data Acquisition and Training¶
Now that we’ve implemented the model, we might as well run some experiments to see what we can accomplish with the LeNet model. While it might serve nostalgia to train LeNet on the original MNIST OCR.
In [3]:.
Here’s a simple function that we can use to detect whether we have a
GPU. In it, we try to allocate an NDArray on
gpu(0), and use
gpu(0) as our context if the operation proves successful. Otherwise,
we catch the resulting exception and we stick with the CPU.
In [4]:
# This function has been saved in the d2l package for future use def try_gpu(): try: ctx = mx.gpu() _ = nd.zeros((1,), ctx=ctx) except mx.base.MXNetError: ctx = mx.cpu() return ctx ctx = try_gpu() ctx
Out[4]:
gpu(0)
evaluate_accuracyfunction that we described when implementing the SoftMax from scratch.
as_in_contextfunction described in the GPU Computing section. Note that we accumulate the errors on the device where the data eventually lives (in
acc). This avoids intermediate copy operations that might harm performance.
In [5]:
# This function has been saved in the d2l package for future use. The function # will be gradually improved. Its complete implementation will be discussed in # the "Image Augmentation" section def evaluate_accuracy(data_iter, net, ctx): acc_sum, n = nd.array([0], ctx=ctx), 0 for X, y in data_iter: # If ctx is the GPU, copy the data to the GPU. X, y = X.as_in_context(ctx), y.as_in_context(ctx).astype('float32') acc_sum += (net(X).argmax(axis=1) == y).sum() n += y.size return acc_sum.asscalar() / n
We also need to update our training function to deal with GPUs. Unlike
`train_ch3 <../chapter_deep-learning-basics/softmax-regression-scratch.ipynb>`__,
we now need to move each batch of data to our designated context
(hopefully, the GPU) prior to making the forward and backward passes.
In [6]:
# This function has been saved in the d2l package for future use def train_ch5(net, train_iter, test_iter, batch_size, trainer, ctx, num_epochs): print('training on', ctx) loss = gloss.SoftmaxCrossEntropyLoss() for epoch in range(num_epochs): train_l_sum, train_acc_sum, n, start = 0.0, 0.0, 0, time.time() for X, y in train_iter: X, y = X.as_in_context(ctx), y.as_in_context(ctx) with autograd.record(): y_hat = net(X) l = loss(y_hat, y).sum() l.backward() trainer.step(batch_size) y = y.astype('float32') train_l_sum += l.asscalar() train_acc_sum += (y_hat.argmax(axis=1) == y).sum().asscalar() n += y.size test_acc = evaluate_accuracy(test_iter, net, ctx) print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f, ' 'time %.1f sec' % (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc, time.time() - start))
We initialize the model parameters on the device indicated by
ctx,
this time using the Xavier initializer.189, train acc 0.103, test acc 0.100, time 1.9 sec epoch 2, loss 2.1493, train acc 0.169, test acc 0.517, time 1.8 sec epoch 3, loss 1.0270, train acc 0.586, test acc 0.671, time 1.7 sec epoch 4, loss 0.7867, train acc 0.689, test acc 0.739, time 1.7 sec epoch 5, loss 0.6699, train acc 0.738, test acc 0.764, time 1.7 sec).
6.6.5. References¶
[1] LeCun, Y., Bottou, L., Bengio, Y., & Haffner, P. (1998). Gradient-based learning applied to document recognition. Proceedings of the IEEE, 86(11), 2278-2324. | http://d2l.ai/chapter_convolutional-neural-networks/lenet.html | CC-MAIN-2019-18 | refinedweb | 810 | 61.83 |
This video is only available to subscribers. Start a subscription today to get access to this and 422 other videos.
Scripting in Swift with Marathon - Part 1
Thanks to John Sundell for joining me on this episode!
Episode Links
- Swift by Sundell - John's excellent blog on Swift
- GitHub - JohnSundell/Marathon: Marathon makes it easy to write, run and manage your Swift scripts 🏃
- Mint · GitHub - A utility for installing Swift packages
- JohnSundell/Files · GitHub - A Swift package for working with the file system
- JohnSundell/ShellOut· GitHub - Easily run shell commands from a Swift script or command line tool
Installing Marathon
I followed the recommended instructions, which involves installing Mint first (😂):
$ brew install mint
Now that Mint is installed, use it to install Marathon:
$ mint run JohnSundell/Marathon
Writing Your first script
$ marathon create AddMigration
This creates an Xcode project in Marathon's support folder, creates the Swift package structure and links in the swift file for us to edit.
Any time we want to edit this file, we have to do so using Marathon:
$ marathon edit AddMigration
Reading Command Line Arguments
One of the first things we have to do is read command line arguments. Luckily, Foundation already has us covered there:
import Foundation print(CommandLine.arguments)
This will print out a single argument, which is the full path to the script being run.
If you want to provide some arguments when debugging in Xcode, you can do so by editing the Xcode scheme.
Running Marathon Scripts
Running the scripts also is done via Marathon:
$ marathon run AddMigration <your> <arguments>
Working with Files
We want to work with the filesystem in this example, so we'll pull in John's library for this, helpfully called "Files". We'll need to tell Marathon keep track of the dependencies that we might want to use. We can do this in multiple ways.
The first way is to add the package as a known dependency with Marathon:
$ marathon add
(Later when we want to update Marathon's copy of this, we can run
marathon update ...)
This adds a cached copy of the dependency in Marathon's support folder, so we can now just import it in our script:
import Foundation import Files let folder = Folder.current print("Your running from \(folder.name)")
If you run this with Xcode, the output will look something like this:
You're running from Debug Program ended with exit code: 0
The folder name is just the single name, if you want the full path, you can use
folder.path:
You're running from /Users/ben/Library/Developer/Xcode/DerivedData/example-ccknwhxumzpmtsgmrdeepmzbsfnf/Build/Products/Debug/ Program ended with exit code: 0
To create or retrieve a folder, you can use methods on the
Folder type:
let folder = Folder.current let subfolder = try folder.createSubfolderIfNeeded(withName: "MySubfolder")
This would create the folder if it didn't exist already
Exiting from scripts with errors
See how Xcode noted that the program ended with exit code 0? This is a Unix convention. "0" means successful, anything non-zero is an error. You can use this to communicate error codes, but it is also useful for chaining together commands:
first_run_this && then_run_that
If the first command returns a non-zero exit code, then the 2nd script will not run.
We want to honor the Unix convention of returning a non-zero value if we encounter an error.
if CommandLine.arguments.count < 2 { print("Usage: marathon run myScript <arg>") exit(1) }
If we try to run this script and don't provide an argument, then the
CommandLine.arguments array will only contain 1 value: the path to the script. We then print out a helpful message and exit with the value "1", indicating an error. | https://nsscreencast.com/episodes/368-marathon-part-1 | CC-MAIN-2020-05 | refinedweb | 621 | 56.39 |
JustLinux Forums
>
Community Help: Check the Help Files, then come here to ask!
>
Software
> Xine?
PDA
Click to See Complete Forum and Search -->
:
Xine?
JayeDVXIII
08-18-2002, 08:36 PM
I have RedHat 7.3 and I would like to use Xine but I have trouble trying to get it to play DVDs.
I've asked this question before but always seem to get a really vague response.
From what I can determine, the player is looking for a dvd input of /dev/dvd
There is no such file on my machine, so my question is how do I create this file so that Xine will see my dvd drive and the inserted dvd and play it correctly?
Btw..I tried Ogle but it always locks up and doesn't work.
And if anyone is going to mention a Simlink..please give instructions as to how to do that.
thanks
saithan
08-18-2002, 11:59 PM
for xine there is an easy way to solve that problem.
look in /home/username/.xine/config
and find where is says:
# path to your local dvd device file
# string, default: /dev/dvd
input.dvd_device:/dev/dvd
change it to point to /dev/cdrom
or open xine and in the setup menus you can also set this variable ( remember to close and restart xine after changing settings).
another fix for other programs that might not have such flexability, create a symlink in /dev named dvd point this symlink to the /dev/cdrom.
The method to create a symlink of this type can be found in the xine howtos.
the default xine that comes with RH7.3 will not play all dvds (encrypted). but there are versions and files that are available to solve this issue.
libdvdread
libdvdcss
libcss
and you will want the xine nav packages for reading the dvd menus.
hope this points you in the direction you were looking for.
mdwatts
08-19-2002, 06:14 AM
ln -s /dev/cdrom /dev/dvd
See if that helps.
JayeDVXIII
08-19-2002, 11:15 AM
thank you
it appears now that when i click "DVD" ..Xine sees my dvd drive and begins to load some weird vob file.
However, I am trying to play the lord of the rings..and I know that yesterday I downloaded all the newest dvd read libs from freshrpms...including css and dvdread..etc
I dont see a picture and the video doesn't apear to play..nor will the program eject the current medium. :-( Even when oipening KDISKfree..and unmounting this device..it wont eject unless i close xine
I know this program works because I remember it worked in Mandrake when I had tried that distro..but in red hat it's been nothing but a pain..any help is appreciated
personal thanks to mdwatts for being so supportive :-)
__________________
"...live people often ignore the strange and unusual..I myself am...strange and unusual..."
JayeDVXIII
08-19-2002, 11:19 AM
I have tried other movies and I'm getting the same problem
When I actually hit play i get a "there is not available input plugin to handle ..." (the path to the first vob file on my dvd)
what am i doing wrong? :-(
mdwatts
08-19-2002, 05:43.
JayeDVXIII
08-20-2002, 02:51 PM
okay please bear with me..i'm trying to follow these directions but am running into a lot of problems
the error return (when running xine from the konsole) that i get is some message about how xine doens't play encrytped dvds.
I have already installed libdvdread, libdvdcss...I was unable to find d5d or d4d and not sure why I or how I would have needed to edit a file called ld.so.config
i'm really confused..also I dont understand why the xine that came with mandrake worked perfectly but the one i downloaded to work with red-hat is so difficult to use
JayeDVXIII
08-22-2002, 08:15.
Could u please explain that a bit further? I went ot freshrpms and downloaded libdvdread and libdvdcss but did not find d4d or d5d (not even sure what that is) Could you also explain what is "ldconfig"...when I try to run this file from a root konsole prompt..I get command not found.
THanks
justlinux.com | http://justlinux.com/forum/archive/index.php/t-60437.html | crawl-003 | refinedweb | 724 | 74.79 |
The question at hand was in the context of an accumulator passing tail recursive implementation of factorial. Which is better: to use an optional private parameter in a public function or to use a "named" let, and introduce the accumulator there?
I am with Patrick (I think) who seems to prefer the nested let. It seems to me that this is also what Richard Gabriel prefers.
My reasons? First, by exposing the optional parameter you are implying it is part of the interface available to outside clients. I don't think this is the correct semantic interpretation in this case, so it is misleasing. Essentially, what you want is a helper function (fact-iter), and fusing it with the public function seems like a hack. Sexy but confusing...
Second, scope is one of the most important clues when reading code. Scoping techniques make code more readable, both for humans and for language processing tools. Provided, that is, that you pay attention to them when you are writing as well as when you are reading code.
And yes, Patrick, I think that it is idiomatic Scheme.
Posted to general by Ehud Lamm on 1/25/04; 12:30:41 PM
(defun fact (n)
(if (= n 0)
1
(* n (fact (1- n)))))
(if test then &rest else)
This should help:
(add-hook 'lisp-mode-hook
(defun my-lisp-mode-hook ()
(set (make-local-variable 'lisp-indent-function)
'common-lisp-indent-function)))
Sincerely,
Your friendly .emacs pedant. :-)
.emacs
A point well taken.
=
<=
It seems there are three choices for negative inputs: loop forever, return nonsense, or give an error. What are the idioms for different languages?
2. What did I write? I prefer neither Brian's nor Richard's style. If I were using Common Lisp again I would still use a named let.
3. Non-tail recursive example - yes, simpler, but the style argument was about how to express the accumulator.
(How you hide the accumulator is another question. Named let? Letrec? Internal define? Local? Helper function? Helper function hidden in a module (assuming your Scheme implementation has a module system)? But this is probably getting really petty.)
A similar example: a (not whole-program) CPS transformation. In the simple case, where the transformation is completely local, you should hide the "start continuation" (usually λx.x). But if you have a bunch of combinators that are all in CPS, you keep the continuation in the interface to give the user the ability to plug in different continuations. And then... you can introduce *another* layer of information hiding, if you want the combinators to work together but without making the accumulator visible to the "top-level." For this, you wrap them in an abstract data type that allows you to combine them, so their continuations are exposed to each other, but not to the user.
λx.x
Keep in mind that trying this with first year students is a bit like teaching 'literary criticism' to first graders just learning the alphabet...
(defmethod fact1 ((n (eql 1)) &optional (acc 1))
acc)
)))
[fact2 is from the original posting. The point here is that its formatting is different.]
I like fact1 and fact4 for different reasons. fact1 shows how cool CLOS is and fact4 describes best what's happening IMHO.
I find the example strange. How often do you write functions in a value accumulating style, or transform functions to tail-recursive style? What's wrong with iteration?
If this is a course that treats programming as an art form, it shouldn't teach the "one" "correct" style. This doesn't make sense in the arts.
(defun fact(n &optional (so-far 1))
(if (<= n 1)
so-far
(fact (- n 1) (* n so-far)))
fact
if
so-far
assert
check-type
(- n 1)
(1- n)
In summary, between careful consideration and my own personal tastes, I think the function should have been written exactly like this:
(defun factorial (n)
"Return N!"
(check-type n (integer 0 *))
(if (zerop n)
1
(* n (factorial (1- n)))))
(I added the documentation string and renamed from fact to factorial while convincing myself to put HTML-emphesis on "exactly". Open-source is good for software engineering :-))
factorial
That's what I reckon!
Too much nitpicking? Want revenge? Here's a favourite function of
mine, in production use for many years:
make_set([]) -> [];
make_set([H|T]) -> [H | [X || X <- make_set(T), X /= H]]. % no comment
make_set([]) -> [];
make_set([H|T]) -> [H | [X || X <- make_set(T), X /= H]]. % no comment
I wonder why not (switching to Haskell, as I don't know what language this is in - guessing ML?):
make_set [] = []
make_set (x:xs) = x : filter (\p -> p /= x) (make_set xs)
- in other words, why is the list comprehension better than a filter?
make_set [] = []
make_set (x:xs) = x : [p | p <- make_set xs, p /= x]
make_set [] = []
make_set (x:xs) = x : filter (p -> p /= x) (make_set xs)
make_set [] = []
make_set (x:xs) = x : (do p <- make_set xs
guard (p /= x)
return p)
It is Erlang.
Doh! Of course it is...
List comprehensions are preferred in Python also - filter is frowned on, if not actually deprecated. So in Python you might say:
>>> def make_set(n):
... if n == []:
... return []
... else:
... return n[:1] + [p for p in make_set(n[1:]) if p != n[0]]
I think it's Erlang.
Regarding the accumulator argument: After some consideration, I don't see why one should regard this (as Dave suggests, and Ehud in the topic header) as an interface issue. In fact, besides namespace clutter, I don't see what's wrong with lifting the helper function to the top-level. It doesn't expose any implementation issues, since there is no guarantee that the factorial function uses it. (Of course, in LISP this could cause problems because you could change the behavior by rebinding the helper function; but then, LISP is LISP, not a `normal' language. ;)
Indeed, it's pretty useful to have the helper function available in cases like this. Let me give you an example where it's clearer, free monoid normalization.
data Mon a = Nil | Mon a :+: Mon a | Elem a
norm :: Mon a -> Mon a
norm m = reduce m Nil
reduce :: Mon a -> Mon a -> Mon a
reduce Nil = id
reduce (m :+: m') = reduce m . reduce m'
reduce (Elem x) = (Elem x :+:)
norm :: Mon a -> Mon a
norm m = reduce m Nil
reduce :: Mon a -> Mon a -> Mon a
reduce Nil = id
reduce (m :+: m') = reduce m . reduce m'
reduce (Elem x) = (Elem x :+:)
Now, suppose I have an arbitrary value m :: Mon a, and another value n :: Mon a which I happen to know is in normal form, and I want to know the normal form of m :+: n. Either I can do:
m :: Mon a
n :: Mon a
m :+: n
norm (m :+: n)
m
n
reduce m n
make_set = foldr (\x -> (x:) . filter (/= x)) []
(I'd write it a little less tersely if it weren't for the Haskell show-off factor here...)
(Elem x) = (x:) gives a type error ([a] where we want Mon a), as does (Elem x) = ((Elem x):) ([Mon a]).
The problem is that the type of (:) is a -> [a] -> [a]. I think we need something with type Mon a -> Mon a -> Mon a instead?
(Edited to remove nonsensical use of word "monoid").
Nice - but to my eyes the least readable so far. That's probably because my eyes aren't adjusted to this particular style, however - I had to squint at Frank's example for the same reason. I end up translating it in my head into something like:
make_set :: Eq a => [a] -> [a]
make_set = foldr (\x xs -> x : (filter (\p -> p /= x) xs)) []
adjoin :: Eq a => a -> [a] -> [a]
adjoin x = (x:) . filter (/= x)
make_set :: Eq a => [a] -> [a]
make_set = foldr adjoin []
make_set :: Eq a => [a] -> [a]
make_set = foldr adjoin []
which brings us back to the utility of exposing helper functions...
That's a good point. Although namespace clutter is not unimportant, it's orthogonal to the issue of information hiding, and more a question of whether the helper function is of any general utility. If the helper function is useful, as in your example, I agree that it makes sense to expose it. That's what I dislike about nested helpers such as internal define. I prefer having a module system where you can hide and unhide helper functions easily without too much cutting and pasting.
But I still think this is an interface issue: even in your example, you provide a top-level function that provides an initial value for the accumulator, for the obvious reasons that a) the caller shouldn't be required to provide the same value each time, and b) the correctness of the implementation of norm shouldn't rely on the caller providing it.
norm
(Of course, in LISP this could cause problems because you could change the behavior by rebinding the helper function; but then, LISP is LISP, not a `normal' language. ;)
Are you referring to dynamic scope or set{f,!}?
set{f,!}
Sorry, it should be (Elem x :+:) on the RHS. I've fixed the code.
(Elem x :+:)
Are you referring to dynamic scope or set{f,!}?
I'm not familiar with the details of LISP, but I'm referring to the fact that top-level variables are bound late, so presumably setf or defun. For example, in Scheme you can change the result of f [typo fixed] by rebinding g using set! or define:
f
g
set!
define
(define (f x) (g x))
(define (g x) 0)
(f 9) ; => 0
(define (g x) 1)
(f 9) ; => 1
(set! g (lambda (x) 2))
(f 9) ; => 2
So if factorial depends on a helper function, then rebinding the helper will change the behavior of factorial, unless you are careful and use an idiom like:
(define fachelp ...)
(define factorial
(let ((fach fachelp))
(lambda (n) ... fach ...)))
How about a variant that preserves the order of the input elements (retaining the first of each occurence) and runs in O(n log n) time or better?
Here's one in Common Lisp:
(defun without-duplicates (list)
"Return a copy of LIST with repeated occurences of elements removed."
(loop for e in list
with table = (make-hash-table)
unless (gethash e table) collect (setf (gethash e table) e)))
P.S. Frank: I think Schemers regard that problem the same way Haskell guys would regard someone changing a subfunction and recompiling/running the program. i.e. it's bad to change the semantics of a helper function without updating its callers, whether done dynamically or statically.
I thought that you didn't like threads...
(I agree with the sentiment, btw)
without-duplicates
BTW, the function make_set is in the standard library module List, where it's called nub.
make_set
nub
(defun without-duplicates2 (list)
(let ((table (make-hash-table)))
(flet ((there!? (x)
(prog1 (gethash x table) (setf (gethash x table) t))))
(remove-if #'there!? list))))
There's a mailing list I started a while back for code discussions like this, though it's gotten no traffic and almost no subscribers. I should probably have started it off with something like Richard Gabriel's annotations instead of just plopping down some code to criticize.
(without-duplicates)
loop
;; very functional
(defun without-duplicates1 (list)
(reduce (lambda (acc elm)
(adjoin elm acc))
list :initial-value nil))
;;)))
Question: Why the hash table? Isn't this premature optimization? For short lists, the overhead of creating a hash table is probably too large, and for long lists its probably better to keep them pruned from the start, right?
The specification of running-time may be overly specific. However, since I have needed such a function in real life I thought it would add some spice. Note that without this stipulation the many make_set implementations already posted already do the job, since they incidentally preserve the order of the input list (but in O(n^2) time).? :-)
BTW, for an "old fashioned" (or at least very specifically tuned) implementation of without-duplicates, see CMUCL's definition of the fancier standard Lisp function remove-duplicates. This function appears (judging by source code comments) to have been written around 1984. (CMUCL's CVS is temporarily down so I can't date it more reliably with cvs annotate.)
remove-duplicates
cvs annotate
Sorry, I haven't payed enough attention to this.? :-)
My only reasoning was that a hash table adds an overhead for which you don't necessarily know if it pays off in the end. If I were a nitpicker I could ask where your requirement stems from and why you are sure that you really need O(n log n), but I am not. ;)
A good data structure for keeping both the O(n log n) requirement and the elements pruned from the start should be a red-black tree. For example, see and - however, I am not 100% sure.
Off hand I can't think of a way to implement this well using trees, because they usually want to change the ordering for balancing. Can anyone think of a nice way to write a data structure
such that one can incrementally insert n elements (m of which are
unique) and then produce a list of unique elements in the same order
they were inserted -- all in O(n log n) time and O(m log m) space or
better? I have some ideas but nothing that I would call nice. In the back of my mind I suspect that Scheme or SML/NJ hackers could do something delightful..
(I don't know red-black trees by heart so I may be missing something obvious. Long ago Darius Bacon pointed me to a beautiful way of writing purely-functional trees and I've always done it that way so far in this life.)
The link to the Common Lisp library above provides actual source code.
they do? the "left-to-right" order of the leaf nodes reflects key order (in this case you have key=insertion order, presumably). but how is insertion order stored separately (if it's not equal to the key? or is that what you meant?)
for code, see the bible
people seem to be neither posting replies to individual posts nor quoting context, so i have no idea what reply is associated with what comment.
if this reference to cormen at al is about red/black trees storing insertion order then ok, i will check it out when i get back home (where my copy is). but i already know how they work - i've written code myself - - and they rearrange the branching of nodes to maintain the colour property. the insertion order is not preserved (and it makes no sense to do so - the whole point of rebalancing is to remove the pattern that insertion ordering imposes. a balanced tree is exactly one where the insertion order is not preserved - it should be balanced whatever the order of insertion was).
you can see this in the code above, if you look at the balance function. the ordering of a, b, c, d remains unchanged (ie key ordering is preserved), but the relative nesting of the types (ie the branching structure) varies (and the insertion ordering is not stored directly (the nodes contain only keys and subtrees)).
more generally, consider a balancing alogithm that guarantees minimum branch length. three keys, A B and C will always be stored with nodes A and C below B (assuming lexical ordering) no matter what the insertion order. red-black trees have a slightly weaker guarantee (the number of one color - is it red? - down any branch is a minimum), but the same argument can be applied to sufficiently large trees.
i try to be careful about making absolute statements, because i have been wrong too many times, but i am pretty sure that insertion ordering is not preserved by red black trees (or any other balanced tree, unless it is explicitly stored, given the arguments above).
A counting argument shows why any binary tree data structure (including red-black trees) can't maintain both insertion and key orderings without auxiliary information.
The information content of a key-ordered binary tree comes from:
1) the set of values in the tree
2) the shape of the tree
3) extra per-node bits (e.g. the 'red' bit in red-black trees)
Since the user controls the set of values, the only place the insertion order can be maintained is in the shape of the tree and the extra bookkeeping bits. (I'm assuming here that the data structure isn't allowed to be padded with extra nodes.)
The number of binary tree shapes with n internal nodes (ie the nth Catalan number) is strictly less than 4^n. Let's assume that there are a fixed number B of extra bits allowed per node. Then there are less than (4*2^B)^n different instances of the binary tree data structure (much less given balance constraints). There are n! insertion orders, which can be made to exceed (4*2^B)^n by choosing n sufficiently large.
In conclusion, any key-ordered binary tree data structure with a fixed number of per-node extra bits cannot maintain insertion order for an arbitrary number of nodes.
I'm sure the implementation cited just adds some extra pointers to maintain insertion order (alhough neither CLR nor C++ STL do) so it's kind of a pointless argument -- but it was fun to run the numbers.
(defun add-vectors (&rest vectors)
(apply #'mapcar #'+ vectors))
? (add-vectors '(1 2 3) '(4 5 6))
(5 7 9)
? (add-vectors '(1 2 3) '(4 5 6) '(7 8 9))
(12 15 18)
? (add-vectors '(1 2 3) '(4 5 6))
(5 7 9)
? (add-vectors '(1 2 3) '(4 5 6) '(7 8 9))
(12 15 18)
Pascal | http://lambda-the-ultimate.org/classic/message10848.html | CC-MAIN-2017-30 | refinedweb | 2,974 | 69.52 |
Revision history for Perl extension RPM. 1.51 Tue Apr 24 18:45:49 PDT 2007 Changes made by Alexey to setting of $VERSION in RPM::* classes didn't play well with CPAN. Since I'm moving the repo to subversion soon anyway, changed these to ordinary strings. 1.50 Tue Apr 24 17:42:49 PDT 2007 This is an official release to make the work done by Alexey Tourbin (<at@altlinux.org>) available in the main branch. All of his changes are merged into the main repository. Without his work, the project would still be languishing. Beside fixing countless bugs, he got me back to actively looking at the code. Added LICENSE paramter in Makefile.PL to re-license the package under the same terms as Perl itself (dual Artistic/GPL). RPM.pm version bumped up to 1.50 for release tracking. Test suites added to t/ for POD correctness and POD coverage. Several new additions to POD as deficiencies found by the POD coverage testing. 1.49_01 Sun Apr 22 2007. 0.40 Fri May 10 01:09:13 PDT 2002 . 0.32 Tue May 15 00:54:20 PDT 2001 - alpha twelve Found and fixed a bug in RPM/Database.xs that was causing more of the "Attempt to free unreferenced scalar" messages. In the process, noticed that caching of values during iteration wasn't actually working as designed. The resulting fix should improve database look-ups fairly noticably. Two more places found (one in RPM/Header.xs, one in RPM/Database.xs) that were contributing to memory leakage. A lot of changes to RPM/Constants.xs in terms of reducing the number and length of string-compares made in constant look-ups. This is most noticable in the RPM* set of constants, where the breakdown is the most granular. On the main dev box (a P-1/233MHz) this sped up the full test suite by over 25%. 0.31 Fri Apr 27 01:45:37 PDT 2001 - alpha eleven Re-worked most of RPM/Constants.xs to accomodate the change from #define to enum values in 4.0.2. This will be released as an interim version, since Red Hat is shipping 7.1 with this version of rpm. 0.30 Wed Mar 7 22:13:40 PST 2001 - tenth alpha Much of the leakage of RPM::Header objects is now gone, due mostly to changing the prototype of rpmdb_FETCH to returning a SV* instead of a RPM::Header reference. The various class DESTROY methods seem to be getting called in the correct order, now. Caught a case in the RPM::Header class where attempting to reference an element of a non-existent tag would trigger auto-vivification on that key, which in turn was leading to some bad calls being made to the rpmlib routines. Re-did the av-assignment in rpmhdr_create. This should save on SV* creation, though it might not have been a leak. Still, this method is more efficient overall. Newer versions of rpm 4.0 tickled a bug in which a database offset value might get sent in without being initialized first. This was caught and fixed. Also related to the 3.0/4.0 rift, some variables only used for 3.0.X are now declared within #ifdef's to defeat 'unused' warnings. The current state of the module will be released to allow for use by other parties, without the wait for any ongoing development milestones on my part. 0.292 Mon Nov 13 22:40:15 PST 2000 -. 0.291 Fri Oct 13 01:45:18 PDT 2000 - eighth alpha The flags that are created from the rpm version are now passed for 3.0.X, as well. A thread-safing bug was found and fixed in Header.xs. An unused variable was removed. Makefile.PL has some large-scale work, including the addition of a template spec file following the __DATA__ token, code to expand this file using the values that MakeMaker has derived for the package, generation of make rules to construct *.rpm and *.srpm files, and generation of "rpmrc" and "rpmmacro" files to use in invoking rpm (to force all operation into the local dir area). 0.29 Wed Oct 4 22:29:56 PDT 2000 -. 0.28 Fri Aug 18 01:29:35 PDT 2000 - sixth alpha Considerable additions made to the documentation in RPM::Constants, as well as a few corrections. The prototype of the constant() function was changed, as well. Several bugs were addressed in RPM::Header, most notably: Error returns now correctly return a value of "undef"; A blocking issue surrounding multiple RPM::Header objects from ftp:// sources is fixed; the mode with which files are opened was also changed to allow for reading off of STDIN. The error-return issue was also applied to RPM::Database. RPM::Header now has a source_name() accessor method that returns the file name (or URI) that the header was read from. This is null if the header came from the database. 0.27 Tue Aug 8 00:02:22 PDT 2000 - fifth alpha Added filenames() method to RPM::Header. This re-assembles the list of filenames from the components in the tags, BASENAMES, DIRNAMES and DIRINDEXES. Added scalar_tag() method to RPM::Header. This returns a 0/1 value based on whether the return value for a given flag is an array ref or scalar (respectively). Can be called with either a string or a number argument. Can be called as a static (class) method. Added RPM/Error.xs and integrated into the build. All the XS code for RPM::Error that was previously in RPM.xs has been moved here. Added export of %RPM to RPM::Database. If requested, this is a hash pre-tied to the RPM::Database package (and thus the rpm database). One may also request $RPM and get an object referencing a tied hash. The return values from fetches on header objects has been completely revised. Tags are now explicitly defined as scalar or list in nature. The scalar_tag() method above is a part of this. The return value from a scalar tag is now a plain scalar. There is no more need for $_->[0] on scalar returns. Lists are still returned as list references, and undef is still used to signify problems. Tests have been added to t/02_headers.t for this, and tests in t/01_database.t were updated to use the new syntax. This does not obsolete the RPM::Header::NVR method, as that is a much faster means of fetching those three items than a stock fetch of the three individual tags would be. More tags/values documented in RPM::Constants. 0.26 Fri Jul 14 01:03:02 PDT 2000 - fourth alpha Added NVR() method to RPM::Header for obvious reasons of convenience. Also added cmpver method, which calls into the rpmCompareVersion() API hook to compare two headers' version/release data with an internal algorithm that handles numerical and alpha content in the tags. Took out all remaining warn()'s and croak()'s, replacing them with rpm_error() calls. Most notable in the error-return cases of RPM::Database::init and ::rebuild. More thread-safing, in particular the heretofore-ignored RPM::Constants XS module. Added a sample script in utils, called rpmprune. It has a --help summary and a man page, see those for details. 0.25 Mon Jun 5 00:54:59 PDT 2000 - third alpha Fixes to the thread-safing code. When built against a 5.6.0 configured for threading, several problems were found. All (current) tests now pass on that configuration. Added a file, IMPORTANT.perl, to the distribution that explains the nature of a condition that can prevent the extension from working on any version of Perl not installed from an rpm. Still more trimming of tokens out of Constants.pm that are not of use by the interface being provided. Filled in a few more in terms of documentation. Found a case in RPM::Header that would cause core-dumps: Any tags found by the iterator that were not exported for the API by the rpm lib could cause a null pointer to be passed through to an entry point that was several lines past where I had normally checked for the null. This meant that source RPMs would almost certainly break, since the offending tags only showed up when I started testing against SRPMS. Now, the iterators skip over these internal tags. The normal FETCH method already tested for this, but the interators were sneaking past those tests. Added a method to the RPM::Header class, is_source(), that returns a true value (1) if the header is associated with a source RPM. 0.2 Mon May 29 17:59:20 PDT 2000 - second alpha Class for RPM::Error added. The code is in the RPM.xs file, but the docs and accessors are done in RPM/Error.pm. All sub-classes moved to RPM/. More documentation added, especially to RPM::Constants. RPM::Constants had about a dozen or so trimmed out. Found error in Database.xs where the FIRSTKEY/NEXTKEY pair would have returned string-ified references instead of package names, because of not taking the first array element. I really plan to change the RPM::Header::FETCH interface. Added two utility functions under the RPM::* space for getting O/S and architecture names. Put in the start of thread-safing the module. But this part of the API is still pretty black in the Lockheed Skunkworks sense of the word, so it isn't at all complete. 0.1 Mon May 22 00:59:54 PDT 2000 - first alpha release Classes for RPM::Header and RPM::Database are (more or less) done. RPM::Constants appears to have everything that is expected to be needed (i.e., any changes should result in shortening the list of exported symbols, rather than lengthening it). A basic top-level RPM namespace is present, but doesn't yet do anything useful. Some basic test scripts are in place, but more are (always) needed. 0.01 Thu May 4 12:04:34 2000 - original version; created by h2xs 1.19 | https://metacpan.org/changes/distribution/Perl-RPM | CC-MAIN-2015-32 | refinedweb | 1,699 | 75.4 |
Sheila King <usenet at thinkspot.net> wrote: > Yes, very good idea. I actually decided to reject all preferences after > trying them out. Reason: I might actually have to read someone's code with > that nonsense in it some day. :((( Nonsense is nonsense is nonsense. Was this your vote? :) Q accept c and x or y Q accept (c and [x] or [y])[0] Q accept (lambda: x, lambda: y)[not c]() Sheila King x = "door" + (quantity>1 and "s" or "") data = (hasattr(s, 'open') and s.readlines() or s.split()) z = 1.0 + (abs(z) < .0001 and 0 or z) t = v[index] = (t<=0 and t-1.0 or -sigma /(t + 1.0)) return (len(s)<10 and linsort(s) or qsort(s)) -- Tabby | https://mail.python.org/pipermail/python-list/2003-March/181054.html | CC-MAIN-2017-30 | refinedweb | 125 | 87.92 |
imp.find_module don't found my module but standard import statement can import this module… why ?
Discussion in 'Python' started by Stéphane Klein, Jul 5, 2011.
Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
- Similar Threads
Plugin system; imp module head scratchDave, Dec 19, 2004, in forum: Python
- Replies:
- 2
- Views:
- 314
- Nick Coghlan
- Dec 19, 2004
findcontrol("PlaceHolderPrice") why why why why why why why why why why whyMr. SweatyFinger, Dec 2, 2006, in forum: ASP .Net
- Replies:
- 2
- Views:
- 2,071
- Smokey Grindel
- Dec 2, 2006
import vs imp and friends.Emanuele D'Arrigo, Jul 23, 2009, in forum: Python
- Replies:
- 2
- Views:
- 261
- Emanuele D'Arrigo
- Jul 24, 2009
Why 'import module' will not import module.py but the directorymodule?Peng Yu, Oct 31, 2009, in forum: Python
- Replies:
- 0
- Views:
- 332
- Peng Yu
- Oct 31, 2009
Re: Fail import with SWIG generated imp.load_module ?MRAB, Dec 14, 2010, in forum: Python
- Replies:
- 0
- Views:
- 421
- MRAB
- Dec 14, 2010 | http://www.thecodingforums.com/threads/imp-find_module-dont-found-my-module-but-standard-import-statement-can-import-this-module%E2%80%A6-why.750915/ | CC-MAIN-2014-42 | refinedweb | 199 | 81.02 |
The three golden rules of interactive display design.
I’ve been the CEO of Lumo Interactive, a company that specializes in interactive digital display software, for over 6 years. In that time, we’ve deployed over 15,000 software licenses, and helped design tens of thousands of interactive displays, from motion reactive floors and walls, to gesture tracking games, to touchscreen and holographic displays of every shape and size.
In that time, I’ve learned a lot about what works (and doesn’t work) when designing a display that hundreds or thousands of people are going to engage with.. If you’re planning an event or campaign, and you’re planning to incorporate a motion, gesture, or touch reactive digital experience, these rules will help you get the most out of your investment.
Rule 1: Write the ending first.
An interactive display can be a useful way to engage an audience. It can also be a complete waste of money, space, and time if you don’t know what you want the audience to take away from your installation when it’s over. Your goals will help determine the end product, so it’s important to understand exactly what you want to achieve. Here are some of the reasons digital displays are used in an activations, and how they can inform design decisions.
You want to teach people something.
Research shows that one of the most effective ways to share and retain information is through an interactive experience. This is something that e-Learning platforms have understood for a while. Even outside the digital world, interactivity is on the rise in the classroom, from kindergarten to Harvard. Even large companies are getting the message — training new staff has always been a challenge, and linear videos and booklets just don’t have the same appeal as a personal, tangible interaction with the content.
When education is your primary goal, your design should focus on ease of use, which includes reducing the learning curve and evaluating success once information has been shared. This means you’ll need to eliminate surprises as much as possible, by creating something comfortable with familiar interaction metaphors, and incentivizing the interaction in a meaningful way.
The Heart Lounge table by digital design company Aarra is a nice example of an accessible way to learn about the components of blood, including what each cell is responsible for. By manipulating each component, users can learn about their functions in a variety of ways. This helps people learn by physically exploring, which leads to better information recall.
You want to create a meaningful connection between the audience and your message or brand.
In this case, the takeaway is a feeling. You want your installation to have an emotional impact on the audience. There are any number of ways to do this with a digital display, but there are important design considerations when the main point of your project is to trigger an emotion.
You need to consider context, both in terms of the physical structure of the display, and in terms of the location. A wonderful example of this is the Pathways to Housing campaign by Sarkissian Mason, which demonstrated the impact average people could have on homelessness simply by not ignoring it.
The installation targeted average New Yorkers who walk by, and probably ignore, the growing homeless population on a daily basis. To raise awareness, this campaign took place right on the streets of New York, and featured a life sized projection of a homeless individual, offering curious passers by a chance to help by engaging via SMS.
You want to spread the word.
If your goal is shareability, your design should involve elements of surprise, entertainment, and novelty. Remember that when someone shares something, it’s a reflection of themselves — your interactive display should be interesting, clever, or delightful enough to motivate the audience to share it because it will reflect well on them, personally.
A really good rule of thumb when it comes to shareability is that the more fun it is to watch other people engage with the installation, the more sharing it will get. Consider this augmented reality experience sponsored by National Geographic. Since all the action takes place on a big screen, the number of people able to see and share the installation is huge, even though the number of people actually engaging at any given time is relatively small.
Rule 2: Add a shiny red button.
This rule is obvious, but difficult to follow. If you think of your display as a really amazing person everyone wants to meet, you need to identify the feature that makes that person so attractive… are they funny? Do they make you feel smarter? Do you feel cooler for having spent time with them?
In the case of an interactive display, you need to make sure there’s a clear reward for engaging. In some cases, this is obvious (at a way-finding kiosk, for example). But in many cases the reward is not as clear. Generally speaking, the more engaging the display, the more the reward has to outweigh the level of discomfort many people feel while using a new technology in a public place.
The shiny red button is an analogy for whatever it is about your installation that draws the audience and retains them so that they can have a personal experience.
Often, the easiest way to do this is to add a new level of engagement to a button that people press without thinking every single day. In the example below, this is a literal button, created by design team Urban Invention.
The point of this installation is to encourage people to wait until it’s safe before crossing the street. The experience rewards people who engage with a game of pong against someone waiting across the street, occupying dwell time and decreasing impatience.
Below is a similar project, created by BBDO Berlin for Smart. On the surface, the goal seems the same, but in this case the shiny red button is unexpected amusement for the audience waiting, and a chance to actively engage in a different, nearby location.
Even though both displays seem to have the same end goal, (make people wait before crossing the street), this isn’t actually the case. In the first installation, a single person plays a game against someone waiting across the street. This experience may be watched (and may entertain) people standing very nearby, and it may even be shareable (the original test generated around 5 million views).
The second installation, however, was a lot more viral, led to several marketing awards, and offered two completely different levels of engagement. It’s also worth noting that the second installation differs from the first because it was designed to be a temporary experience in an event setting, and the goal was to generate ad collateral, rather than provide an actual, somewhat practical way to encourage people to wait at crosswalks.
Different desired outcomes informed the way these displays were designed.
This just goes to show that the perceived intention of an installation is not always the actual motivation. This why it’s so important to really understand what you want at the end before you add your shiny red button.
Rule 3: Remember all the humans.
I’m a huge proponent of accessibility, but that’s not what this rule is about. When you go through the time and trouble to create an interactive digital experience, engaging your immediate audience should be your primary goal, but it should never be your only goal. This is because humans get bored. Fast. This means that in order to extend the shelf life and value of your installation, you need to either attract new humans or build an experience that lives on long after the original concept is executed and packed away.
One way to achieve this is to do something no one’s ever seen before. Consider the LG Halloween prank video, which was done once, totally staged, and caused so many people to upload and share it that I can’t find the original video.
This rule applies to any interactive display you want people to continue to use and/or talk about. Way-finding kiosks may seem like something you wouldn’t need to update often, since people in an airport or mall will always want to use them to find their way. But eventually your original audience will know where they’re going. Turning the kiosk from a tool into an experience may become really important. However, doing this in a meaningful way is more challenging when the display is meant to be practical rather than entertaining.
Creating a reason to return (or a reason for new humans to show up) can be as simple as customizing the experience each time. Imagine a way-finding kiosk that creates a personalized augmented experience people can take with them when they leave.
Customization is the key to designing interactive displays that offer brand new experiences for participants, without reinventing the wheel for each project. This is an exciting time to be in the field of digital display design. Today’s technology lets you choose from an almost unlimited number of ways to engage with content. Artificial intelligence and deep learning continues to make installations smarter and more adaptable. Audiences are becoming more familiar with technology, allowing their curiosity to over-rule our species’ tendency towards fear of the unknown. Understanding how you want the display to change the behavior of your audience is the best way to navigate the vast array of technology choices available.
Conclusion
This is obviously not a comprehensive list of every possible thing to consider when designing a compelling interactive display experience. But when you apply these rules to your project, you’ll achieve a much better, much more satisfying outcome for your team, your clients, and the audience.
Have you done something super cool with interactive digital displays? Let me know, I’d love to share it! | https://medium.com/@megathavale/the-three-golden-rules-of-interactive-display-design-71b8f0fb71f6 | CC-MAIN-2020-34 | refinedweb | 1,674 | 51.18 |
Asked by:
2016U1 REST API Hangs
Question
I'm testing out the new JSON REST api unfortunately I think my install is broken as the api constantly hangs and eventually returns a 500 error. After restarting the service it works for a little bit before hanging again.
Are there any logs I can check to try and figure out what's going on?
I'm resigned to having to reinstall the Head Node, however before going down that route I'd like to see if there's any way to fix it and to do so I'd at a minimum need to see the logs. Any other suggestions of how to debug the problem will be gladly accepted!
Thanks,
DaveThursday, January 25, 2018 11:57 AM
All replies
Hi Dave,
Log of rest service is located at %CCP_LOGROOT_SYS%Scheduler\HpcWebService_*.bin
You can get logviewer app at
Thanks,
Zihao
Tuesday, January 30, 2018 2:12 AM
- Proposed as answer by qiufang shiMicrosoft employee Tuesday, January 30, 2018 5:37 AM
- If you have problem further, please paste the code samples (or send us through hpcpack@microsoft.com), we could take a check for you.
Qiufang ShiTuesday, January 30, 2018 5:37 AM
Thanks for that!
I restarted the service, submitted a job (which worked) then tried to cancel it which then hung and returned the below error:
HTTPError: 500 Server Error: Internal Server Error for url: logs are available at:
Doesn't mean much to me, but maybe someone can spot the problem?
-Dave
Tuesday, January 30, 2018 5:41 AM
- Edited by dhirschfeld Tuesday, January 30, 2018 5:42 AM
Hi Dave,
Please collect related HpcWebService logs and send it to hpcpack@microsoft.com. We'll investigate them.
Thank,
ZihaoTuesday, January 30, 2018 7:03 AM
After re-installing the HPC Pack 2016U1 on a new machine I'm still observing the JSON REST api hanging.
After restarting the HPC Web Service the first attempt to run a job succeeds and any subsequent attempts return a 500 error after a couple of minutes:
HTTPError: 500 Server Error: Internal Server Error for url:
The JSON data I’m using to test is as shown below:: [{'Name': 'Name', 'Value': 'Test'}]: [
{'Name': 'Name', 'Value': 'echo'},
{'Name': 'CommandLine', 'Value': 'echo %COMPUTERNAME%'}
]
I've just now emailed the logs in an email entitled "REST API Hangs". Please let me know if there is any further information you need to debug the problem. Any help trading down the problem would be greatly appreciated!
Thanks,
Dave
Tuesday, March 20, 2018 2:42 AM
Hi Dave,
We cannot reproduce your issue locally. Can you connect to the rest server using our sample code? e.g.
HttpClient httpClient = new HttpClient(new HttpClientHandler(){UseDefaultCredentials = true, ServerCertificateCustomValidationCallback = (a, b, c, d) => true }); var response = await httpClient.GetAsync("" + "/hpc/jobs");
Also we see a lot of re-connect to scheduler events from the log you sent like
[WcfProxy] Channel to net.tcp://dc2thhn02:5802/SchedulerStoreServiceInternal faulted.
Does HpcScheduler service in your cluster work? Is there any other client experiencing difficulty to connect to HpcScheduler service?
Thanks,
Zihao
Tuesday, March 20, 2018 6:01 AM
Unfortunately I'm observing the same thing in C# - the first call to the service works correctly and subsequent calls hang until I restart the service.
> Does HpcScheduler service in your cluster work?
I'm not sure how to test that other than by calling the web api? The Cluster Manager application seems to work fine and lists all the jobs.
Wondering if this can be some bad interaction with the HpcPortal which I also enabled on 443?
My next avenue will be to test the xml interface to see if that also has the same problem. Will report back...
My C# test code is below:
namespace TestHPC { [TestFixture] public class TestHPC { public static bool DisableTrustChainEnforecment(object obj, X509Certificate cert, X509Chain chain, SslPolicyErrors err) { return true; } [Test] public async Task TestAPI() {/json") ); var baseURL = ""; var response = await client.GetAsync(baseURL + "/hpc/jobs"); response.EnsureSuccessStatusCode(); result = await response.Content.ReadAsStringAsync(); } } } }
Tuesday, March 20, 2018 6:49 AM
Hi Dave,
Web portal and web api should work fine together.
Please do tell us if there is any finding in the test of xml interface.
Thanks,
ZihaoTuesday, March 20, 2018 7:14 AM
After some further testing it appears that the xml endpoint /WindowsHPC/Jobs works correctly and doesn't hang.
The xml endpoint /WindowsHPC/Jobs can only be connected to with basic authentication whereas the json endpoint /hpc/jobs can only be connected to with negotiate (SSPI) auth therefore I suspect there's some problem with the authentication in the HPC Web Service which causes it to hang.
Is there some way to enable basic authentication for the json endpoint so I can proceed with that? If that does in fact work correctly on my system then we will have at least pin-pointed the underlying issue.
If anyone has any suggestion of further testing I can do - please let me know! Thanks, Dave
Wednesday, March 21, 2018 5:44 AM
- Edited by dhirschfeld Wednesday, March 21, 2018 5:47 AM
The xml test code:
[Test] public async Task TestXML() {/xml") ); var username = @"DOMAIN\user"; var password = "******"; var encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}")); var auth = new AuthenticationHeaderValue("Basic", encoded); client.DefaultRequestHeaders.Authorization = auth; var baseURL = ""; var response = await client.GetAsync(baseURL + "/WindowsHPC/Jobs"); response.EnsureSuccessStatusCode(); result = await response.Content.ReadAsStringAsync(); } }
Wednesday, March 21, 2018 5:55 AM
- Edited by dhirschfeld Wednesday, March 21, 2018 5:55 AM
Hi Dave,
For now the json endpoint only supports NTLM/negotiate and AAD authentication. There is no basic authentication for it.
It is very likely that it is the authentication part which causing your issue. If you are willing to, we can provide some private bits which enables more log to trace the issue down in your environment.
Thanks,
ZihaoWednesday, March 21, 2018 6:17 AM
Hi Zihao,
I'd be happy to help track down the problem - feel free to contact me by email to let me know what needs to be done.
Could I also request that basic authentication be enabled for the JSON endpoint too? It's useful to be able to quickly and easily test the api in the browser as well as developing with clients which don't support SSPI auth - e.g. the VS Code REST Client or recently in Python there was a bug in the SSPI library on py36.
Thanks,
DaveWednesday, March 21, 2018 11:15 PM
Hi Dave,
Thank you for your assistant. I've sent you a email about how to track the issue down. Also we will investigate about adding basic authentication to new endpoint soon.
Thanks,
ZihaoThursday, March 22, 2018 6:06 AM
Hi Dave,
We have found the potential cause. It is fixed in the latest QFE for Update 1.
Please get the QFE at Download Center and check if your issue is resolved.
Thanks,
ZihaoTuesday, May 29, 2018 2:22 AM
- Thanks for the update Zihao! I'll definitely test and report back any findings. It likely won't be until next week though given my current workload...Tuesday, May 29, 2018 2:30 AM
Unfortunately, after updating to the latest version I'm still seeing the web service hanging. Have emailed further details.
Happy to debug further if there is any more I can do on my side...
Cheers,
DaveThursday, June 21, 2018 3:21 AM
- Did you ever find a solution to this? We're seeing exactly the same behavior (first few JSON API queries work, then the API hangs with the same log messages) in HPC Pack 2016 Update 2 latest update.Monday, May 20, 2019 1:55 PM
Unfortunately no - I worked around it for a while by remote restarting the HPC Service if the call took longer than 1s.
I've since moved on to kubernetes...Monday, May 20, 2019 11:27 PM
Hi,
I'm trying to reproduce the problem.
BTW, we're going to release HPC Pack 2016 Update 3 which supports HTTP Basic Auth for the "/hpc/" end points.
RobertMonday, June 24, 2019 9:30 AM | https://social.microsoft.com/Forums/en-US/49eddc6e-7020-4a49-9118-3c25e65495c0/2016u1-rest-api-hangs?forum=windowshpcitpros | CC-MAIN-2022-33 | refinedweb | 1,360 | 61.97 |
Since a tree is an undirected graph in which any two vertices are connected by exactly one path, the number of nodes should be 1 more than the number of edges. So the code should be very simple...
def validTree(self, n, edges): return n == len(edges) + 1
I've just pushed some additional test cases, please try submitting again. And many thanks to @StefanPochmann for contributing one of the test cases! Stefan had contributed a lot to the LeetCode community posting amazing elegant solutions, reviewing almost every problem and test cases. LeetCode could not have achieved such popularity without your important contribution! Thanks Stefan!
An obvious counter example:
4, [[0, 1], [0, 2], [1, 2]]
This graph is not connected and contains cycle. So it is not a tree.
Yes, correct, this solution can only pass at the beginning when test cases are not enough.
@1337c0d3r I think you're exaggerating a bit, but thanks, I'm happy when my stuff helps :-)
@caikehe Just in case you're wondering, I can see/solve problems before they're published, but if I do, I try to not get an "unfair advantage" and wait a bit before I post my solutions.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/21682/maybe-the-simplest-python-solution | CC-MAIN-2017-51 | refinedweb | 216 | 69.21 |
, C# code cannot be called directly from JavaScript however you can call Objective C objects directly from JavaScript. This is made available via the JSExport protocol. This protocol class is exposed to C# thus it should work since the class is available.
The way it should work is that you inherit this protocol class and decorate the method on the class with the Export attribute that you want exposed as an Objective C method. Something like this ...
namespace JavaScriptTest
{
public class JavascriptBridge : JSExport
{
public JavascriptBridge()
{
}
[Export("addContact:")]
public void AddContact(string data)
{
Console.WriteLine("kilroy is here!!!");
}
}
}
Then to establish the JavaScript binding you'd do something like this ...
// get JSContext from UIWebView instance
JSContext context = new JSContext();
// enable error logging
context.ExceptionHandler = new JSContextExceptionHandler((ctx, ex) => {
Console.WriteLine("WEB JS: {0}", ex);
});
// give JS a handle to the JavaScript bridge.
context[new NSString("myApp")] = JSValue.From(new JavascriptBridge(), context);
// JavaScript that calls into the JavaScript bridge method 'addContact'.
string addContactText = "if (myApp.addContact !== undefined) {myApp.addContact('hello world')}";
// Execute the script.
context.EvaluateScript(addContactText);
You can refer to this article from Big Nerd Ranch to see how JSContext is used in Objective C and download the example:
Here's a closely related enhancement (about a different limitation with the current bindings for JavaScriptCore) that contains a little bit of potentially useful additional discussion:.
The original title of this bug was a little confusing when compared to bug 17550, so I reworded it slightly. This bug (bug 23474) is about sending whole C# objects into JavaScript. The Objective-C mechanism for doing that requires defining _new Objective-C protocols_ that extend `JSExport`, and Xamarin does not currently have a way to do that from C#.
Looks like we can't register protocols dynamically for JavaScriptCore:
Fixed.
maccore/master: b0d8355c0931ad3059066cdb0d37305e0431040e
monotouch/master: ff538393745da3924c9346f3e9f769a7bc91efae
The only catch is that the static registrar must be used.
Here is a sample:
@Rolf, I have checked this issue with the help of Bug description and sample code attached in comment 5. I observed that when I run application I am getting "JS exception" as shown in Screencast.
Screencast:
After commenting "context.ExceptionHandler" I am getting following error :
2015-03-02 18:37:50.312 JavaScriptTest[5357:148816] ObjCRuntime.RuntimeException: Detected a protocol (JavaScriptTest.IMyJavaExporter) inheriting from the JSExport protocol while using the dynamic registrar. It is not possible to export protocols to JavaScriptCore dynamically; the static registrar must be used (add '--registrar:static to the additional mtouch arguments in the project's iOS Build options to select the static registrar).
Due to this exception, I am not able to move ahead. Please review the screencast and let us know what additional step we need to follow to verify this issue.
Ide Log:
Environment Info:
=== Xamarin Studio ===
Version 5.8 (build 1041)
Installation UUID: d6f15b80-470e-4e50-9aba-38a45c556680
Runtime:
Mono 3.12.0 ((detached/b8f5055)
GTK+ 2.24.23 (Raleigh theme)
Package version: 312000077
=== Apple Developer Tools ===
Xcode 6.2 (6770)
Build 6C121
=== Xamarin.iOS ===
Version: 8.9.1.397 (Enterprise Edition)
Hash: 016fd4e
Branch: master
Build date: 2015-02-26 19:15:06-0500
=== Xamarin.Android ===
Version: 5.0.99.288 (Enterprise Edition)
Android SDK: /Users/360logica/Desktop/Anddk.13.1.397 (Enterprise Edition)
=== Build Information ===
Release ID: 508001041
Git revision: fb49f5b17bced266244831c07c28f9fc93915cb1
Build date: 2015-02-27 12:58:53-05
Xamarin addins: e88a2212bb7156a42ad6728b82e99846c3eea817
===
@asimk, can you add "--registrar:static" to the additional mtouch arguments in the project's iOS Build options and try again?
I have also tried the sample gist verbatim with the "--registrar:static" option and get the same error:
JS exception: TypeError: undefined is not a function (evaluating 'obj.myFunc ()')
Some debugging I did leaves me to believe the MyJavaExporter instance is seen as an empty object in JS.
// typeof obj;
2015-03-02 15:25:49.763 JSXamarinTest[67469:16727641] object
// typeof obj.myFunc;
2015-03-02 15:25:49.764 JSXamarinTest[67469:16727641] undefined
// Object.keys(obj).length;
2015-03-02 15:25:49.764 JSXamarinTest[67469:16727641] 0
I had some linker errors that went away after changing the iOS build settings to "Link SDK assemblies only", but that did not change the result of evaluating the JS.
@Michael, this fix has not been released yet (it will be included in the upcoming Xamarin.iOS 8.10 release).
*** Bug 32048 has been marked as a duplicate of this bug. *** | https://bugzilla.xamarin.com/23/23474/bug.html | CC-MAIN-2021-25 | refinedweb | 732 | 50.43 |
User talk:Heerenveen/archive3
From Uncyclopedia, the content-free encyclopedia
Welcome to Uncyclopedia
I saw you made a couple of edits again, which is good, because you've been missed. I hope you'll be back for good; the place really fell apart without you. --
TKFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUCK
23:36, 7 February 2008 (UTC)
- Yeah, I'm back, though I have a hard time believing the site fell apart. A very late congrats on the sysopping, by the way. –—Hv (talk) 8/02 14:31
Hea, thanks for voting on VFD
I noticed your comment about VFD always being full on your user page. Feel free to use the poopsmiths lounge if you know of any particularly poor articles you would like me to move in when the times comes. If more people vote on VFD, we can get the page moving faster. :-). MrN
Fork you! 23:45, Feb 10
- Sorry for not responding sooner, anyway, yeah, I know about the Poopsmith's Lounge and all that (I remember when it was still under Strange but untrue's guidance), and I'll use it in future. Just FYI, that message on my userpage has been there since about April (what with me being inactive for six months and all that). Glad to be of help on VFD, and hopefully we can get more users voting in the future. –—Hv (talk) 12/02 18:44
Selective Inbreeding
I'm very thankful for the review, but for my sake could you go back and elaborate on the humor section so I know, specifically, where and what to improve? Thank you for your time. -- 22:35, 28 February 2008 (UTC)
Loads of thanks
You left for a while....my last memory of you was voting against iTrip. But you came back strong and voted for me this past VFS. Thanks, and I hope to be seeing you around.-Sir Ljlego, GUN VFH FIYC WotM SG WHotM PWotM AotM EGAEDM ANotM + (Talk) 04:44, 1 March 2008 (UTC)
- It's no problem. I was actually surprised you weren't already opped. Congrats! –—Hv (talk) 1/03 15:25
Thank you
Ta for the help with the Scotland Infobox it looks a lot better now, I'll remember that in future:)User:MMACKNIGHTMMACKNIGHT 16:03, 1 March 2008 (UTC)
Thanks!
~Minitrue Sir SysRq! Talk! Sex! =/ GUN • WotM • RotM • AotM • VFH • SK • PEEING • HP • BFF @ 18:12 Mar 1
- You deserved it after all those great reviews. Keep up the good work! –—Hv (talk) 1/03 18:17
- Yeah, here's hoping that being nominated for this award won't make me forget to actually keep reviewing articles. I agree with UU, the award is definitely cursed. =/ ~Minitrue Sir SysRq! Talk! Sex! =/ GUN • WotM • RotM • AotM • VFH • SK • PEEING • HP • BFF @ 18:23 Mar 1
Merci, mon ami
--Sir Todd GUN WotM MI UotM NotM MDA VFH AotM Bur. AlBur. CM NS PC (talk) 10:52, 3 March 2008 (UTC)
THANKS!
For helping SysRq & me with my sig. User:Sk8R Grl/sig 16:35, 6 March 2008 (UTC)
- No problem. –—Hv (talk) 6/03 16:42
Charlie thanks you
~Minitrue Sir SysRq! Talk! Sex! =/ GUN • WotM • RotM • AotM • VFH • SK • PEEING • HP • BFF @ 22:57 Mar 6
Belated
- Heh. Log on. "You have new messages". Check the history first to see who it is. Find out it's you. I think "Oh shit, an op on my talk page, what the hell have I done". Then I find out it's a UotM thanks, and I felt...elated, for some strange reason. Well done on it. –—Hv (talk) 7/03 14:38
Thanks...
Hi Heerenveen, I'm Interferon muton. Thanks for reviewing my article Border Gavaskar Trophy. Would you be kind to review another article which I've written - Judgement Day (please, please, please...). It is related to the first article. Thanks again... - 9th March 2008 —The preceding unsigned comment was added by 121.241.233.98 (talk • contribs)unsigned comment was added by 121.241.233.98 (talk • contribs)
A virgin talk page pussy?
Consider it ravaged. ~Minitrue Sir SysRq! Talk! Sex! =/ GUN • WotM • RotM • AotM • VFH • SK • PEEING • HP • BFF @ 00:51 Mar 16
- No! My talk page! What's happened to it! –—Hv (talk) 16/03 13:30
Template
And then all was quiet. Until...
For all the superb reviews you've been doing of late. Keep it up! --SirU.U.Esq. VFH | GUN | Natter | Uh oh | Pee 22:00, Mar 19
Seeking adoption
Hello, i saw that you were seeking to adopt someone in the "adopt a n00b" program. I would appreciate if you considered Adopting me. Please send me a reply through my talk page. Thank you --Moonzeppelin 00:47, 20 March 2008 (UTC)
Thankies
--SirU.U.Esq. VFH | GUN | Natter | Uh oh | Pee 15:40, Mar 21
Thanks for the Review!
Just recieved your review on the Lara Croft Article, and I would like to thank you for your help. I will take your suggestions and try to improve the article further!
~99.240.53.250
Thanks for the Review of mine also!
I probably will leave it as is. I was just interested if it was at all funny to anyone. Since it's not, I'll leave it to its fate. I have two other articles that need improvement, so I'm gonna work on those first. But thank you. Your comments helped a great deal and I'll apply them in my future pieces...--WesMan20 (talk) 13:34, 24 March 2008 (UTC)
Thanks for your vote
On Battle of the Sexes much appreciated. I wondered if I could pester you as to which parts you thought were too random? To my knowledge there is not actually anything random in there! I know what you mean about going over the top on the random front, and am keen to avoid that. If you could spare the time to give some feedback, you would be doing me a great:59, Mar 24
- It's nothing major, it's just that I felt that it just jumped from one random battle to the next without really explaining how they lead into each other. The other thing that made me think that was what with it being not chronological (i.e. WWII before Waterloo). It's just I value order and whatnot. Your writing of it was very good though, definitely. –—Hv (talk) 24/03 19:06
- Ah, thanks. I get ya. Yea, it was tricky to know which order to put them in. Had I done it the other way around it would not have related to the real world things which I was trying to talk about, but I get your point. Thanks for getting back to me. Much appreciated...:16, Mar 24
Thanks for review
I can really see where you are coming from and I will work to improve on the points you raised.:)--Sycamore (Talk) 13:56, 25 March 2008 (UTC)
- No problems, it's definitely one of the better articles I've seen over there :). Good luck with it! ―― Sir Heerenveen, KUN [UotM RotM VFH FFS SK CM NS OME™] (talk), 13:57, 25 March 2008 (UTC)
Anyway...
I have changed Uncyclopedia:No Reading Articles to be more funny and less in-jokey. Or so I believe. Feel free to knock me for trying. But I do want an opinion.-Sir Ljlego, GUN VFH FIYC WotM SG WHotM PWotM AotM EGAEDM ANotM + (Talk) 02:42, 27 March 2008 (UTC)
- Nah, no need to knock, you've done brilliantly there. I reckon that should, as long as you don't get loads of people saying "Oh, it's in the Project namespace, we can't feature that!" and fainting, that should pass VFH. And yeah, that's definitely less in-jokey now. –—Hv (talk) 27/03 09:26
- Also, I find it slightly weird that I, a sub-mediocre writer who's never had anything on VFH - much less featured - is giving advice to you, an admin and one of (if not the best) writers on this site. But that's Uncyc for you. –—Hv (talk) 27/03 12:58
- Driveby commenting: Relax, and have fun! That, and a look at HTBFANJS, are honestly all it takes to write funny stuff:08, Mar 28
Heeren... what're ya doin'?
Look, look at this: [User:Cajek/Pee table remove due to formatting issues] Out of, like, 120 people who review stuff, you're #3... AND YOU'RE NOT IN PEEING. Join it, and I bet you could be one of the higher ranking people in it in just a few days. Please? Your reviews rock. • <Mar 31, 2008 [23:56]>
- Cajek...he's actually in PEEING. ~Minitrue Sir SysRq! Talk! Sex! =/ GUN • WotM • RotM • AotM • VFH • SK • PEEING • HP • BFF @ 00:11 Apr 1
- Oh for FUCK SAKE. I looked for his name! I really did! YA GOTTA BELIEVE ME • <Apr 01, 2008 [0:20]>
- Cajek, Cajek,... easy mistake to make, as I am a bit under the radar around Uncyc (or was until this month), but that was still bloody hilarious. Although it's nice to know that SysRq's link is also outdated now ;). Also, the formatting seems to have just gone boom. Damn table. –—Hv (talk) 1/04 11:10
- Definitely gone boom. /me slaps forehead Dammit! I WAS LOOKING FOR YOUR NAME!!! • <Apr 01, 2008 [14:12]>
- 'Twas probably my sig3 that made you overlook it, what with the mass shortening and all ;). –—Hv (talk) 1/04 14:15
- So long as it isn't my fault! Speaking of sigs, take a close look at mine... I think you'll find a link screaming for you to click on it, Heeren... :) • <Apr 01, 2008 [14:23]>
Thanks for the Pee!
You probably get this the whole time but thanks for your exceptional pee review! here have this personalised award:
—The preceding unsigned comment was added by Orian57 (talk • contribs)
I • II • III • IV • V • VI • VII • VIII • IX • X • XI | http://uncyclopedia.wikia.com/wiki/User_talk:Heerenveen/archive3 | CC-MAIN-2016-40 | refinedweb | 1,675 | 84.17 |
Hey,
I've been doing really basic programs for fun. This one has me stumped though.
I'm trying to write an encoding and decoding program. I'm sure I can get the decoding if I can just get it to encode right.ber.
Basically what I'm trying to do is assign random numbers to the letters of the alphabet. Like a = 6, b = 98 etc etc. Then I will have the user input the letter and I can't figure out for the life of me how to take that letter and assign it to its number. Then If i could get that to work I will have an encoding number that will be multiplied times the number which will then output. For decoding I can just reverse the process.
Also, this is just letters, if you guys have any suggestions for words that would be great too.
Sorry for the noob question, I'm trying to teach myself C++ and it gets a little complicated. But you guys seem pretty knowledgable :D
Love the tutorials by the way!
I'll post my code so you can get an idea of what I'm trying to do.
Anyway,Anyway,Code:
#include "Library.h"
int main()
{
char letter;
cout << "Enter a letter\n";
cin >> letter;
/*
Somewhere in here I need
to assign the letter a number so
I can multiply it out....
*/
int message;
int encodingnum;
encodingnum = 384739; // Any random number wil work
message = letter * encodingnum;
cout << "Encoded number is\n" << message << endl;
return main();
}
Thanks in advance,
Nate | https://cboard.cprogramming.com/cplusplus-programming/74473-encoding-program-printable-thread.html | CC-MAIN-2017-30 | refinedweb | 260 | 72.76 |
At long last I have managed to get libical 0.46 built on windoze using
VC8. I had to hack a couple of libical source files. I reckon these will
need to go into the official source at some point.
First, I changed vsnprintf.h after the #include <stdarg.h> statement (line
8). I added
#if !defined(_MSC_VER)
and added the closing #endif after the snprintf decl at the end.
This is necessary because VC8 does not define the __STDC__ macro as it
should. One cannot define it in the CMake because this makes other things
fail. Other VC headers expect it to be not defined basically and it causes
problems for some of the macros in fcntl.h.
It may be that at some version of Visual Studio this macro gets defined
correctly. I don't know. VC8 is all I have so I cannot check this easily.
A full fix might involve checking the value of _MSC_VER.
Then I had to edit ical.def. I removed all the occurences of
simple_str_to_float,, a routine that seems to no longer exist. This made
libical build. But the test program regression failed to link due to
missing symbol _icaltimezone_set_tzid_prefix. I added
icaltimezone_set_tzid_prefix to the end of ical.def and rebuilt and this
made everything build ok.
I am puzzled by the reports of everyone else being able to build libical
on windoze ok, given the problems I have found above. Maybe these problems
are peculiar to VC8. Hmmm.. | http://sourceforge.net/p/freeassociation/mailman/freeassociation-libical/thread/OF33B5F44C.89DF1370-ON80257797.0037E7D5-80257797.0038947E@bnpparibas.com/ | CC-MAIN-2015-35 | refinedweb | 247 | 78.25 |
We’ve got great news for you! This year’s first major update, CLion 2019.1, is public!
To update right away, use the Toolbox App, snap package (on Ubuntu), our website, or the patch-update from the latest build of 2018.3. What are you waiting for?
As announced earlier, our main areas of focus this year are IDE performance, expanding Clangd leverage, and Embedded Development. This update makes headway in all three areas:
- Clangd now powers code highlighting, provides more detailed error messages, and performs new inspections.
- CLion’s own language engine has been improved with better performance across the IDE and more accurate refactorings.
- We’ve taken several steps to help you effectively do Embedded Development in CLion.
- Adjust CLion to your code style: ClangFormat, C/C++ naming conventions, and header guards style.
- Project-model-independent build targets and run/debug configurations are now available and are especially useful for compilation database projects.
- Debugger enhancements include:
- Injected languages are here.
- Brighten up your IDE with custom color themes!
- The Rust plugin has been updated.
- Other enhancements include a brand new Recent Locations popup, an improvement for plugin writers, and more.
Read on for more details and check out this short What’s New video by Phil Nash:
We can provide you with a free 30-day trial to test out all these features for yourself before committing to a subscription.
Wider integration with the Clangd-based language engine
As our main focus on wider Clangd integration hasn’t changed, we devote a lot of effort to developing our complementary Clangd-based language engine. Where possible (from the functional and performance point of view), we reimplement actions on this engine, still leaving the option (for now) to switch to CLion’s own engine for such actions.
From a user’s perspective, we see that it makes the editor more responsive. Another step we’ve taken towards wider Clangd integration is that we now leverage Clangd to identify places that need quick-fixes. This means that the Clangd-based language engine can not only be used to identify potential breaches in the code and show an error or warning, but also to provide the location for a quick-fix. Note though that the actual quick-fix is provided by CLion.
This second step however had some drawbacks, and as a consequence a few of the quick-fixes were temporarily removed (CPP-15243).
Amongst other things, the error-annotator has been improved, and can show more detailed error message taken from Clang. Useful cases for this includes debugging a failed overload resolution, where Clang can provide a detailed reason for the substitution failure:
Our C++ language support team is also working on the unique code checks provided by CLion and implementing them on Clangd. This time the Member function can be static check. It analyzes the method body, trying to check if it depends on
this or not:
Improvements for CLion’s own language engine
IDE performance
Even as we are working on the Clangd-based engine, we’re still investing lots of effort into improving our own language engine. First, we aim to boost the IDE’s performance, where Clangd is not yet applicable, and second, we increase the accuracy of the refactorings, which still cannot be moved to the Clangd-engine, at least not in its current state.
Importantly, we’ve reduced the initial indexing times when you create a new project or open one for the first time. The idea is that CLion can now reuse the symbols built already for some other recently opened projects, as long as they fit for this project. A typical case is with STL or Boost libraries, or any other custom library you are widely using in your current and new projects. We plan to work further on this feature and expand on it in the future.
More accurate refactorings
We have been going through and updating the refactorings one by one, and this time we got to work on Extract. To make sure the result is accurate, we worked on making it respect the
std:: namespace qualifier, template specialization and template parameters, and type aliases.
The Rename refactoring has also had some special attention given to it. Now the Rename called on a file doesn’t silently trigger the associated class/struct rename, but instead shows a popup suggesting this option. And vice versa!
Besides, when the header file is renamed, the header guards are updated accordingly if they are used in this header file and the header guards style template used includes the header file name.
First steps towards Embedded Development
If you develop for STMicroelectronics boards, you’ll be happy to find that CLion now integrates with STM32CubeMX:
- CLion’s new project wizard suggests you creating an STM32CubeMX (.ioc) project or you can open an existing project of this type in CLion.
- Later you can start STM32CubeMX directly from CLion at any time to update board settings and generate code.
- CLion will also generate a corresponding CMake file for your .ioc project to work with it correctly and suggest selecting the board config.
If you’ve ever tried the OpenOCD + STM32CubeMX plugin, the functionality is very similar as we now bundled the updated version of this plugin into CLion.
The second part of the plugin can be useful to any embedded developer, as it provides the integration with Open On-Chip Debugger. Use the new Run/Debug configuration template, ‘OpenOCD Download and Run’ to debug on your microcontroller.
Learn more about the integration and necessary setup in this detailed blog post.
Adjust CLion to your code style
ClangFormat
The ClangFormat tool is widely used in the C/C++ world and is even regarded as a standard by many developers. Quite often open source projects store a .clang-format config file in their repository. Now, when you open up such a project in CLion, the IDE will detect the config file and will suggest that you switch to ClangFormat. Which means, ClangFormat is now integrated into CLion as an alternative formatter! It affects all the IDE’s actions, so you can switch to it completely.
There is also a general per-IDE switcher for ClangFormat in Settings/Preferences | Editor | Code Style. Read all about it in our dedicated blog post.
C/C++ naming
PascalCase for classes and structs, camelCase for member functions and variables, SCREAMING_SNAKE_CASE for macros and constants, snake_case for global functions, ‘E’ as a prefix for all enum types – all these naming conventions. CLion understands your pain and now provides the corresponding settings in Settings/Preferences | Editor | Code Style | C/C++ | Naming Convention and respects the selection in all completion, code generation, refactoring actions, and quick-fixes.
You can also select a naming style (and other code style settings) from a predefined scheme: Google, LLVM, Qt, and others are available. Or, you can enable the Inconsistent Naming inspection to have the IDE warn you about any problematic names and then give suggestions for a more accurate name with a quick-fix to replace all the usages for you.
Header Guards style
What do you usually use in header files –
pragma or header guards? By default, CLion generates header guards (you can change the header file template to use
pragma in Settings/Preferences | Editor | File and Code Templates), if you are a header guard kind of person, then you’ll be happy to know that CLion 2019.1 comes with a new ability to configure the header guards style:
The template supports Apache Velocity syntax and uses some predefined variables such as
${PROJECT_NAME},
${PROJECT_REL_PATH},
${FILE_NAME},
${EXT}, etc. If you wish to use a more standard style, select one of the predefined styles option (same as for the naming conventions).
Custom build targets and run/debug configurations
Many of you have been asking us recently to provide you with the ability to build projects using some kind of custom command provided in the IDE. There have also been a lot of requests for the ability to run/debug binary in the IDE by pointing a Run/Debug configuration to the custom executable. This would be especially useful for compilation database projects, which are supported in CLion (and can be extracted from nearly any build system). So in CLion 2019.1, this is exactly what we have done.
To build your project with a custom command, create a Custom Build Target in Settings/Preferences | Build, Execution, Deployment | Custom Build Targets, where provide a toolchain and Build/Clean commands:
To run or debug a custom configuration in CLion, configure the Custom Build Application configuration in Run | Edit Configurations…, where you can provide a custom target, executable, the program arguments, etc.
Learn more about the details of how this all works in our webhelp.
Debugger enhancements
Memory view
Starting from CLion 2019.1, you can dump the raw memory behind a pointer when you are debugging. There is even more to this: open the memory view while debugging and follow the changes to the memory during stepping:
This is still a work in progress. For example, you can expect the ability to dump the arbitrary memory address in the Debug mode coming soon in the updates.
Disassembly view
The Disassembly view has been improved to show the information there categorized by function. And it now works for LLDB, so LLDB and GDB are both covered now.
Use Force Step Into (
Shift+Alt+F7 on Win/Lin,
⌥⇧F7 on macOS) on a function with no source code to open this view:
Mute variables
Variables can take a significant amount of time to calculate, and this may be especially performance-critical when stepping through the code. If you need to keep an eye on the variables calculations, it can be a huge amount of work and may not even be needed in the end. In such situations, you can now Mute variables using a general per-IDE switch. And when you do need to, you can apply the Load option to calculate the particular variable on the current step.
Injected languages
String literals with pieces of code can be treated as real code pieces. This means that code highlighting and language-specific intentions and actions can be applied to them. Typical examples where this could be useful would be SQL or HTML strings, or regular expressions.
To temporarily inject a language, press
Alt+Enter and apply the intention “Inject language or reference”, select the appropriate language, and you are done! Now you can edit code fragments in the dedicated editor section or apply a specific action, for instance, you can check whether a string matches the RegExp right in the IDE:
Isn’t that handy?
Brighten up your IDE with custom color themes!
If the Default white and Darcula themes are not enough for you, then why not go ahead and create your own custom one! Every color of every item in your IDE, from the icons and radio buttons all the way through to the arrows, are now all totally configurable. Adjust them to your own personal preferences and then save it all as a new theme plugin. Learn how to do it in this tutorial.
Rust plugin update
The IntelliJ Rust plugin provides support for Rust along with the Cargo build system and debugger in CLion. This version gives it a massive update:
- Profilers are now supported for Rust: DTrace on macOS and Perf on Linux.
- Out-of-scope items are suggested in code completion and trigger the auto-import when used.
- Rust language injection into code snippets in doc comments is now provided.
- Various improvements to
Cargo checkannotator and LLDB and GDB formatters.
Stay tuned for a detailed blog post on the recent changes (or subscribe to our Rust news here in the blog).
Other enhancements
Other improvements include a new Recent Locations popup, which provides an overview of all the locations that you’ve visited in chronological order, and an updated versions of bundled CMake (3.13), the bundled LLDB (7.0.1), and the latest supported Cygwin (3.0).
Besides, the process of building CLion’s plugins was simplified by publishing CLion as a Maven dependency to be used by gradle-intellij-plugin (since version 0.4.2).
That’s it! Please go and give all the new improvements a try and let us know what you think.
Great! Now my only wish is the MSVC Debuger.
Thank you. It’s under development now. We hope some preview (very early bird) will be ready for 2019.2
Wow! Will that be cdb (which sucks about as much or more than gdb), or the REAL MSVC debugger? This would be huge!
It’s LLDB-based debugger implemented from scratch by our team.
I can’t wait! Are there any plans for the debugger to support Rust well on MSVC? Now that would be a slam dunk. Lack of a good MSVC debugger integration is one of my major reasons not to use Rust.
No plans for Rust at the moment. And mind, it’s not an MSVC debugger integration. This is impossible due to licensing reasons. We do implement a debugger from scratch.
compilation database is not support with postgress project, pretty strange
What do you mean by not supported?
run compiledb -n make under postgress dir will never end, and no usable compile_commands.json
How about collecting it using?
Finally! Thank you!
Hi, congrats on release. I’ve noticed an issue with update. After update clangd server doesn’t work. It launches and crashes, as I can see from process explorer. As a result all code resoving features don’t work. And I can’t open any new files – they are constantly loading. Restarting CLion doesn’t help. To fix I have to turn off clangd in settings, restart CLion, then turn on and restart again. Not reproducable, unfortunately.
Could you please get logs from Help | Show log and submit with this description to?
Unfortunately they contain sensitive information.
Which platform are you at?
Windows 10, using WSL with Ubuntu 18.04
Ok, can you please view the IDE log and maybe look for smth suspicious in there? Crashes, traces, etc.?
How do we disable the clangd memory indicator enabled by default in the EAP?
Thanks
It’s disabled by default in the release. And is controlled by Preferences | Appearance & Behavior | Appearance | Show memory indicator
I want the old memory indicator(very useful), but without the clangd one.
What’s the purpose of having one w/o another?
That toolbar is already overcrowed and the CLion memory really shows something (1500 of 2000M) and I constantly press it to clear the memory but the clang one is always (or most of the time) at 0-100M, so almost useless.
Also it’s funny that they have different formats, one is “100/200M”, the other is “100 of 200M”
For C++ IDE I think both memory indicators are worth looking for if you suspect some issues and turned them on.
Regarding the format, you are probably right and we should unify.
Excuse me if I sound harsh, but… as I really wanted to use CLion, just because I’m a fan of your tools, I still feel stupid trying hard to learn how to include a simple lib in a hello world project. Trying to find out how to create build configurations, like release and debug, architecture variants. Learning how to properly debug something on windows (and installing a lot of tools I won’t use for anything else to support that).
I gave you this advice before, and feel like you didn’t read it at all. Download simple, free IDEs and try to compare them with yours. Start with QtCreator. If I have to stop and learn how to do basic IDE tasks, then CLion doesn’t even beat MS Code with a couple of plugins.
If you have CMake project, which is the most popular project model in the cross-platform C++ dev, then it’s not an issue to add a library or create a new target. CLion then gets it automatically, and create corresponding Run/Debug configurations for your targets.
If you want smth more specific, custom and complicated, then some UI is there to configure, and it’s the same as it goes in other IDEs.
We feel that for example with CMake projects, it’s much easier to start in CLion, than let’s say in QtCreator, as you need nothing except pointing to a top-level CMakeLists.txt file in CLion.
Windows platform is maybe more tricky, but for cross-platform platform projects it is so even w/o CLion if you are not using VS toolchain.
QtCreator is horrible with CMake projects.
VSC has a free CMake extension but it is well free… Its development appears stalled. The only viable alternative appears to be VS2019 for CMake but it is just for Windows and it gets broken all the time. Its CMake support is still not mature.
Yeah, and guess what? QtCreator doesn’t depend on an external tool to build a simple hello world. Besides that, last time I checked, it was just like Clion. It gives you a CMakeLists.txt to edit and good luck, champ. I mean, what is the problem with that? Everyone is a cmake wizard nowadays.
Cmake IS the problem here. News for you all: not everyone wants to spend time maintaining their projects with a text file. What about build configurations? What about multi platform management? What if my project uses 200 libraries? I could spend the night typing “what ifs”.
But the most important reply to your comment is: if its so simple, why not providing a proper ui, so the developer won’t have to know your build tool at all?
CMake sucks, but until something better is available, it is one of the only real solutions for c++.
So many options, so many features, wow, but I still have input lag when I edit a 5000-lines file…in 2019.
Also, when the file is very small and I include curl.h (from cURL), it’s totally disaster, the text has 2 seconds delay.
Yes, I opened bugs for both 2 years ago…
Please list particular links to the tracker, so that we can recheck.
We do constant job on IDE performance improvement, all these Clangd changes are in this direction, so I can’t say we are not giving any attention to it.
Any time I have medium sized projects, or moderate use of templates, Clion causes my fans to spin at max speed and code completion to fail. 2015 MB pro.
We are aware of many performance issues and work on them with top priority. Anyway, will be useful if you collect CPU snapshot and share with our support.
I can’t do that due to proprietary nature of my project. To reproduce this, I would recommending undertaking a medium scale project (several 100K loc), that utilizes several libraries (curl), while making use of modern c++, and light but consistent use of templates. It doesn’t take much to cause it to do this. I often see 300% or 400% CPU usage, and code completion / refactoring / other features grind to a complete halt while my fans spin like crazy. I notice that using auto messes up the type hinting system… which indicates that your model for types is not advanced enough to offer useful suggestions. It is likely the same problem that is causing issues with templates.
Yes, we see various issues in various medium or heavy projects. But they are not caused by one problem. We have a set of known issues we are working on and definitely some we’ll discover later. That’s why we are usually asking about snapshots and code samples. In order to get the nature of the particular problem case.
I have the same. I also noticed that copy/paste a few characters in a few thousands lines file can take up to 10 seconds on Xeon workstation with 64 GB. It seems to be an issue with code formatting as pasting without formatting is fast.
Do you have a CPU snapshot of such delay? Do you have a code sample you can share? Would be very interesting to check it out and dig further in what’s going on in our formatter there.
Why can’t i explore the memory view manually or show a stack variable in memory view? I wish Clion’s debugger support would be as good as eclipse’s :/ otherwise Clion is a great IDE but it lacks debugging support.
Also it would be nice to have a disassembly view that you can explorer as you wish, i.e. next to your c++ code you have the disassembled view so you can check what asm code was produced by the corresponding c++ code (of course this will not work pretty well with -O2 -O3 or even -O1 but it still is a very valuable information).
All in all i like the update but i am still hoping for better debug support and faster autocomplete which takes ~1 second for large header files on my machine (quadcore i7).
By explore manually, do you mean getting memory view by entering a particular address into some UI?
Local variable – works, if it’s a pointer. We’ll later add other cases.
Disassemble on demand is planned for the future releases.
Completion speed-up is also planned, but it’s worth sharing a CPU snapshot with us for the case when it takes 1 sec.
Hello Anastasia,
thank you for reply.
Yes, by manually exploring i mean that you can go to any arbitrary address (i.e. stack and heap memory) and watch it in the memory view.
The plans do indeed sound very nice and promising, i am looking forward to them.
Have a nice day!
Thank you! Memory view UI/UX was kinda experimental in this release, and we definitely see issues and plan to improve.
Size of codebase I had to work with grows faster then Clion performance
Been my experience as well. I’m not sure they understand what it means to have millions of lines of code in thousands of modules. Marking everything as a library isn’t a real strategy. Their platform needs to dramatically change it’s efficiency to be useful at scale.
In my opinion CLion should learn something from QtCreator. For the project it takes Clion 20 minutes to “Update symbols & Build Indices”, QtCreator is ready to work in __seconds__. And it is really ready to work : auto-completion works, Locator works, switch header/source works!
Yes, maybe super smart features like global refactoring or search for string literals require 20-minute analysis of project (When Clion completes 20-minute parsing it becomes best in the world to do this unusual navigation). But please let me code immediately, while doing this long parsing in background.
Have you share some CPU snapshots for such a case with us? Just to check what CLion does there.
Anyway, CLion doesn’t parse files not included into project/CMake. However, some pre-processing is done for libraries. Any particular case should then be deeper investigated.
Yes, already did
For this project:
QtCreator Open CMakeLists, parsing – 20 seconds
Clean Build – 10 minutes
Clion Onen CMakeLists, Updating symbols – 20 minutes
So what QtCreator does in 20 seconds, Clion does in 20 minutes
After initial parsing Clion performance for this project is good enough. So I work with 2 IDEs open. I use QtCreator when Clion is parsing, when Clion is ready I switch to Clion.
Let me just ask – in which situations it’s that slow: initial indexing or reopening of the already indexed project, or switching branches? This is three different situations. So need to get it clear. About all three just to explain:
– initial indexing can indeed be long. Should be optimized anyway (for example, in 2019.1 we’ve added an ability to reuse the indexed external libraries like Boost or STL in some cases), but it should happen only once.
– reopening should be quick. If not, that’s a bug. We need to investigate
– switching branches is a known issue, that has its roots in IntelliJ platform architecture and VCS implementation. We are currently working on improving the case. Hope to get good results in 2019.2 and 2019.3 releases
And it is a deal breaker for many in my organization. When I ask people about Clion, answer is usually “Yeah, I’ve tried. It’s so slow.”
>> Let me just ask – in which situations it’s that slow
1) Initial opening
2) Switching branches
The snapshot in the comments (in the ticket) is it for the initial opening? Can you please get one for that stage on 2019.1?
Yes, it was initial opening. Uploaded new snapshot.
Yes, I see your comment in the ticket, thank you. We’ll check it out
I don’t know what Clion does exactly, but I suspect it parses files that are not included in CMakeLists (I suspect this because it does arbitrary text navigation that fast, so it should have some index for every text file). And this can explain why it is so slow in building symbols.
In organizations that have monorepos, this approach fails.
Does CLion support Kotlin native? Does CMake support Kotlin native? Does Android/AS support Kotlin native?
What about mixed C/C++, Kotlin CMake projects, libraries?
Do you consider such options to make these happen?
Kotlin/Native is supported in CLion. With Gradle, not CMake. And you can do mixed projects for sure and work on them in CLion.
Let me clarify my question: Do you plan to make a CMake only Kotlin support happen? This means support Kotlin in CMake? CMake is nasty enough on its own and I’d rather have to deal with one build system instead of two. I have a CMake project and I also have a wrapper project to compile it for Android – Gradle + CMake is too much (too slow)! I wouldn’t even start that I find the C++ support in Android Studio underwhelming – like how error messages are handled, build system output etc…. it is just bad.
We don’t plan to support CMake for Kotlin/Native. Kotlin/Native is a part of Kotlin Multiplatform and it makes it even harder to support such projects in CMake. So we moved to Gradle.
Nice release, but switching from header to cpp file still takes forever if it event get found at all. Any other devs with this issue?
Yes, we plan to rework it in 2019.2
CLion 2019.1 drives me crazy. I opened a 2018.3 project and got a lot redefenition warnings for structs and functons. Only header files without a related src file are affected, it is gone when I create a related empty .c file and just include the header. Pls fix this! Have to downgrade CLion meanwhile.
Could you please submit an issue with a code sample and a screenshot or detailed text of the error?
There are already some open:
Ddifference is I use C instead C++.
I see. Is it Windows platform?
Yes, Windows 10.
Then yes, it is it. We are on it, managed to reproduce, now investigating.
Double post! Sorry!
“It’s LLDB-based debugger implemented from scratch by our team.”
Is there any plan to allow to use that debugger for other toolchains? (e.g. WSL)
We may consider this as well, but the two parts of the work are a bit unrelated anyway.
Thanks for reply. I hope to be able to use WSL’s LLDB in CLion.
Thank you for yet another great release, especially about the embedded development features. It would be really cool if you could also add support for AVR as I’d really like to drop atmel studio in favor of clion. Atmel studio is not that awful, but it’s windows only (I prefer working on Linux) and honestly, whenever I switch to a different IDE, I realize how much I miss the power of the IntelliJ platform.
Thank you. We’ll consider that.
Can you, please, describe your tool set (toolchain, debugger, flashing probe, target chip name etc) and share a demo project, which uses that all. This may simplify things for us.
I think AVR-GCC based projects may be done with CLion already, thought the setup may be a bit complicated.
When using a remote toolchain, the compile commands db doesn’t get parsed correctly.
Clion expects the directory paths and the compiler to be present on the local machine instead of on the remote machine. Hence nothing indexes or syncs correctly and there is no intellisense.
If a remote toolchain is configured, surely it should be using the remote system when parsing compile_commands.json?
Remote mode is currently supported only for CMake project model.
To be clear, it doesn’t appear that CLion supports remote development with compile_commands.json projects?
i.e at least the following issues are present, despite using a remote toolchain:
1. Directory paths from compile_commands.json are expected to be on the local system.
2. compiler and arguments in compile_commands.json are expected to be on local system and executed locally.
3. clangd is run on the local system instead of remotely, so cannot use compile_commands.json correctly or read system headers
4. It does not seem possible to open project files over sftp
It would be great if there was a mode that just ran clangd, build tools etc via scp and accessed files via sftp etc, honouring the remote host configuration.
yes, it’s currently not supported. We are aware of the issues. Remote toolchain works now only for CMake.
How about the following scenario: the project is developed and built (with makefiles and compilation DB) on the same local machine and the binary runs on a remote machine (different architecture) and with GDB server interface. The remote machine runs a raw binary with no symbols/sources; we provide the path to the symbols to the local LLDB we use for debug (which connects to the remote GDB server).
Can we expect to be able to debug such a setup in Clion?
This is already possible, feature is called Remote Debug with gdbserver:
Thanks, will definitely give it a try!
I seem to be stuck at telling CLion how to open LLDB. The way we do it today (on MacOS) is:
“xcrun lldb “.
In CLion I can either use the built-in GDB (no LLDB option?) or a path to an external GDB – but no way to add parameters?
The built-in GDB returns: com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver$GDBCommandException: Remote failure reply: E01
Directly using our LLDB results in:
lldb: unrecognized option `-interpreter=mi2′
When I tried to bundle our command above into a script and tell CLion that it’s GDB, it waits for a while and then times out.
Please advise what else can we try?
The command syntax was eaten by your comments system. It is
xcrun custom_parameters lldb path_to_target_file
Probably need to find a way to call this from within CLion?
Hi Anastasia, any thoughts on the LLDB opened with xcrun (see details from April 11 in this branch)?
Hi Alexey,
Sorry for the late response. I’m afraid it’s not possible to use LLDB from CLion for debugging via a gdbserver (). Meanwhile, we suggest using GDB for debugging remote targets. The built-in GDB is compiled with multiarch support so it’s capable of debugging most of embedded targets supporting gdbserver.
What is the exact target arch you try to debug?
We’re working on something proprietary, so I doubt standard GDB server will manage. I did try it, however, as noted above, and got:
com.jetbrains.cidr.execution.debugger.backend.gdb.GDBDriver$GDBCommandException: Remote failure reply: E01
I see. The remote end doesn’t have to be a gdbserver, actually, it can be anything supporting the standard GDB remote protocol, like Qemu or some JTAG monitor.
So you’re saying that this is a custom architecture, and you only have an LLDB port for it, but not GDB, do I understand that correctly? If you use a custom build of LLDB for debugging your remote target, I’m afraid CLion doesn’t support that, since we only integrate with our bundled LLDB binary.
More or less. It’s ARM based, so I’d still expect some basic things to work. As I understand, “GDB-Server” reports back the PC (and the registers?), and CLion, through GDB, makes order from it and finds the correct place in the source code, right?
Why does it fail with an exception, then?
Is there any way to help the built-in GDB find the architecture that’s best matching to ours?
Does it discover it during its handshake with the GDB server (which is probably the part that fails)?
The best way to investigate this is to collect debugger logs, that contain all the commands sent to the debugger by CLion. Please follow the instructions at- to enable the logging, then reproduce the error, and send the resulting idea.log to
clion-support at jetbrains.comwith a reference to this comment thread. Thanks.
Will do, thanks!
does a custom build work for local projects only?
I’ve specified toolchain remote (and configured scons build) but when I perform the compilation it tries to do this locally.
ah, I see the reply above – unsupported yet
yes, full remote mode is supported for CMake only. But remote gdb debug with gdbserver is general enough to work with any.
Hi Linux C programmer here. I am using your tool with a project written in C that contains about 50-60 files. The tool is perfect for this. I managed to add support for plain old makefiles as this project requested. I used the 2018 version which sold me over any other IDE.
However, switching to 2019 my annoyance level went up big time. I am loosing productivity big time.
1. Where did Optimize Imports go? I cannot find it anymore. It is not in the menu and the keyboard shortcut does not work anymore.
2. Code folding: why any brackets from if, while, do can have their own code folding icon on the side? I need to learn a new shortcut to do this…
3. The TAB functionality: Why does it behave differently when I tab freely in the empty spaces, but once I am getting to align a piece of text, it actually jumps to the parameters of the function. I do not have a problem with this if it was a Shift|Ctrl|Alt TAB, but not TAB.
4. Now the most annoying: I am trying to copy and paste text from one part to another. The select using the mouse selects the text, basically an area, the cursor becomes as tall as all the select area and when I try to copy this selection in some other area if the free area is not as tall as the area I am copying it, it will jumble with the text that should be pushed down. So if I only have one line free where I want to paste, the editor will put the lines in parallel with the one I paste.
Please, please, please, stop reinventing the wheel and not making it round. please don’t replace expected functionality with something unexpected.
Hi,
I’m sorry you feel this way. Let me address your points one by one:
1. Optimize imports had many-many false positives, so we temporarily removed it. We plan to rework and put it back in 2019.2 or 2019.3
2. We on purpose didn’t add gutter icons to fold control blocks. You can fold them with shortcut and then the gutter icons will appear. Otherwise, the left gutter becomes too overcrowded.
3. In your keymap you can remap the “Next parameter” action to any other key you prefer instead of Tab.
4. I’m not sure what happens to your cursor there, could you maybe record a video with all the keystrokes you hit during it?
Thanks for your comments.
Not sure if I can record a video, but here the the steps:
1. Select an area of code (multiple lines) using the mouse; the selection will not select full lines, just the area. Do a Ctrl C to copy the code.
2. Move to a place where you want to paste it, preferably between 2 existing lines, call them ‘first line’ and ‘second line’.
3. Paste. See what happens. (Instead of the code to go sandwiched between the 2 lines, and the second line to go under the pasted code, the second line goes in parallel with the pasted code).
May I guess you have the Column Selection Mode enabled (by mistake)? When it’s not enabled my mouse selects only full lines. To enable/disable look for it in Edit menu, not sure of the shortcut in Linux, it’s CMD-Shift-8 on Mac, very useful!
That was it. But it wasn’t enabled. I had to cycle the selection. Sorry for the confusion.
So, does it finally work for you?
With the 2019.1 update, Application Template in Run/Debug Configuration is missing.
I cannot debug a native application anymore? something like this
Is there an alternative to this? I tried Custom Build Application but that needs a Custom Build Target and I cannot choose a CMake Target that I already have. seems like a regression.
Since that was a CMake related application, we renamed it in 2019.1 to CMake Application. That’s what previously was called Application, and was not really accurate as it requires the CMake target.
I really think the team needs to focus on performance over everything else. There’s enough features in the IDE already, but it really needs is less freezing. I could probably convince most of the C++ engineers in my company to switch to it (20+ people) if it just didn’t freeze typing, but it does not seem like performance is getting any better. If anything, I get more freezes in this version.
I’m not even asking for it to do operations quickly, I just want to be able to keep typing while it does whatever is taking so long in the background.
We do treat performance as a top-priority task. And in some areas the performance is indeed getting better, also many freezes were eliminated. However, there are still places that require more work (currently planned) and some huge architectural changes (in progress, but not a one-release-cycle thing definitely). So it’s sad to know that for you the performance is worse. Maybe you can report the thread dumps to us (when UI is freezing they are created automatically in the IDE’s log directory)? We’ll investigate and try to help.
Hi,
is it possible to have remote toolchains also work with software packages which are installed into /opt (or any other directory than /usr)?
I’m relying on a proprietary library which is installed into /opt which is fine for CMake but the codemodel doesn’t pick it up emitting false positives all over the place.
Do you use the remote toolchain? How the library is linked in CMake?
Hi,
yes, I’m using the remote toolchain.
First thing is to set a variable for the Find script where to find it (set(THE_LIB_DIR /opt/thelib)), then I’m using a ‘find_package(TheLib COMPONENTS Component REQUIRED)’ call in CMake and finally link to the exposed target like this: target_link_libraries(MyProject PRIVATE TheLib::Component).
> is it possible to have remote toolchains also work with software packages which are installed into /opt
Yes, it has to work.
1. Could you please run
Tools -> Resync with Remote Hosts
2. If the problem still exists please open file with unresolved include and run
Help -> Find Action -> Show Compiler Info, then find section
Header Search paths:and check if required library is in this list.
If required library is not present in
Header Search pathsplease file an issue with proper description, also it would be nice if you create a simple project which helps us to reproduce the problem. Thanks in advance.
Hi,
> 2. If the problem still exists please open file with unresolved include and run Help -> Find Action -> Show Compiler Info, then find section Header Search paths: and check if required library is in this list.
As you suspected it was not in this list. And like you said, other headers in non-standard directories (namely conan-packages) are found. But they are also integrated a bit differently into the CMake build.
I created an issue here with an example to reproduce it:
Thank you for your help!
Thanks. | https://blog.jetbrains.com/clion/2019/03/clion-2019-1-embedded-dev-clangformat-memory-view/ | CC-MAIN-2019-35 | refinedweb | 6,835 | 73.17 |
Control Robotic Arm With Gloves, Android Phone and Arduino
Introduction: Control Robotic Arm With Gloves, Android Phone and Arduino
Today, we have almost 2 techniques to play with Robotic Arm, either by buttons for example as on Game shield or using gloves that include sensors. Yet, today I will show you a new technique by using only your Android Phone and Arduino.
Basically, The project illustrate how to send the mobile sensors data via Bluetooth to Arduino using 1Sheeld and then controlling the motion of the servos.
Step 1: Components
1- Arduino Uno (18$)
3- Servo X2 (1.8 $)
4- Gripper for Robotic Arm with 2 DOF (2.3$)
5- Any Metallic heavy Base.
6- Any kind of strong adhesive (glue)
7- Android Smart Phone/ Tablet.
Step 2: Arm Fabrication
Actually, I'm don't have too much experience in mechanical things. Yet, I tried as much I could to implement the Arm as shown in figure. Basically, all you have to do firstly is to estimate how much load each servo will carry in order to get the right servo with the required torque.
Step 3: Mobile Application
Step 4: Arduino Sketch
As shown below the code is so simple. Actually, any one even who is new in using Arduino can get it.
All we have to declare the pins for 4 PWM for each servo and then map the Value of the sensor from (0 to 180) which are the whole region the servo can rotate.
#include <OneSheeld.h> #include <Servo.h> Servo myservo1; Servo myservo2; Servo myservo3; Servo myservo4; void setup() { OneSheeld.begin(); myservo1.attach(3); myservo1.write(90); myservo2.attach(5); myservo2.write(0); myservo3.attach(6); myservo3.write(180); myservo4.attach(9); myservo4.write(15); } void loop() { if (ToggleButton.getStatus ()) myservo2.write(120); else myservo2.write(0); if(OrientationSensor.getZ()>0 && abs(OrientationSensor.getZ())<= 83 && GravitySensor.getZ() > 0) myservo1.write(map(OrientationSensor.getZ(),0,90,90,0)); if(OrientationSensor.getZ()<0&& abs(OrientationSensor.getZ()) <= 83&& GravitySensor.getZ() > 0) myservo1.write(map(abs(OrientationSensor.getZ()),90,0,180,90)); if(OrientationSensor.getY() < 0 && OrientationSensor.getY() >= -90 && abs(GravitySensor.getZ()) >= 2.5) myservo4.write(map(abs(OrientationSensor.getY()),0,90,15,105)); if(OrientationSensor.getY() > 0 && OrientationSensor.getY() <= 50 && abs(GravitySensor.getZ()) >= 2.5) myservo4.write(map(abs(OrientationSensor.getY()),0,50,15,0)); if(OrientationSensor.getX() > 0 && OrientationSensor.getX() <= 180 && abs(GravitySensor.getZ()) >= 2.5) myservo3.write(map(abs(OrientationSensor.getX()),0,180,180,0)); }
Step 5: Test
Finally, all you have to do to open 1Sheeld mobile Application, then choose the required shields (Orientation, gravity and Button) .
hello, im having a trouble, i upload the code and as soon as i turn my motors on they keep rotating forever. I need help ?
Sorry, I'm kinda new at arduino, which holes in the circuit board do the servos. That probably sounds like a dumb question, sorry
the pwm ports
the one that are having a tild(~) this type of notation.
Hey! I'm sorry but I'm a real novice at using arduino so could you tell me how am I going to make my servos take only a 35 degree rotation? Please do reply. Thank you! XD
Hi, i'm having some trouble
could you contact me at lfernandomr25@gmail.com
Please!! thanks.
Its Looking Cool.....
I'm so glad for being interested
Great... project...especially what using android phone....
yeah sure, actually smart phones nowadays have powerful capabilities that we should use in our projects :)
What website did you get the gripper from?
I got it from a local electronics shop in my city. I think you will find it in Amazon or aliexpress
That's so cool, looks like magic to me! Thanks for sharing your process!
Thanks a lot :) | http://www.instructables.com/id/Control-robotic-arm-with-gloves-Android-Phone-and-/ | CC-MAIN-2017-51 | refinedweb | 628 | 50.84 |
Security Section Index | Page 5
Does Java Card support biometrics?
No. As of version 2.1.1, Java Card doesn't provide any API for biometrics.
How does Java Card protect itself against SPA, DPA, etc?
The Java Card specification doesn't deal with smart card attacks. Card issuers have to make sure that their Java Card implementation is immune (or at least very resistant) to all well-known smart ...more
Are transient writes transactioned?
No. Transient data is lost whenever the card is powered-up, so it wouldn't make sense to include it in transactions.
May transient data be shared?
No. Any attempt to share a transient array, whatever its type is, will trigger a SecurityException.
How much transient data can I allocate?
Not much. The value is platform-dependent, but it's usually around 220 bytes. Transient space is shared among all applets, so you need to be very conservative. Unfortunately, there's no API to get...more
When do I need to use transients?
Transients are relevant when you need to store data that mustn't survive either applet deselection or card reset. They're also good for frequently modified non-persistent data and temporary result...more
Can any object be transient?
No. Java Card 2.1.1 only support transient arrays of primitive types (boolean, byte, short) and of Object references. You can't just create a transient instance of the MyObject class. Note than o...more
What is transient data?
Transient data is applet data, which is cleared either when the applet or deselected or when the card is reset. Transient data is stored in a dedicated RAM area and is typically used to store sess...more
How secure is object sharing?
The security of object sharing relies on AIDs. If an applet may be loaded with an arbitrary AID, then your security is pretty much out the window. This is why the security mechanisms provided by O...more
Can any data be shared?
No. To be shareable, an object must be an instance of a class implementing an interface extending the Shareable interface. Got that? Well, this is the one-line version. Check out the Java Card doc...more
Can two applets share data?
Yes. If two applets live in the same package, they are attached to the same memory context. Thus, they may exchange object references and use them directly. Two applets living in different package...more
What is the firewall?
The firewall is a software feature of the Java Card platform, which isolates applets from each other. In other words, even if an applet succeeds in obtaining a reference to an object belonging to ...more
How safe is Java Card?
This is a very tough question. The security of Java cards is evaluated using the Common Criteria (CC) methodology. A number of platforms (Gemplus, Oberthur Card Systems, Schlumberger, probably ot...more
What are the security features of Java Card?
The main security features of Java Card are: All the benefits of the Java language: data encapsulation, safe memory management, packages, etc. Applet isolation, thanks to the Java Card firewall. ...more
How do I configure a HostnameVerifier on an HttpsURLConnection?
The solution: connection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String urlHostname, String certHostname) { return ("".equalsIgnoreCase(ce...more | http://www.jguru.com/faq/core-java-technology/security?page=5 | CC-MAIN-2017-43 | refinedweb | 545 | 61.02 |
#include <termios.h> int cfsetispeed(struct termios *termios_p, speed_t speed);
int cfsetospeed(struct termios *termios_p, speed_t speed);
The cfsetispeed() function sets the input baud rate stored in the structure pointed to by termios_p to speed.
The cfsetospeed() function sets the output baud rate stored in the structure pointed to by termios_p to speed.
There is no effect on the baud rates set in the hardware until a subsequent successful call to tcsetattr(3C) on the same termios structure.
Upon successful completion, cfsetispeed() and cfsetospeed() return 0. Otherwise −1 is returned, and errno may be set to indicate the error.
The cfsetispeed() and cfsetospeed() functions may fail if:
The speed value is not a valid baud rate.
The value of speed is outside the range of possible speed values as specified in <termios.h>.
See attributes(5) for descriptions of the following attributes:
cfgetispeed(3C), tcsetattr(3C), attributes(5), standards(5), termio(7I) | http://docs.oracle.com/cd/E36784_01/html/E36874/cfsetospeed-3c.html | CC-MAIN-2015-27 | refinedweb | 152 | 62.07 |
Currently, read-event waits forever when called in batch mode. This is because of the following fragment from kbd_buffer_get_event: #ifndef HAVE_DBUS /* We want to read D-Bus events in batch mode. */ if (noninteractive /* In case we are running as a daemon, only do this before detaching from the terminal. */ || (IS_DAEMON && daemon_pipe[1] >= 0)) { int c = getchar (); XSETINT (obj, c); *kbp = current_kboard; return obj; } #endif /* ! HAVE_DBUS */ The call to getchar will wait indefinitely, until something is typed on the keyboard. Worse, if Emacs is built with D-Bus, this fragment is bypassed (including if Emacs is run in daemon mode!), and then read-event does honor the timeout. The net effect is that writing code that waits for events and works on all platforms is tricky at best. This was discovered while debugging the problems of file-notify-tests.el, see bug #16519 for more details and context. Does any port for a supported platform need this fragment, or can we safely delete it? What about the daemon -- does it need this "when detaching from the terminal", and if so, why? In any case, I think we need to document this deviant behavior, at least for now, because there's no hint of it anywhere in the docs. Of course, sit-for is also affected by that. Comments? | http://lists.gnu.org/archive/html/emacs-devel/2014-01/msg02247.html | CC-MAIN-2019-18 | refinedweb | 217 | 73.37 |
Double Brace Initialization in Java!
- By Viral Patel on June 26, 2009
Few days back I came to know about a different way of initializing collections and objects in Java. Although this method of initialization has been there in Java since quite a few years now, very few people actually knows about it or have used it in their code. The technique is called Double Brace Initialization technique in Java.
Let us see first how we will initialize an ArrayList in Java by “normal” way:
List<String> countries = new ArrayList<String>(); countries.add("Switzerland"); countries.add("France"); countries.add("Germany"); countries.add("Italy"); countries.add("India");
Above code snippet first creates an object of ArrayList type String and then add one by one countries in it.
Now check the Double Brace Initialization of the same code:
List<String> countries = new ArrayList<String>() {{ add("India"); add("Switzerland"); add("Italy"); add("France"); add("Germany"); }};
How does this works?
Well, the double brace ( {{ .. }} ) initialization in Java works this way. The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an “instance initializer”, because it is declared withing the instance scope of the class — “static initializers” are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class . The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors.
If you have not understood the concept, try executing following code and it will make things clear for you.
public class Test { public Test() { System.out.println("Constructor called"); } static { System.out.println("Static block called"); } { System.out.println("Instance initializer called"); } public static void main(String[] args) { new Test(); new Test(); } }
Output:
Static block called Instance initializer called Constructor called Instance initializer called Constructor called
Thus the instance initializer code will be called each time a new instance of object is created.
Get our Articles via Email. Enter your email address.
Unfortunatelly that code creates anonymous class. Multiple using of such technique will create dozen of anonymous classes, and that could cause problems with perm gen space.
I agree with you Ruslan. This technique is not efficient way of doing this, but I dint knew if such thing exists :-)
I agree with Viral that many Java developers will not be knowing it unless they read the specification. Nice to know that such an option exists.
Interesting to know with clean explanation
Javas Double Brace Instatiation makes it a lot easier to read your source code. For review reasons is that important to you and your colleagues. I think most people only see these advantages if nobody uses them: they would be glad to have them.
A few tips and backgrounds, too: is is about the obstacles and the possibillities with Javas Double Brace Instatiation:
I hope I could help a little.
Awesome! Never tried such a thing so far. This could be useful in providing easy fixes.
Thanks
Hi,
Anybody please help me , how to send /receive sms from/to java web application/java application.
Nice explanation…Thanks a lot for this article.
I tried this program and Guess what {{}} Looses….. n times So I appreciate your effort but this is lil slower think..kindly revert If I am wrong. | http://viralpatel.net/blogs/double-brace-initialization-in-java/ | CC-MAIN-2014-52 | refinedweb | 590 | 63.8 |
BuildSim Cloud API library for Python
Project description
This library allows you to quickly and easily use the BuildSimHub Web API v1 via Python.
This library represents the beginning of the Cloud Simulation function on BuildSimHub. We want this library to be community driven and BuildSimHub led. We need your help to realize this goal. To help, make sure we are building the right things in the right order, we ask that you create issues and pull requests or simply upvote or comment on existing issues or pull requests. We appreciate your continued support, thank you!
For more information, examples, and tutorials, please check our wiki page.
Table of Contents
- EplusGIT model management system - compare, merge and copy - can be accessed through API
- Regional project and global project. - the newly added global project allows user upload custom weather files for simulation / parametrics.
- Design day condition - automatically update design day conditions.
Previous update: Version 1.5.5: 4. Package and distribution on PYPI 5. New [monte carlo] algorithm is implemented in parametric study. 6. New methods to modify energy efficiency measure and parameters in a single model.
Version 1.5.0: 7. API library is now supporting model download. Check out this script 8. Model upload support customize (.CSV) schedules. Check out this script 9. Supports hourly data extract from a single model. script 10. Support extracting a single table from HTML. script 11. Open 3D geometry viewer using API. script 12. Zone Load / Load component Extraction. script 13. Add post-processing functions - convert data to pandas dataframe, and utilize plotly for plotting.
Version 1.4.0 14. Initialize a simulation job / parametric job requires a project api key now. 15. User API key is deleted 16. Run function in simulation job supports multiple models submission. 17. Include more standard measures: Building orientation, overhangs, fins, roof absorptions, water heater, water usage, equipment power 18. Include more data retriving options at building level.
Installation
Prerequisites
- The BuildSimHub service, starting at the free level
- Python version 3.5 or 3.6, Python 2.7 is under-testing.
- If you wish to use the Built-in plotting function, you will then need the latest Plotly python package. The installation instruction can be found in here
Install Package
pip install BuildSimHubAPI
Setup environment
There are no requirements for regular users to access BuildSim Cloud besides a Python installation. However, for software vendors who would like to integrate the BuildSim Cloud, you can revise the vendor key in the info.config file.
Edit the info.config
vendor_id:[Your name]
If you decided to use BuildSim Cloud, please send your specific vendor id to us: weili.xu@buildsimhub.net.
Project key (required)
To activate a simulation through API client, you need to supply a project key - a key that helps BuildSim connect your local application to your project. The project key can be found in two places.
- Project list page: Simply click the "Copy Key" button and paste it in you application.
- In the project tab under every model: Under every model, search for project api key field in the project tab.
''' Example of how to innitialize API client ''' project_api_key = 'abcdef-ghijkl-mnopqrst' bsh = buildsimhub.BuildSimHubAPIClient() new_sj = bsh.new_simulation_job(project_api_key)
Model key (optional)
Some functions in the API library requires you to supply a
model_api_key. These functions allow you to update a model's history or retrieve the simulation results from a model under the specified project. The
model_api_key can be found in every model (highlighted in the figure below).
Quick Start
Hello BuildSim
from BuildSimHubAPI import buildsimhub ###############NOW, START THE CODE######################## bsh = buildsimhub.BuildSimHubAPIClient() new_sj = bsh.new_simulation_job('abcdef-ghijkl-mnopqrst') model = new_sj.run("/Users/weilixu/Desktop/5ZoneAirCooled.idf", track=True) print(model.net_site_eui())
The
BuildSimHubAPIClient creates a portal object that manages simulation workflow.
From this object, you can initiate a simulationJob to conduct a cloud simulation. Call
run() method with parameters can start the cloud simulation. The returned object is the model object, which contains full set of simulation results.
Quick start for Parametric simulation
import BuildSimHubAPI as bsh_api project_api_key = '8d0aa6f4-50c3-4471-84e6-9bd4877ed19a' file_dir = "/Users/weilixu/Desktop/data/UnitTest/5ZoneAirCooled.idf" bsh = bsh_api.BuildSimHubAPIClient() new_pj = bsh.new_parametric_job(project_api_key) # Define EEMs measure_list = list() wwr = bsh_api.measures.WindowWallRatio() wwr.set_min(0.3) wwr.set_max(0.6) measure_list.append(wwr) lpd = bsh_api.measures.LightLPD('ip') lpd.set_min(0.6) lpd.set_max(1.2) measure_list.append(lpd) heatEff = bsh_api.measures.HeatingEfficiency() heatEff.set_min(0.8) heatEff.set_max(0.95) measure_list.append(heatEff) # Add EEMs to parametric job new_pj.add_model_measures(measure_list) # Start! parametric = new_pj.submit_parametric_study_local(file_dir, algorithm='montecarlo', size=10, track=True) print(parametric.net_site_eui())
The parametric workflow requires user specified energy efficient measures. The full list of measures can be found in BuildSimHub wiki.
Roadmap
- We are working on a standard EEMs, which allows user to apply common energy efficiency measures to any IDF models. Open an issue if you did not see any desired EEMs in the standard EEM library!
- More simulation configurations and output results return will be added in the future!
- BuildSim Plot: This is the new project which we are integrating plotly package with our standard API library to provide the capability of visualizations.
- BuildSim Learn: This is a new project which we are working on integrating scikit-learn into the current workflow to enhance the parametric workflow.
- If you are interested in the future direction of this project, please take a look at our open issues and pull requests. We would love to hear your feedback.
About
buildsimhub-python is guided and supported by the BuildSimHub Developer Experience Team.
buildsimhub-python is maintained and funded by the BuildSimHub, Inc. The names and logos for buildsimhub-python are trademarks of BuildSimHub, Inc.
License
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/BuildSimHubAPI/1.6.8/ | CC-MAIN-2020-10 | refinedweb | 972 | 51.34 |
#include<iostream> #include<string> #include<cctype> using namespace std; int main() { string first, last, middle; char initial; cout<<"Enter your name: "; cin>>first; first[0] = toupper(first[0]); cin>>last; last[0] = toupper(last[0]); if (cin.peek() == '\n') { // no middle name } else { // middle name was read as last! //cout<<"What is your middle name?"; middle = last; cin>>last; middle[0] = toupper(middle[0]); initial = middle[0]; } cout<<"Your formal name would be: "<<last<<", "<<first; if (!middle.empty()) { cout<<" " <<initial; } cout<<".\n"; cout<<"Thank you for using the program!\n" "Stay warm!!\n"; return 0; }
This is what I have so far for my C++ name code.
I need to figure out how to do such followings
If user puts in "MARY AVERAGE USER", program returns "User, Mary A."
How do I change capital letters not including first letters to lower case?
And, I need to fix it so that it allows for correct capitalization of Mc and Mac names (lke McIntyre or MacTavish)
I need help1! please help me out!
Thank you so much
This post has been edited by jayman9: 22 April 2007 - 12:33 PM | http://www.dreamincode.net/forums/topic/27007-name-program-help-urgent/ | CC-MAIN-2016-44 | refinedweb | 188 | 75.71 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.