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
|
|---|---|---|---|---|---|
Hey guys! I am having problems with moving platforms in my 2D game and i can't figure out what is causing the issue.
I have a gameobject that is moved via script. It contains the actual platform. The platform itself has a box collider2d, a rigidbody2d (set to isKinematic) and a script attached to it. Objects that land on top of it are parented to the parent of the platform. All things are doing what i want them to do. If the player jumps onto the platform he is parented to the platform container, same goes for boxes. However if the player moves on the platform the movement is slower than usual. The player is moved using
float move = Input.GetAxis ("Horizontal");
myRigidbody2D.velocity = new Vector2(move*maxSpeed, ySpeed);
If i debug.log the velocity, the numbers are the same whether i walk on the platform or on normal ground but on the platform the player is only about half as fast.How the hell is that possible? What is going on?
------------------ EDIT -----------------------
so i am still going mad about this issue. I have found a way to move my objects with the platform without parenting them because i read on several threads that parenting to moving platforms is bad practise and can cause problems. The strange phenomenas are still happening though.If you want to look into any of my code i will gladly share it. At the moment my next guesses for a potential origin of the problem are:
a) The player movement is manipulated in the FixedUpdate of the characterController script (with Input.GetAxis and then setting the velocity) and in the update function of my platform-Script (with transform.Translate). However when i parented the player in my old approach i didnt manipulate the movement anywhere but in the player's FixedUpdate. In my platform script i only set a parent for it.
b) To detect wether or not the player is standing on the platform i am using OnCollisionEnter2D and OnCollisionExit2D. I am not sure how and why this would cause such an behaviour but i guess ill change this anyway since they do not seem to be called reliantly when the player hits the platform and i hope i can achieve a better result using raycasts.
I have already invested an incredible amount of time to get this fixed (around 20 hours of coding, testing, etc) so i hope i can get this fixed soon. Any help is highly apprecciated.
If you are using rigidbodies you shouldn't have to parent the object to the platform, but you do need to make the platform move and accelerate smoothly.
If i understand you correctly you suggest that i accelerate the platform at a speed where the player never loses contact to the platform (since the reason why i started parenting was that the player moved differently than the platform resulting in the player losing contact to the platform and falling back on it when moving down and the player kinda "vibrating" when moving up). However since i have different objects on the platform that can have different mass they are moving at different speed. Also i dont know which speed the platform will have in the end - it might be kinda fast. Won't this lead to problems when trying your approach? Also the player could jump while the platform is accelerating...
Answer by DavidWatts
·
Sep 08, 2016 at 09:21 PM
here is a script I wrote while trying this myself a while back just attach it to the player. hope this helps.
using UnityEngine;
using System.Collections;
public class SimpleCharacterController : MonoBehaviour {
Transform lastParent;
CharacterController character;
// Update is called once per frame
float cosSlopeLimit;
Vector3 platformVelocity;
void Start () {
character = GetComponent<CharacterController>();
lastParent = transform.parent;
cosSlopeLimit = Mathf.Cos( character.slopeLimit * Mathf.Deg2Rad );
}
void LateUpdate () {
if( transform.parent != lastParent && character.collisionFlags == CollisionFlags.None )
transform.SetParent( lastParent, true );
}
void OnControllerColliderHit ( ControllerColliderHit hit ) {
if( hit.gameObject.GetComponent<MovingPlatform>() ) {
if( hit.normal.y >= cosSlopeLimit )
transform.parent = hit.transform;
else if( transform.parent != lastParent )
transform.parent = lastParent;
}
else if( transform.parent != lastParent )
transform.parent = lastParent;
}
}
thank you for your answer.As it seems you are using a CharacterController on your character that i don't have so i can't attach it to my player since i dont have "collisionFlags" etc defined.However i found it interesting that you set the parent in LateUpdate instead of Update. I tried it out but it didnt seem to make a difference.I have now started to completly rewrite my character script and i wont make it physics based again. It's pretty sad that unity does not have a documented solution for something so basic as moving platforms im.
Player Movement Not Always Responding
1
Answer
How to move the player only 1 tile per buttonPress?
2
Answers
Boss AI Help in a 2D Platform game
0
Answers
Player loses momentum when landing
0
Answers
Unexpected symbol '=' parser error and Unexpected symbol '(' error
1
Answer
|
https://answers.unity.com/questions/1238599/weird-player-movement-when-parented-to-moving-plat.html
|
CC-MAIN-2020-10
|
refinedweb
| 834
| 55.74
|
Piroumian, Konstantin wrote:
>>Another thing is to use the Generator that Gianugo made that uses xpath to
>>make it possible to remove all book.xml files.
>
> Do you mean XMLDB generator? I'll take a look at it, never used it before.
> Do you think that xdocs contain enough data to be used for menu generation?
> I'll take a look at it too.
No, I think he was thinking about the (it's in scratchpad)
XPathDirectoryGenerator, which basically allows you to run an XPath
query on a set of documents.
However, Stefano is right pointing out the issue of automatic vs. manual
descriptors. I'm a bit biased towards the automatic solution, but it's
true that manual work tends to be more accurate (hmmm... stone in the
lake: how about a namespaced "book.xml" fragment in every document?).
Ciao,
--
Gianugo Rabellino
|
http://mail-archives.apache.org/mod_mbox/forrest-dev/200203.mbox/%3C3C8FD466.1010303@apache.org%3E
|
CC-MAIN-2014-42
|
refinedweb
| 143
| 67.35
|
Search Type: Posts; User: kinestetic
Search: Search took 0.01 seconds.
- 9 Apr 2015 3:22 AM
- Replies
- 7
- Views
- 959
Hi there! IntelliJ IDE plugin is awesome, but I have a question. How can I configure the app namespace?
E.g: I have a file with class name MyApp.view.AwesomeView. I move the file to...
- 4 Sep 2012 3:22 AM
- Replies
- 7
- Views
- 4,670
Works for me:
Project.js line 165
Project = Ext.extend(Object, {
constructor : function(projectFile, builder) {
},
//Adding -Dfile.encoding=UTF-8 key
getCompressor...
- 28 Jan 2012 12:45 AM
- Replies
- 7
- Views
- 3,024
Wonderfull! Now I can clear my map-render hooks . Thanks!
- 26 Jan 2012 10:15 PM
- Replies
- 7
- Views
- 3,024
May be 'maprender' event will be helpfull. Тo fire 'maprender' event, you need to set Ext.Map panel as active item in your tabpanel, after that you can set as active item something else. No need to...
- 24 Jan 2012 10:00 AM
- Replies
- 7
- Views
- 3,024
Function that does something with map (adding marker for example):
/* mappanel - Ext.Map instance*/
function addMarker(mappanel) {
var map=mappanel.getMap(),
position = new...
- 23 Jan 2012 9:20 PM
Jump to post Thread: Map tab problem using TabPanel by kinestetic
- Replies
- 12
- Views
- 2,434
alawibh, i can answer on your 1st question. As i saw, you launched your app on android. Google Android does not support controls, pinch, etc within Google Maps api v3. You can test it simply:...
- 24 Oct 2011 12:49 AM
- Replies
- 0
- Views
- 948
REQUIRED INFORMATION Ext version tested:
Ext 4.0.7
Ext 4.0.2
Browser versions tested against:
IE7
IE8
IE9
Description:
- 31 May 2011 9:23 PM
- Replies
- 322
- Views
- 220,055
That's great extension. Thanks. But I have a little problem.
When I'm adding a new marker to map, how can I add a custom CSS class to a marker? Or ID?
I need manipulate marker by JS. (I'm using...
- 5 Feb 2011 12:47 PM
- Replies
- 7
- Views
- 1,276
I have similar problems, my project is not only for touch devices. ie8 gives more than 10 errors runing the script, chrome or safari have only 1 but not critical
Results 1 to 9 of 9
|
https://www.sencha.com/forum/search.php?s=8156c759fe1efdaf881ab3fea5e013d6&searchid=11968228
|
CC-MAIN-2015-27
|
refinedweb
| 381
| 85.69
|
#include "opencv2/core/cvdef.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
#include "opencv2/core.hpp"
We represent a graph as a set of vertices. Vertices contain their adjacency lists (more exactly, pointers to first incoming or outcoming edge (or 0 if isolated vertex)). Edges are stored in another set. There is a singly-linked list of incoming/outcoming edges for each vertex.
Each edge consists of:
Two pointers to the starting and ending vertices (vtx[0] and vtx[1] respectively).
A graph may be oriented or not. In the latter case, edges between vertex i to vertex j are not distinguished during search operations.
|
https://docs.opencv.org/3.4/d0/dc2/core_2include_2opencv2_2core_2types__c_8h.html
|
CC-MAIN-2019-51
|
refinedweb
| 110
| 63.25
|
Details
Description
When generating Enveloping signatures in 1.4.5, they are invalid. These signatures worked in 1.4.4, but now do not work in 1.4.5
Activity
- All
- Work Log
- History
- Activity
- Transitions
The test is generating the signature using the org.apache.xml.security APIs, and validating the signature using the JSR 105 APIs (javax.xml.crypto).
It seems like a bug or interoperability issue between JDK 6 and Apache Santuario 1.4.5. I believe you are using JDK 6 right? If so, you are by default using the JSR 105 implementation from JDK 6 and not the one bundled with XMLSec 1.4.5. See my blog entry on how to use JDK 6 or later and override it with the JSR 105 implementation in Santuario:
When I tested with the JSR 105 implementation in Santuario 1.4.5 I did not see the problem.
I'll need to investigate this issue a bit more first to see what the problem may be, and whether it is in JDK 6 or Santuario. Possibly/probably some sort of a C14N issue.
I think it's an issue with Santuario 1.4.5. In our particular use case we're generating signatures with Java and verifying them with C++.
Your test sample seems to be problematic to begin with, you can't use xml as a namespace prefix unless it's defined to be what XML requires (it's reserved). I'm surprised it's parseable, but the bug may simply be a lack of proper error checking for that situation in one of the libraries.
In any case, I'd start by using something other than "xml" and see what happens.
I'll be the first to admit I'm a novice at best when it comes to XML and understanding namespaces, baseURIs and all other fun stuff it has. However, it seems as though that is the issue. Changing the XML in my test code to String xml = "<test><foo>bar</foo></test>"; results in valid signatures for both 1.4.4 and 1.4.5.
So I agree/think that it should probably not generate a signature for the XML if I've screwed it up and/or throw some kind of exception during signing or verification.
Thanks for the help though!
It's hard to say exactly what it should do, but I would suggest keeping this open for investigation into what layer is behaving oddly. I'm not really surprised the parsers are broken enough to accept this, and having done that, it's not likely we could or should be just refusing to sign it. The checking alone would add inefficiencies that other people shouldn't pay for.
As far as the bug, c14n handles the XML namespace (the one hardwired to that prefix) very particularly, and there's no such thing as an element in that namespace. So I'm sure there's just some code getting confused, and probably behaving differently in different implementations. But it would be good to know where.
It also may mean there's a regression somewhere involving c14n of the xml namespace declaration itself, which was an older bug.
Sample code that when run with 1.4.4 is valid, invalid in 1.4.5
|
https://issues.apache.org/jira/browse/SANTUARIO-278?attachmentOrder=desc
|
CC-MAIN-2016-40
|
refinedweb
| 552
| 64.61
|
Assert Exception Message in pytest
pytest() makes it easy to assert that an exception is raised and that it's the one you expect.
Prerequisites
Once we setup pytest, we get a nice assertion utility to verify that exceptions are raised.
For instance, in module
my_module.py with code:
def my_fn(): raise Exception('Kaboom')
We can write a test that expects the exception to be raised.
import pytest import my_module def test_exception_raise(): with pytest.raises(Exception) as exc_info: my_module.my_fn() assert str(exc_info.value) == 'Kaboom'
A
with block is used. Note the
as binding to
exc_info. This is of type
_pytest._code.code.ExceptionInfo. It has a member called
value, which is the actual
Exception. If we were raising a different type of
Exception, we would define that in the
raises parameter (eg,
pytest.raises(HttpException)). We cast the exception to a string to extract its message. We make the assertion on that message.
|
https://jaketrent.com/post/verify-error-message-pytest/
|
CC-MAIN-2022-40
|
refinedweb
| 154
| 61.22
|
Hi,
Right, so as for 1) this would be more for doing selections and trasformations that are quick
and trivial and that can't be done using something like XmlProperty to extract values.
2) is a bit trickier, so that would be details I'd look into. I'm a bit swamped with other
work but I'm going to poke around and see what I can see.
Thanks,
Andrew
Dominique Devienne <ddevienne@gmail.com> wrote: > how would people feel about having
inline XSLT
> in the ant file under the xslt task?
Yes, I thought about this too, but I don't think it's either practical nor easy.
(1) Not practical because XSL stylesheet tend to be rather big. Mixing
more than a minimal XSL with a build file will rapidly become unwieldy
IMHO.
(2) Not easy because XSL makes heavy use of XML namespaces, and this
will (a) either clash with Ant processing of XML NS, or (b) require
the use of a CDATA section of the XSL code, which would be ugly.
Maybe there's an XML NS-aware version of XmlFragment, I don't recall.
Stefan uses it I believe to have in-Ant NAnt builds, or something of
the like, so it might work and prove me wrong on (2), yet (1) remains.
That said, if you feel like doing it, go for it! ;-) --DD
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org
For additional commands, e-mail: dev-help@ant.apache.org
---------------------------------
Do you Yahoo!?
Get on board. You're invited to try the new Yahoo! Mail.
|
http://mail-archives.apache.org/mod_mbox/ant-dev/200609.mbox/%3C20060913201859.8282.qmail@web50802.mail.yahoo.com%3E
|
CC-MAIN-2017-22
|
refinedweb
| 264
| 82.44
|
When you first run
create-react-app, you’ll end up with a folder like this:.
Let me assure you right here and right now: there is no “one true way” to organize your files. Even better, you can completely screw it up – and through the magic of the
mv command and a little work changing some
import statements, your project will be just fine.
Don’t worry so much.
But I can tell. You don’t buy any of that. You’re still wondering what the best organization method is. Fine.
Before we go on, make sure you’re familiar with the idea of Presentational vs Container components (aka Smart vs Dumb).
Here’s the folder structure I recommend starting with, and it’s the one I always start with myself:
You can make this more granular over time, and move things around as you see fit, but let’s go over what’s here.
src/api.js- You’ll probably need to make calls to a backend API at some point. Put all that code here. If it gets too unwieldy in one file, make a
src/apidirectory and put the area-specific API files under there – like
userApi.js,
productApi.js, etc.
src/components- All your Presentational (aka Dumb) components go here. These are the simple stateless ones that just take props.
src/containers-.
src/images- Put the images in one place to start with.
src/index.js- This is where you initialize the app and call ReactDOM.render, so it makes sense to keep this at the top level.
src/utils- You’ll probably end up with miscellaneous utility functions – error handlers, formatters, and the like. I usually put them in a file inside utils so I can access them easily..
Easy Imports
Create React App supports the NODE_PATH variable for setting up custom import paths. That means you can turn this:
import Thing from '../../components/Thing'
Into this:
import Thing from 'components/Thing' // or even import Thing from 'Thing'
To enable this awesome power, all you need to do is open your
package.json file and look for this line:
"start": "react-scripts start",
And insert NODE_PATH like this:
"start": "NODE_PATH=src react-scripts start",
If you’ve got more than one path you can separate them with colons like
NODE_PATH=src:src/components:src/containers.
Testing
Jest supports NODE_PATH as well, and to make that work you’ll want to add
NODE_PATH to the test script like so:
"test": "NODE_PATH=src react-scripts test --env=jsdom",
One caveat: mocks may not work as expected until this issue is resolved.
Windows Support
Since Windows handles environment variables differently, you’ll need the
cross-env package to make this work. /ht to Dan Abramov for pointing this out.
Install it:
yarn add -D cross-env # or npm install -D cross-env
And then change the scripts to include it:
"start": "cross-env NODE_PATH=src react-scripts start", "test": "cross-env NODE_PATH=src react-scripts test --env=jsdom",
Redux
If your current level of comfort with React leads you to read articles about how to best organize your project, you probably do not need Redux yet. Learn React by itself first. It doesn’t have to be a full-on Semester of Study or anything – take a few days to learn React, and then go learn Redux.
When you add Redux to your project, start off with something like this:
src/redux/actions- Create a file for each set of related actions, like
userActions.js,
productActions.js, etc. I like to bundle action creators and the related action constants in the same file.
src/redux/reducers- Create a file for each reducer, and an
index.jsin here to contain the “root” reducer.
src/redux/configureStore.js- Create and configure the store here. You can just
import rootReducer from './reducers'.
If you hate having to jump between files to create an action, check out the Ducks pattern where a reducer + related actions + types are all contained in a single file.
Another Way
An alternative is to organize files by “functional area” rather than “kind”, with folders like
users,
products, and
profile. The
users folder might contain
UserDetailPage.js and
UserListPage.js.
This organization style starts off deceptively simple. Inevitably you end up with a folder like
common to hold the
Button.js and
Icon.js. And then you might want
common/containers and
common/components. At some point it grows out of control, with directories 3 levels deep, and now whenever you have to create a new file you break out into a full sweat. WHERE SHOULD IT GO?!!
Simple is better. Start simple. Keep it simple, if you can.
In Summary
- To start off, organize your project something like the screenshot above
- Tweak it as you need to (don’t stress about getting it perfect on day one)
- Err on the side of fewer folders and fewer levels of nesting until the flat structure becomes a problem.
For a step-by-step approach to learning React,
|
https://daveceddia.com/react-project-structure/
|
CC-MAIN-2017-51
|
refinedweb
| 839
| 64.1
|
Support HTML in consent requirement descriptions
Review Request #9965 — Created May 22, 2018 and updated
Instead of juggling
mark_safevs
mark_safe_lazyand
ugettextvs
ugettext_lazyand string interpolation, we now have a flag on the
BaseConsentRequirementthat indicates whether or not the description
fields are HTML (in which case they will be rendered as-is and marked
safe) or text (in which case they will be wrapped with
<p>tags). This
allows the rendering code (which is handled by a new
render_{field}_descriptionmethod that can be overridden in a pinch to
specialize its behaviour) instead of naively by the template.
Used this with
I mentioned this in a change making use of this, but it applies here.
I don't think we should require that text be set in the subclass to start with
<p>if
is_htmlis
True. That should be handled here if no tags are present. In fact, we can go a step further and simplify this code in the process, and break the logic out so it's not duplicated.
def _render_text(self, text, is_html): if is_html: text = mark_safe(text) text = conditional_escape(text) if not text.startswith('<') and not text.endswith('>'): text = format_html('<p>{0}</p>', text) return text
This way,
<p>is applied for the plain text case, and for the HTML case if outer tags aren't already present.
It also properly handles safe text that's coming in (which allows the existing form we have where
mark_safeis called -- honestly, we need to ship this code fast so I don't want to redo all the consent requirements again, and handling the existing case is going to be helpful there).
|
https://reviews.reviewboard.org/r/9965/
|
CC-MAIN-2019-09
|
refinedweb
| 271
| 62.82
|
On Fri, 27 Aug 2004 00:53:51 +1000, Anthony Baxter <anthonybaxter at gmail.com> wrote: >On Thu, 26 Aug 2004 14:40:18 GMT, Arthur <ajsiegel at optonline.com> wrote: >> >IMO, to change it inside of a function def should be (but isn't) as easy >> >as... >> > >> > >>> def foo(): >> > ... """ I am foo """ >> > ... __doc__ = __doc__ + 'indeed' >> > >> >Paul >> >> Yes. Not only do I follow, but I think we came to exactly the same >> place, from very different directions, and coming from what I sense is >> very different backgrounds. >> >> Its just that I don't think many others seem to find that as >> interesting as I happen to. > >Not so much that, as running out of ways to restate myself. The >proposed syntax above still requires magic handling of double-under >variables in a function, and a new namespace. I can't see how you can >think that this is a _good_ thing. Googling on "function namespace" is interesting. Subject to my interpretation of what I am accessing: Common Lisp has 'em, Scheme don't. Talked about a lot in the context of XML in ways I am not sure are relevant. Nested scopes is the beginning of their introduction into Python - as I am reading a cite from Dive Into Python. So of course what I have been driving at all along, is some extension to the the nested scope mechanism. Yes. I'm talking through my backside. Darts at the wall language design, I call it. Art
|
https://mail.python.org/pipermail/python-list/2004-August/289587.html
|
CC-MAIN-2016-50
|
refinedweb
| 247
| 82.85
|
dave: > On Tue, Apr 22, 2008 at 11:57 AM, Aaron Tomb <atomb at galois.com> wrote: > > > > On Apr 22, 2008, at 6:20 AM, John Goerzen wrote: > > > > > > > > > * xml > > > > A simple, lightweight XML parser/generator. > > > > > > > > > > > > > > > > > > Can you describe how this compares to HaXml? Were there deficiencies in > > > HaXml? > > > > > > > The main difference is that it's simpler. It's perhaps 10-20% the size of > > HaXml. For a program that just has to do simple XML processing, it's > > sometimes undesirable to have to link in a library that does a lot more than > > you need. > > It would be convenient to have a list of unsupported XML features. The > ones I've noticed so far are > > * doctypes (and all doctype-related markup) > * processing instructions > * notations > > Comments are recognized but not preserved, so you can't round-trip a > document containing them. > > (Personally, I use namespaces more than I use any of these, which is > why I don't use HaXml.) > I've created a wiki page to start on community documentation for the light xml library, Feel free to add text, examples, etc there -- Don
|
http://www.haskell.org/pipermail/haskell-cafe/2008-April/042065.html
|
CC-MAIN-2014-23
|
refinedweb
| 184
| 72.66
|
Section Problems Number 6 - Recursion
Be prepared to discuss these problems in discussion section.
1. What is the output of
csc(5)?
public void csc(int n){
if( n <= 0 )
System.out.println( "done" );
else {
System.out.println( n );
csc( n - 1);
}
2. What is the output of
System.out.println( disc(7) );
public int disc(int x){
int result = 0;
if( x <= 2)
result = 3;
else
result = x / 3 + disc( x - 2 );
return result;
}
3. What is the output of
lotto( 5 ) ?
public void lotto( int n ){
if( n == 0 )
System.out.prinltn( "There");
else{
System.out.prinltn( "Here");
lotto( n - 2 );
}
4. What is the output of
gas("Curious George");
public void gas(String s){
if( s.length() > 0 ){
System.out.print( "" + s.charAt(0) + s.charAt( s.length() - 1);
gas( s.substring(1, s.length() );
System.out.print( "" + s.charAt(0) + s.charAt( s.length() - 1);
}
}
5. What is the output of
System.out.println( make("001230") );
public static String make(String input){
String rest = "";
if( input.length() > 0 ){
rest = make( input.substring( 0, input.length() - 1 ) );
char c = input.charAt( input.length() - 1 );
if( c == '0' )
rest = "A" + rest;
else if( c == '1' )
rest = "B" + rest + "B";
else if( c == '2' )
rest = rest + "C";
}
return rest;
}
6. Consider method
make from question 5. What value must be
passed in for input so that make returns the String "ABACAB"?
7. Rewrite method
make from question 5 so that it is iterative
(uses a for or while loop) instead of recursive.
8. Rewrite the following method so that it is recursive instead of iterative.
public int max(int[] list){
int max = list[0];
for(int i = 1; i < list.length; i++)
if( list[i] > max )
max = list[i];
return max
}
Hint: It is much easier if you write a recursive helper and call it from max.
public int max(int[] list){
return maxOfPortionOfList(list, 0);
}
private int maxOfPortionOfList(int[] list, int pos)
{ //base case. When is it very simple to get the max of a list
// you complete this
}
9. What is the output of
System.out.println( f(7) );
//pre: n >= 1
public int f(int n)
{ if( n == 1 || n == 2)
return 1;
else
return f(n-1) + f(n-2);
}
10. Execute the following code class. It makes use of the Stopwatch class from the assignments.
public class SP06 {
public static void main(String[] args) {
Stopwatch s = new Stopwatch();
final int LIMIT = 45;
int result;
for(int i = 1; i <= LIMIT; i++){
s.start();
result = f(i);
s.stop();
System.out.println("value of f(" + i + ") = " + result + ". Time to calculate: " + s);
}
}
public static int f(int n){
if( n == 1 || n == 2)
return 1;
else
return f(n-1) + f(n-2);
}
}
How long does it take to the program to calculate f(20), f(30), f(40), f(44), f(45). How long do you think it will take the program to calculate f(46)? f(50)? f(100)?
What do you think the Big O of method f is?
Rewrite method f so it is iterative with a Big O no worse than O(N).
11. Flood fill. Write a method to simulate the flood fill option on many graphics programs. A window will be represented as an 2D array of integers where the integers represent different colors. Floodfill will be passed a 2D array of integer as well as the row and column to start filling from and the color to change to. The method should branch out from this position (up, down, left, and right, but not diagonally) and change all squares equal to the original one to the new color:
public void floodfill(in[]][] canvas, int row, int column, int newColor)
If canvas is equal to the matrix below:
and row = 4, column = 2, and newColor = 33 the resulting matrix would be
Complete method floodfill using recursion.
12. Write a method that recursively determines
the number of different ways to roll a particular number on a given number of
dice:
/*
pre: numDice > 0
post: return the number of different ways to roll numToRoll
with numDice dice. Assume each die has sides numbered 1 to 6.
*/
public int waysToRoll(int numToRoll, int numDice)
All dice have six sides. For example if the methods was called as follows:
System.out.println( waysToRoll(4,2) );
The output would be 3.
Thus with 2 dice there are 3 combinations that add up to 4. Note even though the first 2 both have a 3 and a 1 they are considered different combinations of rolls.
Another example:
System.out.println( waysToRoll(5,3) );
The output would be 6:
After implementing a recursive solution implement a non recursive solution.
|
http://www.cs.utexas.edu/~scottm/cs307/handouts/SectionProblems/SectionProblems6Recursion.htm
|
CC-MAIN-2016-26
|
refinedweb
| 783
| 75.1
|
You can subscribe to this list here.
Showing
7
results of 7
On windows if you want to run a python file as a cgi with apache you must use a different extension other then .py, co .cgi works best. Also remember to use the #! to correctly point to your python exe since apache uses it to run cgi's. <br>
<br>
But if you are on windows and you are using apache why are you using the cgi method? why not use the webkit.dll? I have been using Webware with apache on windows for quite a while not and find that this is the most stable approach<br>
<br>
Jose<BR><BR><br>
<BLOCKQUOTE style="PADDING-LEFT: 8px; MARGIN-LEFT: 8px; BORDER-LEFT: blue 2px solid"><BR>-------- Original Message --------<BR>Subject: Re: [Webware-discuss] [newbie] Installed, compiled server: <BR>"Hello World" ?<BR>From: "Frederic Faure" <ffaure@...><BR>Date: Mon, July 21, 2003 7:09 am<BR>To: "Webware discuss" <webware-discuss@...><BR><BR>At 10:01 21/07/2003 -0400, Aaron Held wrote:<BR>>You can use WebKit.cgi, you just have to make sure that Apache can run <BR>>python cgi's. If python is registered you may be able to just change the <BR>>extension from .cgi to .py<BR><BR>Thx for the tip. I'm currenly using Sambar on an NT box just for testing, <BR>but I'll probably switch to Apache later.<BR><BR>>ps. to go from main just pass three lights and make a left.<BR><BR>Got it ;-)<BR><BR>Thx<BR>Fred.<BR><BR><BR><BR>-------------------------------------------------------<BR>This SF.net email is sponsored by: VM Ware<BR>With VMware you can run multiple operating systems on a single machine.<BR>WITHOUT REBOOTING! Mix Linux / Windows / Novell virtual machines at the<BR>same time. Free trial click here:<BR>_______________________________________________<BR>Webware-discuss mailing list<BR>Webware-discuss@...<BR> </BLOCKQUOTE>
Hello ,
How should we support the Source Code Encodings from Python 2.3 in PSP
files. Adding a new directive ? Is anything like this already
implemented ?
Best regards,
Lothar mailto:llothar@...
Tripp Lilley wrote:
>
> I think this is definitely a case where the instance pooling
> algorithm is getting in the way of the threading vs. non-threading
> philosophy discussion. What I mean is, the fact that the pool is
> currently a static number of instances -should- be regarded as an
> implementation detail subject to change, and that change should be to
> introduce a dynamic pooling algorithm. This is true of DBPool and,
> well, every pooling mechanism :)
>
> So, in case it wasn't clear, the pool should increase its size to
> accomodate instantaneous demand and then trim itself back down to a
> reasonable size when the demand subsides.
>
> It's actually easier to implement this than it sounds... When a
> request comes in for a pool object, the pool looks for an existing
> instance. If there are no existing instances, it doesn't
> -immediately- create one. Rather, it waits a specified time for an
> existing instance to become available, and, if not, -then- creates a
> new one. This puts an upper bound on the time a client will have to
> wait for a handler. This timeout is pretty easy to implement using a
> lock.wait(timeout) call on a lock that represents instance
> availability in the pool's internal queue.
>
> Discarding extra pool instances is left as an exercise to the reader
> :)
I'm not conviced that a dynamic algorithm is better than just using a fixed
pool (assuming we're talking about threads, or servlet instances). Your box
has to have enough memory and horsepower to handle the worse case of a
maxed-out pool, right? If that's the case, then why not just allocate the
maximum right up front (or let the pools grow as needed like the servlet
pools)? Surely having some extra threads or extra instances lying around
doesn't noticeably hurt performance. Also, having to allocate extra
instances or threads to handle a surge of activity is bound to be somewhat
costly just at the time when you need the CPU to actually _handle_ the
requests.
When I deploy WebKit I set the minimum, maximum, and initial thread pool
sizes to the same value. Can someone convince me why this is a bad idea?
- Geoff
At 10:01 21/07/2003 -0400, Aaron Held wrote:
>You can use WebKit.cgi, you just have to make sure that Apache can run
>python cgi's. If python is registered you may be able to just change the
>extension from .cgi to .py
Thx for the tip. I'm currenly using Sambar on an NT box just for testing,
but I'll probably switch to Apache later.
>ps. to go from main just pass three lights and make a left.
Got it ;-)
Thx
Fred.
You can use WebKit.cgi, you just have to make sure that Apache can run
python cgi's.
If python is registered you may be able to just change the extension
from .cgi to .py
-Aaron
ps. to go from main just pass three lights and make a left.
Frederic Faure wrote:
>.
>
>
>
> -------------------------------------------------------
> This SF.net email is sponsored by: VM Ware
> With VMware you can run multiple operating systems on a single machine.
> WITHOUT REBOOTING! Mix Linux / Windows / Novell virtual machines at the
> same time. Free trial click here:
> _______________________________________________
> Webware-discuss mailing list
> Webware-discuss@...
>
--
-Aaron
"I don't know what's wrong with my television set. I was getting
C-Span and the Home Shopping Network on the same station.
I actually bought a congressman."
- Bruce Baum
Aaron Held wrote:
> I too am on the make my own blog bandwagon.
>
> For this type of information you have many choices
>
> Easy: Use Cheetah to render your pages,
> Somthing like:
>
> #cache <ul>
> #for $blog in $blogroll
> <li><a href="$blog.url">$blog.title</a></li>
> #end for
> </ul>
> #end cache
>
> Flexable
> Cache it in yout module, use a module level variable to hold the data
> and use TaskKit to update it.
nice one.
i known cheetah but i was resistant to use it, but now i'm starting
to see the benefits. in the current cheetah-less implementation i filled
my base servlet with:
def writeHeader(self):
self.writeln('<html>...') # lots of HTML code
writeFooter():
self.writeln('<div>...') # lots of HTML code
but i wonder that i can use a cheetah TMPL file to store
the markup for layout of the site.
recently in the cheetah ML i saw this interesting example:
from WebKit.Page import Page
class baseservlet(Page):
"""This class adds links Webware servlets to Cheetah templates.
It includes the logic to generate its HTML content by finding a Cheetah
template
with the same name as this class plus the '_tmpl.tmpl' suffix.
(This template has been previously complied into a python module 'named
servletname_tmpl')
It imports that template, registers itself as the template's servlet
(containing the business logic the template may need), and then renders
the template by calling its respond method and passing the resulting
HTML string to the writeln() method."""
def writeHTML(self):
#print ">> baseservlet.writeHTML()"
tmpl = self.template()
tmpl.servlet = self
self.writeln(tmpl.respond())
def template(self):
templateName = self.__class__.__name__ + '_tmpl'
importLine = 'from %s import %s as template' % (templateName,
templateName)
exec(importLine)
return template()
def hasUser(self):
return self.session().hasValue('user')
i'm trying to guess here, but if i understand correctly basically here
an external TMPL is imported dynamically in the servlet using its name
to lookup the right template fiel. a "baseservlet" subclass implements
per-page servlet logic and set itself as ref servlet. i'm wondering if
there's a more elegamnt way to dynamically import a class, that
exec(importLine) seems a bit brutal to me :)
i stil have to try this, but seems a smart approach.
later,
deelan.
|
http://sourceforge.net/p/webware/mailman/webware-discuss/?viewmonth=200307&viewday=21&style=flat
|
CC-MAIN-2015-48
|
refinedweb
| 1,310
| 65.22
|
----- Original Message ----- From: <Martin_Doering@mn.man.de> To: Multiple recipients of list <lua-l@tecgraf.puc-rio.br> Sent: Monday, August 28, 2000 4:30 PM Subject: Re: Re: Antwort: global keyword instead of local > Erm... could you be a little bit more verbose? O don't know python... What > do I see here? I understand the function definition, but what about the > stack trace? > Oh -- sorry about that... :)) Function definition: def f(): i = i+1 Now, we define a global variable: i = 1 If we now try to call f(), we will get an error, since i does not exist in the local namespace of f. That's all. If we wanted f() to work, we would have to write: def f(): global i i = i+1 Quite the opposite of Lua, I guess. :) -- Magnus Lie Hetland (magnus at hetland dot org) "Reality is what refuses to disappear when you stop believing in it" -- Philip K. Dick
|
https://lua-users.org/lists/lua-l/2000-08/msg00097.html
|
CC-MAIN-2020-45
|
refinedweb
| 158
| 75
|
Share code with Add as Link
August 06, 2014
Applies to: Windows Phone 8 and Windows Phone Silverlight 8.1 | Windows 8
This topic describes how to share code between multiple projects using Add as Link available in Visual Studio, and how to leverage this technique when building an app to run on Windows Phone 8 and on Windows 8.
This topic contains the following sections.
In Visual Studio you can use the same file in multiple projects, without copying the file to each project. For example, in the following diagram, two projects share the same class, SharedClass.cs.
You can use this simple but powerful code sharing strategy to create a file or code asset once and then share it with multiple projects. Apart from being linked to your project, the file or acts like any other file in your project. When you edit the file, the changes are applied to all projects that link to the file.
You can use this code sharing technique when you are building your app to run on Windows Phone 8 and on Windows 8. Depending on the type of app you are creating, you’ll have some opportunity to share code this way across your projects. This is particularly useful when you’re trying to share code that isn’t portable, which is code can’t be shared inside a Portable Class Library. Windows Runtime APIs are not portable and can’t be used in a Portable Class Library. However, Windows Phone 8 and Windows 8 share a subset of Windows Runtime API, and you’ll probably want to try to write against this API once, and then share the logic in both apps. For more info about the Windows Runtime APIs that are common to Windows Phone and Windows 8, see Windows Phone Runtime API. The following diagram illustrates how you might share code by linking the file to multiple projects.
In this example, we have a Windows Phone 8 project and a Windows 8 project. The class SharedClass.cs contains code that isn’t portable, but is written using API common to Windows Phone 8 and Windows 8. We can share this class by adding it as a link to each project. By doing this, we’re writing code once and using it multiple times. We’ve abstracted the common, non-portable code into shared classes and each app project contains code and functionality that is specific to the app.
In general, you can use this technique for any code you’re able to isolate that’s platform-independent and used in both apps. Good candidates for this kind of sharing include, but are not limited to, the following scenarios.
App logic common to both apps, but not portable. In Windows Phone 8 and Windows 8, a lot of infrastructure code, or code that interacts with the operating system or external data sources, can be written using Windows Runtime API. Because Windows Phone 8 has adopted a subset of Windows Runtime, it’s possible to write code that uses this functionality once, and then share it across your apps. For example, both platforms have the same Windows Runtime API for networking, sensors, location, in-app purchase, and proximity. There’s significant overlap in these API on both platforms. This code can’t be placed in a Portable Class Library because it’s not portable. The .NET Framework portable libraries don’t support Windows Runtime. Instead, you can isolate the use of these APIs to classes in your app and share as linked code files in both your Windows Phone 8 and Windows Store app. If you’re using the free, Express versions of Visual Studio, you won’t be able to create Portable Class Libraries. In this case, you should use this code sharing technique to share your app logic. For example, apps that have been built using the Model-View-ViewModel (MVVM) pattern could share the model and viewmodel of you app.
User controls with no platform dependencies. Windows Phone 8 and Windows 8 both enable you to create rich user experiences using XAML. They implement this layer differently and have also defined the API in different namespaces. However, this divergence is not insurmountable. In fact, a lot of the functionality, types, and members are named the same between the platforms, and behave the same way. Although the overriding guidance is to build the best user experience as possible for each platform, there may be cases when you can extract elements of your UI that are common to both, write it once, and share with both apps. It isn’t possible to conditionally compile XAML, so the UI that’s defined in a shared user control must be platform independent. You can use conditional compilation in your code-behind class of the user control, so this offers some flexibility.
This is a simple way to write code once and share between your projects. For info about handling platform differences in your code, see Handling Windows Phone 8 and Windows 8 platform differences.
You link to a file from your project in Visual Studio.
In Solution Explorer, right-click your project, and then select Add Existing item Or, you can type Shift+Alt+A.
In the Add Existing Item dialog box, select the file you want to add, and in the Add drop-down list, click Add As Link.
The file will be added your project as a linked file, which means it isn’t physically copied to the project, but instead just linked to it. A linked file will have a different icon than a file that was physically added to a project.
Shared
Not Shared
You can follow this procedure to link multiple files to your project. If you accidentally add a file to your project when you meant to add it as a link, make sure to delete the file from the project and from the project's folder on the disk before trying again to add it as a linked file.
|
http://msdn.microsoft.com/es-es/library/jj714082
|
CC-MAIN-2014-35
|
refinedweb
| 1,005
| 69.11
|
Talk:Tag:amenity=kneipp water cure
From OpenStreetMap Wiki
(Redirected from Talk:Tag:leisure=foot bath)
leisure=* ?
Shouldn't this be a leisure tag? --AndiG88 (talk) 10:10, 29 July 2014 (UTC)
- Probably not. “amenity” is defined as “Covering an assortment of community facilities including toilets, telephones, banks, pharmacies and schools.”. People don't neccessarily use a Kneipp basin just for personal enjoyment. The main idea/intention is to use it to improve/maintain one's health. Water-treading is part of some sort of therapy (“Kneippkur” in German). So amenity might be actually preferred here for the same reason that amenity=hospital is used. --Wuzzy (talk) 19:29, 11 April 2015 (UTC)
- So it should be better placed into the healthcare system. --Polarbear w (talk) 08:57, 21 June 2016 (UTC)
- In my opinion is "amenity" a good namespace. There are people who use such facilities for their own health and other for personal enjoyment. --JIDB (talk) 19:44, 21 June 2016 (UTC)
More generic term
This tag should be more generic and not almost exclusive to Germany or any other country. In a generic tag we could have these specific tags. It seems it was a bit discussed in the proposal talk page but it was just that (see Talk:Proposed_features/Extending_kneipp_water_cure#Use_more_generic_term_than_kneipp_water_cure.3F). See also Key:healthcare and healthcare:speciality=hydrotherapy. Zermes (talk) 15:01, 10 October 2016 (UTC)
- A more generic tag could be nice, but we would need someone who knows a lot about all possible hydrotherapy amenities and would like to make a tagging proposal. Do you have any concrete examples, that would would put in the same category? We must also take into account, that the Kneipp water cure amenities usually exist on their own (outdoors and without any other therapy installation nearby) and are not only used for healthcare but also for leisure.
|
http://wiki.openstreetmap.org/wiki/Talk:Tag:leisure%3Dfoot_bath
|
CC-MAIN-2017-22
|
refinedweb
| 311
| 55.34
|
ok frnds i got the solution thnks for your reply..
thnks,........
ok frnds i got the solution thnks for your reply..
thnks,........
so what is the float value
hello frnds i have some problem in this code can you solve this my issue and pls tell me whats the issue in this progrma
public class App {
public void print(int i) {
...
hello frnds,
please can you tell me the ans. of my this Q.
Is there any way to capture/record from "Wave Out Mix" or "Stereo Mix" in Windows7/Vista?:-/
hello frnds,
can u tell me
how to record speaker output using cmd ?
thnks in advance:cool:
can anybody tell me the solution of this problem
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/jna/Platform
--- Update ---
problem is solved...........
|
http://www.javaprogrammingforums.com/search.php?s=7d86d368e0734f7f1916fd8b953fc221&searchid=784475
|
CC-MAIN-2014-10
|
refinedweb
| 132
| 74.49
|
Serve static files directly from a WSGI application
Project Description
WhiteNoise
Radically simplified static file serving for Python web apps.)
It’s designed to work nicely with a CDN for high-traffic sites so you don’t have to sacrific performance to benefit from simplicity.
WhiteNoise works with any WSGI-compatible app but has some special auto-configuration features for Django.
WhiteNoise takes care of best-practices for you, for instance:
- Serving gzipped content (handling Accept-Encoding and Vary headers correctly)
- Settting far-future cache headers on content which won’t change
Worried that serving static files with Python sounds like a terrible idea? Have a look at the Infrequently Asked Questions below.
QuickStart for Django apps
Edit your wsgi.py file and wrap your WSGI application like so:
from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application)
Add this to your settings.py:
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
For more details, including on setting up CloudFront and other CDNs see the Using WhiteNoise with Django guide.
QuickStart for other WSGI apps/')
For more details see the full documentation.
Compatibility
WhiteNoise works with any WSGI-compatible application and is tested on Python 2.7, 3.3 and 3.4
DjangoWhiteNoise is tested with Django versions 1.4 — 1.7
Endorsements
WhiteNoise is being used in Warehouse, the in-development replacement for the PyPI package repository.
Some of Django and pip’s core developers have said nice things?”
Issues & Contributing
Raise an issue on the GitHub project or feel free to nudge @_EvansD on Twitter.
License
MIT Licensed
Infrequently Asked Questions
Isn’t serving static files from Python horribly inefficient? determing?
No, you shouldn’t. The main problem with this approach. everythig.
Release history Release notifications
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/whitenoise/1.0.1/
|
CC-MAIN-2018-17
|
refinedweb
| 312
| 50.53
|
I am currently making a code review software called vym.
Vym allows you to create a slide deck based on a Pull Request that you can present in real-time. It is a new way of reviewing code.
Edit 05/11/2016
I have launched Vym some time ago and I am moving away from the project. You can read why in this article.
Instead of building it in a secrecy, I would like to incrementally release until I am close to the launch.
I am frequently releasing my progress on the sandbox version on vym.io. You can try vym over there!
Why do we need a new way?
The main problem that I am trying to solve is that GitHub’s Pull Request interface is not suitable for large changes or code presentation.
If there are 30 files changed in your PR, presenting it to your team is a nightmare because you have to scroll up and down constantly. There is no way to organize the files.
I have actually already shipped an app to address this problem on September last year. it was called Coddee. You can read more about it on my past blog post Making Coddee.io.
So why am I building a vym while abandoning Coddee? It is because I realized that we need a new way. Let me explain.
After shipping Coddee, I was proud of it. But I could not use it unless I forced myself to do so. It was not a pleasure to use.
I think the reason was because Coddee was merely a simple improvement to the existing solution. In order for people to ditch the GitHub’s interface and use Coddee, Coddee needed to be at least, say, 10 times better. Simply put, we are reluctant to switch from one solution to another if the latter is only a little bit better.
I also documented this thought on this blog post.
All in all, to solve the problem of inefficient code review process, a completely new medium is needed.
Okay, show me the money.
The above picture is what vym looks like at the moment in the sandbox version. The picture shows a ‘wizard’ view in which you can edit slides.
I put previews on the left hand side, and the main view on the right.
When you present, you can simply have all your teammates point their browser to the unique url for the slide deck, and present it in real time (i.e. when you navigate throught the slides, their screens will get updated reactively).
Here is what a live presentation mode looks like:
Note that you can add not only files, but also texts. This feature helps you explain your code better.
What is the tech stack?
I am using Meteor as a full stack framework. The view layer is React. Meteor makes it a breeze to make the presentation real-time. It actually works that way out of the box.
The development experience has been a pleasure, largely because Meteor 1.3 supports the native ES6 module system. The module support makes it easy to write and use React components.
For instance, you can write your component like the following:
import React from 'react'; const Header = ({currentUser, logout, login}) => ( ... ); export default Header;
And you can use it anywhere in your app by importing it.
Also, I am following Mantra to structure my application. It is a project that recently launched to give a more opinionated and solid structure to Meteor application by taking advantage of native ES6 module support.
I wrote the official command line interface for Mantra, and have been actively using it while developing. I love it. I guess you could say that I am eating my own dog food.
By the way, here is the repo for the CLI if anybody is interested in using it. I also wrote a blog post about how I made it.
Ending
I will be frequently releasing my progress on the sandbox version. Also I will write blog posts on vym’s official blog. when I release major features, or just for the heck of it when I feel like doing so. :)
The best way to follow all the updates is probably on vym’s official Twitter account @vym.
By and large, my goal this time is to end up with something that I would actually use daily.
|
https://sung.io/i-am-making-vym/
|
CC-MAIN-2018-51
|
refinedweb
| 733
| 75.3
|
Patchwork Plaid — A modularization story
How and why we modularized Plaid and what’s to come
This article dives deeper into the modularization portion of Restitching Plaid.
In this post I’ll cover how we refactored Plaid away from a monolithic universal application to a modularized app bundle. These are some of the benefits we achieved:
- more than 60% reduction in install size
- greatly increased code hygiene
- potential for dynamic delivery, shipping code on demand
During all of this we did not make changes to the user experience.
A first glance at Plaid
Plaid is an application with a delightful UI. Its home screen displays a stream of news items from several sources.
News items can be accessed in more detail, leading to separate screens.
The app also contains “search” functionality and an “about” screen. Based on these existing features we selected several for modularization.
The news sources, (Designer News and Dribbble), became their own dynamic feature module. The
about and
search features also were modularized into dynamic features.
Dynamic features allow code to be shipped without directly including it in the base apk. In consecutive steps this enables feature downloads on demand.
What’s in the box — Plaid’s construction
Like most Android apps, Plaid started out as a single monolithic module built as a universal apk. The install size was just under 7 MB. Much of this data however was never actually used at runtime.
Code structure
From a code point of view Plaid had clear boundary definitions through packages. But as it happens with a lot of codebases these boundaries were sometimes crossed and dependencies snuck in. Modularization forces us to be much stricter with these boundaries, improving the separation.
Native libraries
The biggest chunk of unused data originates in Bypass, a library we use to render markdown in Plaid. It includes native libraries for multiple CPU architectures which all end up in the universal apk taking up around 4MB. App bundles enable delivering only the library needed for the device architecture, reducing the required size to around 1MB.
Drawable resources
Many apps use rasterized assets. These are density dependent and commonly account for a huge chunk of an app’s file size. Apps can massively benefit from configuration apks, where each display density is put in a separate apk, allowing for a device tailored installation, also drastically reducing download and size.
Plaid relies heavily on vector drawables to display graphical assets. Since these are density agnostic and save a lot of file size already the data savings here were not too impactful for us.
Stitching everything together
During the modularization task, we initially replaced
./gradlew assemble with
./gradlew bundle. Instead of producing an Android PacKage (apk), Gradle would now produce an Android App Bundle (aab). An Android App Bundle is required for using the dynamic-feature Gradle plugin, which we’ll cover later on.
Android App Bundles
Instead of a single apk, AABs generate a number of smaller configuration apks. These apks can then be tailored to the user’s device, saving data during delivery and on disk. App bundles are also a prerequisite for dynamic feature modules.
Configuration apks are generated by Google Play after the Android App Bundle is uploaded. With app bundles being an open spec and Open Source tooling available, other app stores can implement this delivery mechanism too. In order for the Google Play Store to generate and sign the apks the app also has to be enrolled to App Signing by Google Play.
Benefits
What did this change of packaging do for us?
Plaid is now more than 60 % smaller on device, which equals about 4 MB of data.
This means that each user has some more space for other apps.
Also download time has improved due to decreased file size.
Not a single line of code had to be touched to achieve this drastic improvement.
Approaching modularization
The overall approach we chose for modularizing is this:
- Move all code and resources into a core module.
- Identify modularizable features.
- Move related code and resources into feature modules.
The above graph shows the current state of Plaid’s modularization:
:bypassand external
shared dependenciesare included in core
:appdepends on
:core
- dynamic feature modules depend on
:app
Application module
The
:app module basically is the already existing
com.android.application, which is needed to create our app bundle and keep shipping Plaid to our users. Most code used to run Plaid doesn’t have to be in this module and can be moved elsewhere.
Plaid’s
core module
To get started with our refactoring, we moved all code and resources into a
com.android.library module. After further refactoring, our
:core module only contains code and resources which are shared between feature modules. This allows for a much cleaner separation of dependencies.
External dependencies
A forked third party dependency is included in core via the
:bypass module. Additionally, all other gradle dependencies were moved from
:app to
:core, using gradle’s
api dependency keyword.
Gradle dependency declaration: api vs implementation
By utilizing
api instead of
implementation dependencies can be shared transparently throughout the app. While using
api makes our dependencies easily maintainable because they are declared in a single file instead of spreading them across multiple
build.gradle files this can slow down builds.
So instead of our initial approach we reverted to
implementation, which requires us to be more explicit about the dependency declaration but tends to make our incremental builds faster.
Gradle figures out where stuff is needed and where to place code in the app bundle. This also can make incremental…github.com
Dynamic feature modules
Above I mentioned the features we identified that can be refactored into
com.android.dynamic-feature modules. These are:
:about
:designernews
:dribbble
:search
Introducing com.android.dynamic-feature
A dynamic feature module is essentially a gradle module which can be downloaded independently from the base application module. It can hold code and resources and include dependencies, just like any other gradle module. While we’re not yet making use of dynamic delivery in Plaid we hope to in the future to further shrink the initial download size.
The great feature shuffle
After moving everything to
:core, we flagged the “about” screen to be the feature with the least inter-dependencies, so we refactored it into a new
:about module. This includes Activities, Views, code which is only used by this one feature. Also resources such as drawables, strings and transitions were moved to the new module.
We repeated these steps for each feature module, sometimes requiring dependencies to be broken up.
In the end,
:core contained mostly shared code and the home feed functionality. Since the home feed is only displayed within the application module, we moved related code and resources back to
:app.
A closer look at the feature structure
Compiled code can be structured in packages. Moving code into feature aligned packages is highly recommended before breaking it up into different compilation units. Luckily we didn’t have to restructure since Plaid already was well feature aligned.
As I mentioned, much of the functionality of Plaid is provided through news sources. Each of these consists of remote and local data source, domain and UI layers.
Data sources are displayed in both the home feed and, in detail screens, within the feature module itself. The domain layer was unified in a single package. This had to be broken in two pieces: a part which can be shared throughout the app and another one that is only used within a feature.
Reusable parts were kept inside of the
:core library, everything else went to their respective feature modules. The data layer and most of the domain layer is shared with at least one other module and were kept in core as well.
Package changes
We also made changes to package names to reflect the new module structure.
Code only relevant only to the
:dribbble feature was moved from
io.plaidapp to
io.plaidapp.dribbble. The same was applied for each feature within their respective new module names.
This means that many imports had to be changed.
Modularizing resources caused some issues as we had to use the fully qualified name to disambiguate the generated
R class. For example, importing a feature local layout’s views results in a call to
R.id.library_image while using a drawable from
:core in the same file resulted in calls to
io.plaidapp.core.R.drawable.avatar_placeholder
We mitigated this using Kotlin’s import aliasing feature allowing us to import core’s
R file like this:
import io.plaidapp.core.R as coreR
That allowed to shorten the call site to
coreR.drawable.avatar_placeholder
This makes reading the code much more concise and resilient than having to go through the full package name every time.
Preparing the resource move
Resources, unlike code, don’t have a package structure. This makes it trickier to align them by feature. But by following some conventions in your code, this is not impossible either.
Within Plaid, files are prefixed to reflect where they are being used. For example, resources which are only used in
:dribbble are prefixed with
dribbble_.
Further, files that contain resources for multiple modules, such as styles.xml are structurally grouped by module and each of the attributes prefixed as well.
To give an example: Within a monolithic app,
strings.xml holds most strings used throughout.
In a modularized app, each feature module holds on to its own strings.
It’s easier to break up the file when the strings are grouped by feature before modularizing.
Adhering to a convention like this makes moving the resources to the right place faster and easier. It also helps to avoid compile errors and runtime crashes.
Challenges along the way
To make a major refactoring task like this more manageable it’s important to have good communication within the team. Communicating planned changes and making them step by step helped us to keep merge conflicts and blocking changes to a minimum.
Good intentions
The dependency graph from earlier in this post shows, that dynamic feature modules know about the app module. The app module on the other hand can’t easily access code from dynamic feature modules. But they contain code which has to be executed at some point.
Without the app knowing enough about feature modules to access their code, there is no way to launch activities via their class name in the
Intent(ACTION_VIEW, ActivityName::class.java) way.
There are multiple other ways to launch activities though. We decided to explicitly specify the component name.
To do this we created an
AddressableActivity interface within core.
Using this approach, we created a function that unifies activity launch intent creation:
In its simplest implementation an
AddressableActivity only needs an explicit class name as a String. Throughout Plaid, each
Activity is launched through this mechanism. Some contain intent extras which also have to be passed through to the activity from various components of the app.
You can see how we did this in the whole file here:
Styling issues
Instead of a single
AndroidManifest for the whole app, there are now separate
AndroidManifests for each of the dynamic feature modules.
These manifests mainly contain information relevant to their component instantiation and some information concerning their delivery type, reflected by the
dist: tag.
This means activities and services have to be declared inside the feature module that also holds the relevant code for this component.
We encountered an issue with modularizing our styles; we extracted styles only used by one feature out into their relevant module, but often they built upon
:core styles using implicit inheritance.
These styles are used to provide corresponding activities with themes through the module’s
AndroidManifest.
Once we finished moving them, we encountered compile time issues like this:
* What went wrong:
Execution failed for task ‘:app:processDebugResources’.
> Android resource linking failed
~/plaid/app/build/intermediates/merged_manifests/debug/AndroidManifest.xml:177: AAPT:
error: resource style/Plaid.Translucent.About (aka io.plaidapp:style/Plaid.Translucent.About) not found.
error: failed processing manifest.
The manifest merger tries to merge manifests from all the feature modules into the app’s module. That fails due to the feature module’s
styles.xml files not being available to the app module at this point.
We worked around this by creating an empty declaration for each style within
:core’s
styles.xml like this:
<! — Placeholders. Implementations in feature modules. →
<style name=”Plaid.Translucent.About” />
<style name=”Plaid.Translucent.DesignerNewsStory” />
<style name=”Plaid.Translucent.DesignerNewsLogin” />
<style name=”Plaid.Translucent.PostDesignerNewsStory” />
<style name=”Plaid.Translucent.Dribbble” />
<style name=”Plaid.Translucent.Dribbble.Shot” />
<style name=”Plaid.Translucent.Search” />
Now the manifest merger picks up the styles during merging, even though the actual implementation of the style is being introduced through the feature module’s styles.
Another way to avoid this is to keep style declarations in the core module. But this only works if all resources referenced are in the core module as well. That’s why we decided to go with the above approach.
Instrumentation test of dynamic features
Along the modularization we found that instrumentation tests currently can’t reside within the dynamic feature module but have to be included within the application module. We’ll expand on this in an upcoming blog post on our testing efforts.
What is yet to come?
Dynamic code loading
We make use of dynamic delivery through app bundles, but don’t yet download these after initial installation through the Play Core Library. This would for example allow us to mark news sources that are not enabled by default (Product Hunt) to only be installed once the user enables this source.
Adding further news sources
Throughout the modularization process, we kept in mind the possibility of adding further news sources. The work to cleanly separate modules and the possibility of delivering them on demand makes this more compelling.
Finish modularization
We made a lot of progress to modularize Plaid. But there’s still work to do. Product Hunt is a news source which we haven’t put into a dynamic feature module at this point. Also some of the functionality of already extracted feature modules can be evicted from core and integrated into the respective features directly.
So, why did we decide to modularize Plaid?
Going through this process, Plaid is now a heavily modularized app. All without making changes to the user experience. We did reap several benefits in our day to day development from this effort:
Install size
Plaid is now on average more than 60 % smaller on a user’s device.
This makes installation faster and saves on precious network allowance.
Compile time
A clean debug build without caches now takes 32 instead of 48 seconds.*
All the while increasing from ~50 to over 250 tasks.
This time saving is mainly due to increased parallel builds and compilation avoidance thanks to modularization.
Further, changes in single modules don’t require recompilation of every single module and make consecutive compilation a lot faster.
*For reference, these are the commits I built for before and after timing.
Maintainability
We have detangled all sorts of dependencies throughout the process, which makes the code a lot cleaner. Also, side effects have become rarer. Each of our feature modules can be worked on separately with few interactions between them. The main benefit here is that we have to resolve a lot less merge conflicts.
In conclusion
We’ve made the app more than 60% smaller, improved on code structure and modularized Plaid into dynamic feature modules, which add potential for on demand delivery.
Throughout the process we always maintained the app in a state that could be shipped to our users. You can switch your app to emit an Android App Bundle today and save install size straight away. Modularization can take some time but is a worthwhile effort (see above benefits), especially with dynamic delivery in mind.
Go check out Plaid’s source code to see the full extent of our changes and happy modularizing!
|
https://medium.com/androiddevelopers/a-patchwork-plaid-monolith-to-modularized-app-60235d9f212e?hl=ru
|
CC-MAIN-2019-22
|
refinedweb
| 2,673
| 56.35
|
Problem:
Executing this code:
import pandas as pd data = {"1","2","3","4","5"} index = ["1_i","2_i","3_i","4_i","5_i"] df = pd.DataFrame(data,index=index) print(df)
Results in this output:
0 1_i 4 2_i 3 3_i 5 4_i 1 5_i 2
Question: Why aren’t the values in order according to the index that I set it to? 1 should be set to the index 1_i, 2 should be set to the index 2_i, etc.
Answer
The problem is that you are making the dataframe from a set, which is arbitrarily ordered. Try making your dataframe from a container that maintains order, like a list or tuple.
import pandas as pd data = ["1","2","3","4","5"] # a list index = ["1_i","2_i","3_i","4_i","5_i"] df = pd.DataFrame(data, index=index)
|
https://www.tutorialguruji.com/python/why-are-my-pandas-dataframe-values-out-of-order-according-to-the-index/
|
CC-MAIN-2021-43
|
refinedweb
| 133
| 70.13
|
IntroductionJust as a reminder of our full roadmap towards learning MVC, see:
Pre-requisites
The following are pre-requisites for this article:
Code-First ApproachToStep:public DbSet<User> Users { get; set; }User, defined in angular brackets, is the model that we created in the Models folder, so our MVCDBContext class looks like:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using LearningMVC.Models;
namespace LearningMVC
{
public class MVCDBContext : DbContext
{
public DbSet<User> Users { get; set; }
}
Both:
var dbContext = new MVCEntities() ;
to
var dbContext = new MVCDBContext();Job Done. Just Hit F5 and you'll see:How does the application run, where is the data base??? Dude, go back to your database server, and check for the database:We see that our database was created with the name MVCDB. That's the magic of Entity Framework. Now we can do all the CRUD operations on this database, using our application. Just create a new user.In the database we see the user has been created.By default, the integer property has ID in its name of the model and will be the primary key in the data base, in our case UserId, or you can define the primary key in the model too.ConclusionNow we know how to play with Entity Framework to create a database as per our domain model from our code, we have already moved on to the advanced concepts of MVC and Entity Framework.When we see the definition of DbContext, it uses the terms Repository Pattern and Unit of Work Pattern, we'll discuss these more in detail in my next article.
Read more:
My other series of articles:
For more informative articles visit my Blog.
View All
|
http://www.c-sharpcorner.com/UploadFile/1492b1/mvc-application-using-entityframework-code-first-approach-p/
|
CC-MAIN-2017-09
|
refinedweb
| 289
| 54.63
|
This project build pipelines for resolution score for Take BLiP
Project description
TakeResolution
Gabriel Salgado and Moises Mendes
Overview
Here is presented these content:
Intro
This project proposes to try to answer this: how much is resolution on this chatbot?
To discover the solution, analysed data includes bot structure and interactions events. These data are obtained from Spark database on Databricks cluster. A single run for this project intends to analyse data of a single bot on this database.
The first step is collect bot data from Spark database. Bot data is, at all, a table with bot identity, flow described as JSON and others information. Then, defined bot flow is selected on this step.
As long as we progress on this project, this description will include more details.
Configure
Here are shown recommended practices to configure project on local.
Virtual environment
This step can be done with commands or on PyCharm.
On commands
It is recommended to use virtual environment:
pip install venv
Create a virtual environment:
python -m venv venv
Enter to virtual environment (Windows):
./venv/Scripts/activate
Enter to virtual environment (Linux):
./venv/bin/activate
To exit virtual environment:
deactivate
On PyCharm
Open
File/Settings... or press
Ctrl+Alt+S.
This opens settings window.
Open
Project: ResolutionAnalysis/Project Interpreter on left menu.
Open
Project Interpreter combobox and click on
Show All....
This opens a window with Python interpreters.
Click on
+ or press
Alt+Insert.
This opens a window to create a new Python interpreter.
We will choose default options that create a new virtual environment into project.
Click on
Ok button.
Click on
Ok button again.
And again.
Configuring on PyCharm
If you are using PyCharm its better show PyCharm where is source code on project.
Right click on
src folder in
Project window at left side.
This opens context menu.
Choose
Mark Directory as/Sources Root option.
This marks
src as source root directory.
It will appears as blue folder on
Project navigator.
Install
The
take_resolution package can be installed from PyPI:
pip install take_resolution
Or from
setup.py, located at
src folder:
cd src pip install . -U cd ..
Installing
take_resolution also installs all required libraries.
But we can intended to only install dependencies or maybe update our environment if requirements changed.
All dependencies are declared in
src/requirements.txt.
Install dependencies can be done on command or on PyCharm.
On command
To install dependencies on environment, run:
python commands.py install
On PyCharm
After you created virtual environment or on open PyCharm, it will ask if you want to install requirements.
Choose
Install.
Test
You can test on commands or on PyCharm. It is being build.
On commands
First enter to virtual environment. Then run kedro tests:
python commands.py test
When this feature is built:
See coverage results at
htmlcov/index.html.
On PyCharm
Click on
Edit Configurations... beside
Run icon.
This opens Run/Debug Configurations window.
Click on
+ or press
Alt+Insert.
Choose
Python tests/pytest option.
Fill
Target field with path to tests folder as
<path to project>/src/tests.
Click on
Ok button.
Click on
Run icon.
This run the tests.
Open
Terminal window and run command to generate HTML report:
coverage html
See coverage results at
htmlcov/index.html.
Package
First enter to virtual environment.
To package this project into
.egg and
.whell:
python commands.py package
Generated packages will be in folder
src/dist.
Each new package, do not forget to increase version at
src/take_resolution/__init__.py
Upload
To upload build package to PyPI:
python commands.py upload
This upload the latest build version. After, package can be downloaded and installed by pip in any place with python and pip:
pip install take_resolution
Notebooks
Packaging this project is intended to be installed on a specific Databricks cluster.
This is the cluster where we work with ML experiments using
mlflow.
And an experiment is done as example notebooks on
shared, that is like:
import mlflow as ml import take_resolution as tr with ml.start_run(): # experiment code using our pipelines params = {} ml.log_params(params) # other logs from results
Tips
In order to maintain the project:
- Do not remove or change any lines from the
.gitignoreunless you know what are you doing.
- When developing experiments and production, follow data standard related to suitable layers.
- When developing experiments, put them into notebooks, following code policies.
- Write notebooks on Databricks and synchronize it to this repository into particular sub-folder in folder
notebooksand commit them.
- Do not commit any data.
- Do not commit any log file.
- Do not commit any credentials or local configuration.
- Keep all credentials or local configuration in folder
conf/local/.
- Do not commit any generated file on testing or building processes.
- Run test before pull request to make sure that has no bug.
- Follow git flow practices:
- Create feature branch for new feature from
devbranch. Work on this branch with commits and pushes. Send a pull request to
devbranch when terminate the work.
- When terminate a set of features to release, merge
devbranch to
testbranch. Apply several and strict tests to be sure that all are fine. On find errors, fix all and apply tests again. When all are ok, merge from
testto
masterincreasing release version and uploading to PyPI.
- If some bug is found on production,
masterbranch, create hotfix branch from
master. Correct all errors and apply tests like in
testbranch. When all are ok, merge from hotfix branch to
masterand then, merge from
masterto
dev.
Project details
Release history Release notifications | RSS feed
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/take-resolution/0.3.0/
|
CC-MAIN-2022-40
|
refinedweb
| 937
| 60.82
|
Have you thought about how you can provide your users with different color schemes for your application? or Do you want your application to have a
Dark theme?
Who doesn't like change? Even on our phones, sometimes we get bored of the look and feel, that we try out some new themes.
To provide multiple themes or not?
Sometimes it is always good to stick with the brand colors, this is especially the way to go for products that cater to consumers directly. Then there are apps that cater to other businesses, in this kind of application, it is good to have the option to customize the look and feel of the application for different businesses.
So the answer would be it depends on a lot of things. To name a few:
- who are audience
- does it bring in value
One really good example for when theming your application would make sense is for a School Management Software. Say the application is used by Teachers, Students, and Parents. We can give a different theme to the application based on the role.
Another good fit for providing custom themes would be applications that can be white-labeled. So for each of the users/businesses, they can set up their own themes to match their brand colors.
Even if you are going to provide multiple color themes for the application, it's probably a good idea to come with a
Dark Mode for the application. More and more products are now supporting
Dark theme.
CSS Custom Properties
The easiest way to theme your application is using
CSS Variables /
CSS custom properties. It makes theming so much easier than before when we had to do a lot of stuff, just to change some colors here and there.
But with CSS custom properties is so damn easy.
CSS Preprocessors had the concept of variables for a long time and CSS was still lagging behind on it until a few years back. Now its is supported in all modern browsers.
One really interesting thing about CSS custom properties is that they can be manipulated from JavaScript.
- Declare variables
--primaryColor: red; --primaryFont: 'Poppins'; --primaryShadow: 0 100px 80px rgba(0, 0, 0, 0.07);
- Usage
button { background: var(--primaryColor); font-family: var(--primaryFont); box-shadow: var(--primaryShadow); }
This is the most basic thing you should be knowing about CSS Custom Properties.
Theming in Angular
Starting off with a brand new Angular project with CLI v11.2.9. We now start by declaring some CSS variables for our application.
In the
styles.scss file:
:root { --primaryColor: hsl(185, 57%, 35%); --secondaryColor: hsl(0, 0%, 22%); --textOnPrimary: hsl(0, 0%, 100%); --textOnSecondary: hsl(0, 0%, 90%); --background: hsl(0, 0%, 100%); }
We have declared a few variables and assigned the default colors for all of them. One thing to note, when you are going to be providing different colors is that you name the variables in a generic way. You shouldn't be naming it with the color's name.
Setting up the themes
I will be creating a
theme.config.ts file all the themes will be configured. You can always make a static config like this or maybe get the config from an API response.
The latter is the better approach if you make changes to your themes often.
export const THEMES = { default: { primaryColor: 'hsl(185, 57%, 35%)', secondaryColor: 'hsl(0, 0%, 22%)', textOnPrimary: 'hsl(0, 0%, 100%)', textOnSecondary: 'hsl(0, 0%, 90%)', background: 'hsl(0, 0%, 100%)', }, dark: { primaryColor: 'hsl(168deg 100% 29%)', secondaryColor: 'hsl(161deg 94% 13%)', textOnPrimary: 'hsl(0, 0%, 100%)', textOnSecondary: 'hsl(0, 0%, 100%)', background: 'hsl(0, 0%, 10%)', }, netflix: { primaryColor: 'hsl(357, 92%, 47%)', secondaryColor: 'hsl(0, 0%, 8%)', textOnPrimary: 'hsl(0, 0%, 100%)', textOnSecondary: 'hsl(0, 0%, 100%)', background: 'hsl(0deg 0% 33%)', }, spotify: { primaryColor: 'hsl(132, 65%, 55%)', secondaryColor: 'hsl(0, 0%, 0%)', textOnPrimary: 'hsl(229, 61%, 42%)', textOnSecondary: 'hsl(0, 0%, 100%)', background: 'hsl(0, 0%, 100%)', }, };
This is the most basic way to do this. Maybe in the future, we can talk about how we can create a theme customizer where the user can completely change the look and feel of the application.
Theming service
We create a service and call it
ThemeService. The logic for updating the themes will be handled by this service. We can inject the service into the application and then change the theme using a function we expose from the service.
import { DOCUMENT } from '@angular/common'; import { Inject, Injectable } from '@angular/core'; import { THEMES } from '../config/theme.config'; @Injectable({ providedIn: 'root', }) export class ThemeService { constructor(@Inject(DOCUMENT) private document: Document) {} setTheme(name = 'default') { const theme = THEMES[name]; Object.keys(theme).forEach((key) => { this.document.documentElement.style.setProperty(`--${key}`, theme[key]); }); } }
The service is very straightforward. There is a single function that we expose which changes the theme. How this works is basically by overriding the CSS variable values that we have defined in the
styles.scss file.
We need to get access to the
document, so we inject the
Document token in the constructor.
The function takes the name of the theme to apply. What it does it, get the theme variables for the selected theme from our config file and then loop through it wherein we apply the new values to the variables.
Done!
Code and Demo
Click on the buttons to change the themes.
Do add your thoughts in the comments section.
Stay Safe ❤️
Discussion (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/angular/theming-your-angular-apps-using-css-variables-easy-solution-3od0
|
CC-MAIN-2021-21
|
refinedweb
| 907
| 62.48
|
If you use the AWS Elastic Load Balancer (ELB) you’ll need to decide what to use as an endpoint on your application server for the health checker. This is how the ELB will determine if an instance is healthy, or not.
If you use the default “/” path, this may mean that a session in your application is kicked off every time the health checker connects, which could translate to unnecessary added load on your server (though perhaps it may be negligible).
Furthermore, if you create a static .html file and map it, and point the health checker to that, it could turn out that though your application server is hung, the simple static .html is still getting served. This would not make for an accurate health check, and happened to me in my experience.
The best way to ensure that your application server is online and not hung, without adding extra load to your server, will be to create a simple program that runs on the application server. In the case of a Java application server, you can create a simple servlet, as follows:
package com.whatever.aws.elb;; @SuppressWarnings("serial") public class Ping extends HttpServlet { private String message; public void init() throws ServletException { message = "Pong"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" < h1 > " + message + " < /h1> "); } }
And map the servlet to a path in web.xml:
<servlet> <servlet-name>Ping</servlet-name> <servlet-class>com.perthera.elb.Ping</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Ping</servlet-name> <url-pattern>/Ping</url-pattern> <url-pattern>/ping</url-pattern> </servlet-mapping>
Now, you can configure the ELB health checker to connect to the “/ping” path on your instance. If it times out, or returns an error, that means the application server is not healthy. If it returns a normal HTTP code, then all is good.
|
http://blog.adeel.io/tag/health-check/
|
CC-MAIN-2018-30
|
refinedweb
| 325
| 53.61
|
Have you ever wanted to fit a line to a set of data points using Python? Well, if you ever do, here’s how do to it:
Method 1:
The NumPy/SciPy package has a built in function; stats.linregress you can use. I didn’t choose this method because I didn’t want to fool with installing a package for my simple one-off need. There’s an example of using SciPy’s linear regression function here.
stats.linregress
Method 2:
I found and modified the linreg function on this helpful website: Simple Recipes in Python by William Park.
Here is my modified version, simply modified to clean up the formatting, and to include the R^2 value in the return values:
from math import sqrt
def linreg(X, Y):
"""
Summary
Linear regression of y = ax + b
Usage
real, real, real = linreg(list, list)
Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value
"""
if len(X) != len(Y): raise ValueError, 'unequal length'
N = len(X)
Sx = Sy = Sxx = Syy = Sxy = 0.0
for x, y in map(None, X, Y):
Sx = Sx + x
Sy = Sy + y
Sxx = Sxx + x*x
Syy = Syy + y*y
Sxy = Sxy + x*y
det = Sxx * N - Sx * Sx
a, b = (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det
meanerror = residual = 0.0
for x, y in map(None, X, Y):
meanerror = meanerror + (y - Sy/N)**2
residual =, RR
if __name__=='__main__':
#testing
X=[1,2,3,4]
Y=[357.14,53.57,48.78,10.48]
print linreg(X,Y)
#should be:
#Slope Y-Int R
#-104.477 378.685 0.702499064
By the way, I used Excel’s built-in function: linest to make sure this function is working properly.
linest
Please don’t hesitate to post any questions as comments. I wasn’t sure of the statistics background of my audience (all 3 of you , hi mom!).
[tags]Python, Excel, Statistics, Python Statistics, Simple Linear Regression, Ordinary Least Squares, OLS, SLR, Linear Regression, Regression[/tags]
Posted by Greg Pinero (Primary Searcher) on Jun 21st, 2006 and is filed under Python.
Both comments and pings are currently closed.
Add this post to Del.icio.us - Digg
Instead of using the map(None, X, Y), you could also use the built-in zip function and do zip(X,Y). I had never seen the idiom of using map with function=None before and had to look up what it did…
Good point, Stan. It looks like the code I modified was written in 1998. Perhaps they didn’t have zip() back then?
Hey, thanks a lot for making the linear regression script! I’m using in a small project on the colour patterns of flounders!
Great work,
Rob
© 2017, Blended Technologies LLC
Entries (RSS) and Comments (RSS).
|
http://www.answermysearches.com/how-to-do-a-simple-linear-regression-in-python/124/
|
CC-MAIN-2017-09
|
refinedweb
| 473
| 71.04
|
constants in a typesafe manner using Java 5.0
Document options requiring JavaScript are not displayed
Help us improve this content
Level: Introductory
Brett McLaughlin (brett@newInstance.com), Author/Editor, O'Reilly Media, Inc.
09 Nov 2004.
public static final
You already know that the two fundamental building blocks of Java code are classes and interfaces. Now Tiger has introduced one more: the enumeration. Usually referred to simply as an enum, this new type allows you to represent specific data points that accept only certain sets of pre-defined values at assignment time.
Of course, well-practiced programmers already know you can achieve this functionality with static constants, as shown in Listing 1:
public class OldGrade {
public static final int A = 1;
public static final int B = 2;
public static final int C = 3;
public static final int D = 4;
public static final int F = 5;
public static final int INCOMPLETE = 6;
}
Note: I'd like to thank O'Reilly Media, Inc., which has permitted me to use the code sample from the "Enumerations" chapter of my book Java 1.5 Tiger: A Developer's Notebook for this article (see Resources).
You can then set up classes to take in constants like OldGrade.B, but when doing so keep in mind that such constants are Java ints, which means the method will accept any int, even if it doesn't correspond to a specific grade defined in OldGrade. Therefore, you'll need to check for upper and lower bounds, and probably include an IllegalArgumentException if an invalid value appears. Also, if another grade is eventually added (for example, OldGrade.WITHDREW_PASSING), you'll have to change the upper bound on all your code to allow for this new value.
OldGrade.B
int
OldGrade
IllegalArgumentException
OldGrade.WITHDREW_PASSING
In other words, while using classes with integer constants like this might be a passable solution, it's not a very efficient one. Fortunately, enumerations offer a better way.
Defining an enum
Listing 2 uses an enumeration to provide similar functionality to Listing 1:
package com.oreilly.tiger.ch03;
public enum Grade {
A, B, C, D, F, INCOMPLETE
};
Here I've used the new keyword enum, given the enum a name, and specified the allowed values. Grade then becomes an enumerated type, which you can use in a manner shown in Listing 3:
enum
Grade
package com.oreilly.tiger.ch03;
public class Student {
private String firstName;
private String lastName;
private Grade grade;
public Student;
}
public String getFullName() {
return new StringBuffer(firstName)
.append(" ")
.append(lastName)
.toString();
}
public void assignGrade(Grade grade) {
this.grade = grade;
}
public Grade getGrade() {
return grade;
}
}
By creating a new enumeration (grade) of the previously defined type, you can then use it like any other member variable. Of course, the enumeration can be assigned only one of the enumerated values (for example, A, C, or INCOMPLETE). Also, notice how there is no error checking code or boundary considerations in assignGrade().
grade
A
C
INCOMPLETE
assignGrade()
Working with enumerated values
The examples you've seen so far have been rather simple, but enumerated types offer much more. Enumerated values, which you can iterate over and use in switch statements, among other things, are very valuable.
switch
Iterating over enums
Let's begin with an example that shows how to run through the values of any enumerated type. This technique, shown in Listing 4, is handy for debugging, quick printing tasks, and loading enums into a collection (which I'll talk about shortly):
public void listGradeValues(PrintStream out) throws IOException {
for (Grade g : Grade.values()) {
out.println("Allowed value: '" + g + "'");
}
}
Running this snippet of code will give you the output shown in Listing 5:
Allowed Value: 'A'
Allowed Value: 'B'
Allowed Value: 'C'
Allowed Value: 'D'
Allowed Value: 'F'
Allowed Value: 'INCOMPLETE'
There's a lot going on here. First, I'm using Tiger's new for/in loop (also called foreach or enhanced for). Additionally, you can see that the values() method returns an array of individual Grade instances, each with one of the enumerated type's values. In other words, the return type of values() is Grade[].
for/in
foreach
enhanced for
values()
Grade[]
Switching on enums
Being able to run through the values of an enum is nice, but even more important is the ability to make decisions based on an enum's values. You could certainly write a bunch of if (grade.equals(Grade.A))-type statements, but that's a waste of time. Tiger has conveniently added enum support to the good old switch statement, so it's easy-to-use and fits right in with what you already know. Listing 6 shows you how to pull this off:
if (grade.equals(Grade.A));
}
out.println(outputText.toString());
}
Here the enumerated value is passed into the switch statement (remember, getGrade() returns an instance of Grade) and each case clause deals with a specific value. That value is supplied without the enum prefix, which means that instead of writing case Grade.A you need to write case A. If you don't do this the compiler won't accept the prefixed value.
getGrade()
case
case Grade.A
case A
Planning ahead with switch
You can use the default statement with enums and switches, just as you would expect. Listing 7 illustrates this usage:
default;
default:
outputText.append(" has a grade of ")
.append(student1.getGrade().toString());
break;
}
out.println(outputText.toString());
}
Consider the code above and realize that any enumerated value not specifically processed by a case statement is instead processed by the default statement. This is a technique you should always employ. Here's why: Suppose that the Grade enum was changed by another programmer in your group (who of course forgot to tell you about it) to the version shown in Listing 8:
package com.oreilly.tiger.ch03;
public enum Grade {
A, B, C, D, F, INCOMPLETE,
WITHDREW_PASSING, WITHDREW_FAILING
};
Now, if you used this new version of Grade with the code in Listing 6, these two new values would be ignored. Even worse, you wouldn't even see an error! In these cases, having some sort of general purpose default statement is very important. Listing 7 may not handle these values gracefully, but it will give you some indication that values have snuck in, and that you need to address them. Once you've done that you'll have an application that continues to run, doesn't ignore values, and that even even instructs you to take later action. Now that's good coding.
Enums and collections
Those of you familiar with the public static final approach to coding have probably already moved on to using enumerated values as keys to maps. For the rest of you who don't know what this means, take a look at Listing 9, which is an example of common error messages that can pop up when working with Ant build files:
package com.oreilly.tiger.ch03;
public enum AntStatus {
INITIALIZING,
COMPILING,
COPYING,
JARRING,
ZIPPING,
DONE,
ERROR
}
Having some human-readable error message assigned to each status code would allow you to look up the appropriate error message and echo it back out to the console when Ant supplies one of the codes. This is a great use-case for a Map, in which each key of the Map is one of these enumerated values, and each value is the error message for that key. Listing 10 illustrates how this works:
Map
public void testEnumMap(PrintStream out) throws IOException {
// Create a map with the key and a String message
EnumMap<AntStatus, String> antMessages =
new EnumMap<AntStatus, String>(AntStatus.class);
// Initialize the map
antMessages.put(AntStatus.INITIALIZING, "Initializing Ant...");
antMessages.put(AntStatus.COMPILING, "Compiling Java classes...");
antMessages.put(AntStatus.COPYING, "Copying files...");
antMessages.put(AntStatus.JARRING, "JARring up files...");
antMessages.put(AntStatus.ZIPPING, "ZIPping up files...");
antMessages.put(AntStatus.DONE, "Build complete.");
antMessages.put(AntStatus.ERROR, "Error occurred.");
// Iterate and print messages
for (AntStatus status : AntStatus.values() ) {
out.println("For status " + status + ", message is: " +
antMessages.get(status));
}
}
This code uses both generics (see Resources) and the new EnumMap construct to create a new map. Also, an enumerated type is supplied via its Class object, along with the type of the Map's values (in this case, simple strings). The output of this method is shown in Listing 11:
EnumMap
Class
You may have noticed that the sample code in Listing 10 actually implies Tiger treats enums as classes, which is evidenced by the AntStatus Class object being not only available, but also in use. This is true. Under the hood, Tiger views enums as a special class type. For more information on the implementation details of enums, see Chapter 3 of Java 5.0 Tiger: A Developer's Notebook (see Resources).
AntStatus
[echo] Running AntStatusTester...
[java] For status INITIALIZING, message is: Initializing Ant...
[java] For status COMPILING, message is: Compiling Java classes...
[java] For status COPYING, message is: Copying files...
[java] For status JARRING, message is: JARring up files...
[java] For status ZIPPING, message is: ZIPping up files...
[java] For status DONE, message is: Build complete.
[java] For status ERROR, message is: Error occurred.
Going further
Enums can also be used in conjunction with sets, and much like the new EnumMap construct, Tiger supplies a new Set implementation EnumSet that allows you to work with bitwise operators. Additionally, you can add methods to your enums, use them to implement interfaces, and define what are called value-specific class bodies, where specific code is attached to a particular value of an enum. These features are beyond the scope of this article, but they're well documented elsewhere (see Resources).
EnumSet
Use them, but don't abuse them
One of the dangers of learning a new version of any language is the tendency to go crazy with new syntactical structures. Do that and suddenly your code is 80 percent generics, annotations, and enumerations. So use enumerations only where they make sense. Where, then, do they make sense? As a general rule, anywhere constants are in use, such as in places you are currently using the switch code to switch constants. If it's a single value (for example, an upper bound on a shoe size, or the maximum number of monkeys that can fit in a barrel), leave the constant as it is. But if you're defining a set of values, and any one of those values can be used for a certain data type, enumerations should be a perfect fit.
Resources
About the author
Brett McLaughlin has worked in computers since the Logo days (remember the little triangle?) with such companies as Nextel Communications and Lutris Technologies. In recent years he has become one of the most well-known authors and programmers in the Java and XML communities. His most recent book, Java 1.5 Tiger: A Developer's Notebook, is the first book available on the newest version of Java, and his classic Java and XML remains one of the definitive works on using XML technologies in Java.
Rate this page
Please take a moment to complete this form to help us better serve you.
Did the information help you to achieve your goal?
Please provide us with comments to help improve this page:
How useful is the information?
|
http://www.ibm.com/developerworks/java/library/j-enums.html
|
crawl-001
|
refinedweb
| 1,875
| 54.52
|
Creating Alarms and Reminders for Windows Phone
Introduction
With Windows Phone Mango, Microsoft introduced over 500 new features, big and small. One of the features it introduced was programmatic access to the alarms and reminders feature on the Windows Phone platform.
Alarms and reminders are two types of scheduled notifications, both of which reside in the Microsoft.Phone.Scheduler namespace.
Hands On
To see the behavior of alarms and reminders ourselves, let's create a demo application. Create a new Silverlight for Windows phone application called WPAlarmDemo.
Now, add 4 buttons called "Add Alarm", "Delete Alarm", "Add reminder" and "Delete Reminder".
Your UI at this point should look like this:
Figure 1: "My Application" UI
For simplicity's sake, we will set our alarm and reminder to 10 seconds from the current system time. This will help speed up our testing.
On the code behind for MainPage.xaml page (MainPage.xaml.cs), add two variables of type Alarm and Reminder called "alarm" and "reminder".
public partial class MainPage : PhoneApplicationPage { Alarm alarm; Reminder reminder; // Constructor public MainPage()
Double click the "Add Alarm" button and enter the following code
private void buttonAddAlarm_Click(object sender, RoutedEventArgs e) { alarm = new Alarm("MyAlarm"); alarm.BeginTime = DateTime.Now.AddSeconds(10); alarm.Content = "Alarm has fired"; ScheduledActionService.Add(alarm); }
Now Add code to remove the alarm from the ScheduledAction list.
private void buttonDeleteAlarm_Click(object sender, RoutedEventArgs e) { ScheduledActionService.Remove("MyAlarm"); }
Now, add similar code for the event handler for the click event on "Add Reminder" button.
private void buttonAddReminder_Click(object sender, RoutedEventArgs e) { reminder = new Reminder("MyReminder"); reminder.BeginTime = DateTime.Now.AddSeconds(10); reminder.Content = "Reminder has fired"; reminder.Title = "Reminder Demo"; ScheduledActionService.Add(reminder); }
Finally, add code to remove the reminder from the ScheduledAction list.
privatevoid buttonDeleteReminder_Click(object sender, RoutedEventArgs e) { ScheduledActionService.Remove("MyReminder"); }
You are now ready to test your sample. Compile and execute your sample. If you are having issues compiling the code, you can get the sample code for this exercise below.
When we execute the application, click on the "Add Alarm" button. Wait for 10 seconds; you will see an alarm notification on the application page.
Figure 2: Alarm notification
We can dismiss the alarm by clicking the "dismiss" button.
Now, click the "Add Reminder" button. After 10 seconds, we see a reminder show up.
Figure 3: Reminder Demo
In this demo application, I have not specified an URI but you might want to consider using that to get the full leverage from the reminder feature.
Summary
In this article, we learned how to create alarms and reminders in a Windows Phone application.
NEED HELPPosted by piya on 03/11/2016 09:11am
Not able to declare alarm and reminder type variable. Need HELP!!Reply
ENipIC tW XU hpH HaIz HCPosted by egWFfjgniV on 06/24/2013 04:09pm
Continue Reading viagra online price comparison - can you buy generic viagra from a storeReply
MrPosted by Robert Tate on 06/30/2012 01:26am
Hi, My wife and I are both on medication which has to be taken every other day. My question is can I set 2 alarms on my Nokia 800 so I am reminded whose turn it is to take their pill. RobertReply
|
http://www.codeguru.com/csharp/.net/wp7/article.php/c20075/Creating-Alarms-and-Reminders-for-Windows-Phone.htm
|
CC-MAIN-2016-40
|
refinedweb
| 533
| 56.86
|
tag:blogger.com,1999:blog-20541840382858591312018-09-01T11:59:54.086+02:00My Technical Notes & Others...Tips & Tricks, Summaries, Check Lists, Do's & Don'ts, Reminders, Stuff that works...Jérôme Verstrynge to prepare for the DAMA DMCP exam? My experience...There is, unfortunately, not much information explaining how to prepare and pass the DAMA DMCP<img src="" height="1" width="1" alt=""/>Jérôme Verstrynge Mining - How Much Passive Income Can You Make? About Cryptocurrency Mining Cloud mining is profitable, I have tried it. The question is, what is the return on investment and when will you get your money back? Considering mining fees, contract duration and many other factors, it's hard to guess which site offers the best cloud mining contracts. And what about reinvestment opportunities? Well, rather than guessing, I've spent a bit of my <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge Concepts Plugged Together (for newbies)Although Docker looks like a promizing tool facilitating project implementation and deployment, it took me some time to wrap my head around its concepts. Therefore, I thought I might write another blog post to summarize and share my findings. Docker Container & Images Docker is an application running containers on your laptop, but also on staging or production servers. Containers are isolated <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge React Concepts & Principles, Because I Am Not A UI SpecialistI have been reading React's documentation, but found it to take too many shortcuts regarding the descriptions of concepts and how they related to each other to understand the whole picture. It is also missing a description of the principles it relies on. Not everyone is already a top-notch Javascript UI designer. This post is an attempt to fill the gaps. I am assuming you know what HTML, CSS and <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge An OpenShift Web/Spring Application From The Command LineOpenShift offers online functionalities to create applications, but this can also be achieved from command line with the RHC Client Tool. For windows, you will first need to install RubyGems and Git. The procedure is straightforward. Git SSL Communication OpenShift requires SSL communication between local Git repositories and the corresponding server repositories. Generating SSH Keys for <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge 21-22-23, 2013 - Search Queries Not Updated in Google Webmaster ToolsThis <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge Responsive Design BreakpointsWhile trying to find an answer to my own question: "What are the best responsive design breakpoints?", I have performed a small statistical study over SmartPhone screen widths (portrait and landscape) using information provided by i-skool. The above table shows how often a specific SmartPhone width in the source data is reported. There are five peaks: 320 pixels 480 pixels 768-800 pixels <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge 4th, 2013 - Sudden Drop In Traffic - A Thin Or Lack Of Original Content Ratio Issue? Many people have reported a sudden drop in traffic to their websites since September 4th, 2013. Google <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge & Decode URL Parameters In JavaA small code example describing how to encode and decode URL query strings properly from Java. The code example is available from GitHub in the in the Java-Core-Examples directory. StringJérôme Verstrynge RemindersA small post to aggregate notes related to FreeMarker. Accessing Parameter Inside A Directive The following piece of code: <#assign myVar = ${myValue}-1> will trigger the following exception: Exception in thread "main" freemarker.core.ParseException: Encountered "{" ... One should not use ${...} inside a FreeMarker directive, but rather: <#assign myVar = myValue - 1 ><img src="" height="1" width="1" alt=""/>Jérôme Verstrynge Javascript From Java (Example)This post explains how to call Javascript from Java. The code example is available at GitHub in the Java-Javascript-Calling directory. Code Example We create some small Javascript code in a string. This code dumps "Hello World!" and defines a function called myFunction() adding 3 to the provided value: public class JavascriptCalling { public static final StringJérôme Verstrynge A Customized Spring User & PersistenceThis post explains how to create a customized Spring user and persistence mechanism for authentication. The code is available at GitHub in the Spring-MVC-Customized-User directory. Things To Take Into Consideration Before creating a customized user, we need to remind what a user is in Spring. We know from here that a user is an implementation of the UserDetails interface. Spring security also <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge Spring ACL SQL Script In MemoryThis post describes how to execute the Spring ACL script to create ACL tables in an in-memory HSQL database instance. The code is available at GitHub in the Execute-ACL-SQL-Scripts-In-Memory directory. In-Memory DataSource We are using a configuration classe implementing the DisposableBean interface to shut down the created HSQL embedded database nicely. @Configuration public class <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge An Image Or Text Within A DivThis post explains how to center an image or text in HTML using CSS. The code example is available on GitHub in the Center-Image-Text-Div directory. Centering An Image Vertically And Horizontally Within A Div The method described here requires to know the size of the image. The HTML is the following: <div id="myDiv"> <img id="myImg" src="SomeImg.jpg"> </div> The CSS is the following: #<img src="" height="1" width="1" alt=""/>Jérôme Verstrynge ServiceLoader ExampleDefining an API and developing the corresponding implementation has become an uber mainstream practice when developing large Java applications. Modularization is such an useful design principle, especially to avoid spaghetti code, for testing and debugging, and for re-implementation of old code. Many developers seek to separate API interfaces and abstract classes from their implementation in <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge TestNG ExampleThis post illustrates some of the feature of TestNG. The code example is available at GitHub in the Java-TestNG directory. We use maven. Therefore, the configuration will located in the pom.xml. Source Code We use a very simple class returning integers for testing purposes: public class Generate { private Generate() { } public static int aOne() { return 1; } public <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge'package javax.servlet.http does not exist' SolutionThis is a common error which occurs when trying to compile a web project. This package is usually provided by the container. However, it is not (always) available at compile time and one should not include it in the final .war too. If you are using Maven, the solution is simple. Add the following dependency with the provided scope: <dependency> <groupId>javax.servlet</groupId> <<img src="" height="1" width="1" alt=""/>Jérôme Verstrynge From Google's Sandbox In A WeekSharing the experience acquired while trying to get a keyword-stuffed site out of Google's sandbox. I explain how I succeeded faster than methods described on the net so far. Not a silver bullet, but surely a boost. In less than a week, I got my site at search result position number 3 for its title keywords: As a reminder, the Google Sandbox effect is observed when a site is indexed by Google<img src="" height="1" width="1" alt=""/>Jérôme Verstrynge(<img src="" height="1" width="1" alt=""/>Jérôme Verstrynge With Google Webmaster Tools FrustrationsIf you don't understand the mechanics behind Google Webmaster Tool (GWT, not to be confused with Google's Web-Toolkit framework) and of page indexing, trying to obtain valid information about your website can be a very frustrating experience, especially if it is a new website. This has even led me to take counter-productive actions in order to solve some of GWT flaws. This post is about sharing <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge A Service And JSP Pages Securing A Spring Service When a service is implemented in Spring, it can be secured with the @Secured annotation. It has a parameter where the list of roles can be defined. In order to enable this annotation, one must add the the following line in the Spring Security configuration XML file: <security:global-method-security A complete example is available <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge Content: Quality, Ranking And PromotionThis post is a summary of thumb rules collected here and there and personal experience about content posted online. It is a living document that I will update from time to time: Love the content or have a genuine passion for it! - People notice when you are being authentic and passionate, or not. Content is king! - The quality of the delivered content influences your ranking much more than <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge To Java EE ConceptsThis post aims at clarifying acronyms and concepts used in the Java EE paradigm, where EE stands for Entreprise Edition. It enables the creation of modular Java applications to be deployed on application servers. It relies on Java SE, a core set of Java libraries upon which all Java applications are implemented. General Concepts Before we dive into Java EE, here is a reminder of general concepts<img src="" height="1" width="1" alt=""/>Jérôme Verstrynge Of The Default OpenShift Spring Web ApplicationOpenS. The purpose of this post is to discuss the default Spring <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge Is JNDI, SPI, CCI, LDAP And JCA?J <img src="" height="1" width="1" alt=""/>Jérôme Verstrynge
|
http://feeds.feedburner.com/blogspot/jdBLC
|
CC-MAIN-2018-43
|
refinedweb
| 1,590
| 51.38
|
I'd like to call a closure with a delegate parameter to override or shadow the calling context. But the following example prints prints "outside" where I expect "inside".
What am I doing wrong?
def f(String a){
def v = { return a }
v.delegate = [a:"inside"]
// Makes no difference:
// v.resolveStrategy = Closure.DELEGATE_FIRST
println(v.call())
}
f("outside")
I believe the issue is that when the closure is declared inside the function, it 'closes' round the known values in the method (
a), so that value becomes effectively hard-coded into the closure (it never hits the delegate to find the unknown value as it is known to the Closure).
If you move the closure
v definition outside of the function
f, then it works:
v = { return a } def f(String a){ v.delegate = [a:"inside"] println(v.call()) } f("outside")
Other option is to use
getProperty('a') instead of directly using
a as this forces the use of the delegate to retrieve the value of
a.
Can also be done by referring the
delegate in the closure. For
v as a closure,
a does not make any sense (equivalent to use of ExpandoMetaClass)
def f(String a){ def v = { delegate.a } v.delegate = [a:"inside"] println v() } f("outside")
|
http://www.dlxedu.com/askdetail/3/a037160872f0fd952c93a3719c22a968.html
|
CC-MAIN-2018-43
|
refinedweb
| 209
| 64.1
|
Created on 2010-08-26 14:42 by uis, last changed 2012-07-21 13:33 by flox. This issue is now closed.
The following code leads to an UnicodeError in python 2.7 while it works fine in 2.6 & 2.5:
# -*- coding: latin-1 -*-
import xml.etree.cElementTree as ElementTree
oDoc = ElementTree.fromstring(
'<?xml version="1.0" encoding="iso-8859-1"?><ROOT/>' )
oDoc.set( "ATTR", "ÄÖÜ" )
print ElementTree.tostring( oDoc , encoding="iso-8859-1" )
IMO the code is not correct: how does ElementTree know which encoding is used for the attribute value? Even 2.5 prints a different content when the script is saved with a different encoding.
The line should look like:
oDoc.set( "ATTR", u"ÄÖÜ" )
or use ascii-only characters.
Of course, if you use an unicode string it works and of course it would be easy to switch to unicode for this demo code. Unfortunately, the affected application is a little bit more complex and it is not that easy to switch to unicode. I just wonder why the tostring() method does not assume that internal strings are encoded in the explicitly provided encoding? Is ElementTree restricted to the use of unicode strings? Anyway, why was it working (as expected) with python 2.5 & python 2.6?
Testing with python 2.5: oDoc.set("ATTR", "ÄÖÜ") uses the encoding used by the source code (with "# -*- coding:";) If I use utf-8 instead, the output is:
<ROOT ATTR="ÄÖÜ" />
which contains the numbers of the 3 pairs of surrogates.
Well, the output of the print is not that interesting as long as ElementTree is able the restore the former attributes value when reading it in again. The print was just used to illustrate that an UnicodeDecodeError appears. Think about doing an
ElementTree.fromstring( ... ).get( "ATTR" ).encode( "iso-8859-1" ).
I would suggest adding an additional except branch to (at least) the following functions of ElementTree.py:
* _encode,
* _escape_attrib, and
* _escape_cdata
The except branch could look like:
except (UnicodeDecodeError):
return text.decode( encoding ).encode( encoding, "xmlcharrefreplace")
I propose to close this as won't fix.
The upgrade to ElementTree 1.3 brought some consistency when dealing with Unicode and encodings.
The reported behavior was only seen in Python 2.7, when using bytes improperly.
|
http://bugs.python.org/issue9692
|
CC-MAIN-2015-06
|
refinedweb
| 380
| 68.16
|
Technical Support
On-Line Manuals
CARM User's Guide
Discontinued
#include <string.h>
unsigned int strrpos (
const unsigned char *string, /* string to search */
char c); /* character to find */
The strrpos function searches string for
the last occurrence of c. The null character
terminating string is included in the search.
The strrpos function returns the index of the last
character matching c in string
or a value of -1 if no matching character was found. The index of the
first character in string is 0.
strchr, strcspn, strpbrk, strpos, strrchr, strrpbrk, strspn
#include <string.h>
#include <stdio.h> /* for printf */
void tst_strrpos (const unsigned char *s) {
unsigned int i;
i = strrpos (s, ' ');
if (i == -1)
printf ("No spaces found in %s\n", s);
else
printf ("Last space in %s is at offset .
|
http://www.keil.com/support/man/docs/ca/ca_strrpos.htm
|
CC-MAIN-2019-43
|
refinedweb
| 131
| 64.1
|
Every Emacs release adds all sorts of functions that might impinge on the user namespace, Would you please give some examples for a recent release, so it will be clear whether you are talking about the same issue? Most functions in Emacs have name prefixes or suffixes which help prevent name conflicts; those names don't pose a problem. We only rarely add names like `remove-if' which have nothing in the name to keep them out of the user's way, and we normally document such names in the manual. If that practice has changed, I would like to know.
|
http://lists.gnu.org/archive/html/emacs-devel/2010-10/msg00021.html
|
CC-MAIN-2014-15
|
refinedweb
| 101
| 71.99
|
When xset fields are iterated over, it is found that for the mandated field,
Field name :xstream.name
Field type :application/octet-stream
How is it possible to get the value of the field name, if type is octet-stream? (there is no get method for byte types)
The xstream.name is the name of the field not the data it contains - it is returned via the field iterator, or specified by the application to directly access the field. If the application does not know the field names it created it will be pretty useless!!
The "Get" methods you refer to retrieve the value of properties. To retrieve xstream data you open the stream (XAM_OpenXStream) and read the bytes (XStream_Read).
the getFieldType for the field name xstream.name returns "application/octet-stream"
what is the relevance of having such a field property listed by the iterator and not able to get the value?
It is not a property, it is an xstream. There are two types of fields - properties (which are primitive data types and have corresponding "get" methods) and xstreams (which are byte streams). As an xstream is a field so it should obviously be returned by a field iterator.
You can easily get the value of the field (as I described in my previous post).
Finally, the field would be called .xstream.name by whichever application created the XSet. There is no such "mandated field" - in fact, it is an invalid field name because a "user" cannot create files in a namespace beginning with ".".
|
https://www.dell.com/community/Centera/Get-value-for-quot-xstream-name-quot-field/td-p/6779105
|
CC-MAIN-2019-35
|
refinedweb
| 256
| 72.76
|
Keeping the Cubes Current
This chapter discusses how to use the Cube Manager and other tools for updating the cubes.
Also see the appendix “Using Cube Versions.”
Also see “Accessing the Samples Shown in This Book,” in the first chapter.
Overview
The generic phrase updating a cube refers to the process of causing a cube to reflect the current contents of the source table and related tables. The system provides three techniques:
Rebuild the cube, using the Build option in the Architect, for example. This process can be time-consuming, and queries cannot be executed while a cube is being rebuilt.
You can also use Selective Build to rebuild certain elements of the cube.
Synchronize the cube. The cube synchronization feature (also known as the DSTIME feature) enables InterSystems IRIS Business Intelligence to keep track of changes to the data. You periodically synchronize the cube to include those changes.
It is possible to execute queries during synchronization.
Depending on the cube implementation and depending on which data changes, it may not be possible to use this feature; see “When Cube Synchronization Is Possible,” later in this chapter.
Update the cube manually. This process uses the %ProcessFact() and %DeleteFact() methods. Unlike with the other options, in this case, it is necessary for your code to know which records of the fact table to update or delete.
It is possible to execute queries during the manual updates.
You can use any suitable combination of these techniques. The following table compares them:
For information on the Cube Manager, see “Using the Cube Manager,” later in this chapter.
Cube Updates and Related Cubes
For any kind of update, whenever you have cube-to-cube relationships, it is necessary to update the cubes in a specific order. In particular, update the independent cube first. Then update any cubes that depend on it. To do this, you can use the Cube Manager, which traverses the relationships and determines the correct update order.
Or you can write and use a utility method or routine that builds your cubes in the appropriate order.
Cube Updates and the Result Cache
For any cube that uses more than 512,000 records (by default), the system maintains and uses a result cache. For any combination of update techniques and tools, you should also carefully consider the frequency of cube updates, because any update could invalidate parts of the result cache.
For large data sets, the system maintains and uses a result cache for each cube as follows: Each time a user executes a query (via the Analyzer for example), the system caches the results for that query. The next time any user runs that query, the system checks to see if the cache is still valid. If so, the system then uses the cached values. Otherwise, the system re-executes the query, uses the new values, and caches the new values. The net effect is that performance improves over time as more users run more queries.
When you update a cube in any way, parts of the result cache are considered invalid and are cleared. The details depend upon options in the cube definition (see “Cache Buckets and Fact Order,” earlier in this book). Therefore, it is not generally desirable to update constantly.
How Cube Synchronization Works
This section describes briefly how cube synchronization works. Internally, this feature uses two globals: ^OBJ.DSTIME and ^DeepSee.Update.
First, it is necessary to perform an initial build of the cube.
When InterSystems IRIS® detects a change within the source table used by a cube, it adds entries to the ^OBJ.DSTIME global. These entries are to indicate which IDs have been added, changed, or deleted.
When you synchronize the cube (via %SynchronizeCube(), described later in this chapter), InterSystems IRIS first reads the ^OBJ.DSTIME global and uses it to update the ^DeepSee.Update global. After it adds an ID to the ^DeepSee.Update global, InterSystems IRIS removes the same ID from the ^OBJ.DSTIME global. (Note that in previous versions, the cube synchronization feature used only one global; the newer system prevents a race condition.)
Then InterSystems IRIS uses the ^DeepSee.Update global and updates the fact and dimension tables of the cube, thus bringing the cube up to date.
The following figure shows the overall flow:
The subsections discuss the following details:
When the cube synchronization feature can be used
When the cube synchronization feature cannot be used
Cube synchronization in a mirrored environment
Structure of the cube synchronization globals
When Cube Synchronization Is Possible
You can use the cube synchronization feature in scenarios where all the following items are true:
The base class for the cube is a persistent class (but is not a linked table).
The changed record is a record in that class.
When Cube Synchronization Is Not Possible
You cannot use the cube synchronization feature in the following scenarios:
The base class for the cube is a data connector. (See the chapter “Defining Data Connectors.”)
The base class for the cube is a linked table. (See “The Link Table Wizard” in Using the InterSystems IRIS SQL Gateway).
The changed record is not in the extent of the base class used by the cube. That is, the changed record belongs to another table.
In these scenarios, the cube synchronization feature cannot detect the change, and your application must update the cube manually as described in “Updating Cubes Manually.”
Also, cube synchronization does not affect age dimensions (that is, dimensions whose Dimension type is age).
Cube Synchronization in a Mirrored Environment
If you use Business Intelligence on a mirror server, note that the ^OBJ.DSTIME global is part of the application data and should be mirrored (if it mapped to a different database, for example, that database should be mirrored). The ^DeepSee.Update global is generated by Business Intelligence code and thus is present only in the database that contains the cube definitions and data.
On the mirror server, the databases that store the ^OBJ.DSTIME and ^DeepSee.Update globals must be read/write. Note that you can store both of these globals in the same database, although the above figure shows them in separate databases.
For a discussion of using Business Intelligence on a mirror server, see “Recommended Architecture” in the first chapter of this book.
Structure of the Cube Synchronization Globals
This section describes the structure of the cube synchronization globals. You do not need this information to use cube synchronization; this information is provided in case you wish to use these globals for other purposes.
^OBJ.DSTIME
The ^OBJ.DSTIME global has a different form depending on whether DSINTERVAL is set.
If DSINTERVAL is not set, this global has nodes like the following:
Note that it is possible to manually delete a fact from a fact table without deleting the corresponding record from the source class by using the %SetDSTimeIndex() method.
If DSINTERVAL is set, this global has nodes like the following:
The system removes unneeded entries from the ^OBJ.DSTIME global when you synchronize or rebuild a cube.
^DeepSee.Update
The ^DeepSee.Update global has nodes as follows:
Here is an example:
^DeepSee.Update=3 ^DeepSee.Update("DeepSee.Study.Patient",0,1)=0 ^DeepSee.Update("DeepSee.Study.Patient",0,2)=0 ^DeepSee.Update("DeepSee.Study.Patient",0,100)=0 ^DeepSee.Update("DeepSee.Study.Patient",1,1)=2 ^DeepSee.Update("DeepSee.Study.Patient",1,120)=0 ^DeepSee.Update("DeepSee.Study.Patient",2,42)=0 ^DeepSee.Update("DeepSee.Study.Patient",2,43)=0 ^DeepSee.Update("DeepSee.Study.Patient",2,50)=0 ^DeepSee.Update("DeepSee.Study.Patient",2,57)=0 ^DeepSee.Update("cubes","PATIENTS","dstime")=3 ^DeepSee.Update("cubes","PATIENTS","lastDataUpdate")="64211,63222.68"
The nodes under ^DeepSee.Update("DeepSee.Study.Patient",0) represent the first set of changes, the nodes under ^DeepSee.Update("DeepSee.Study.Patient",1 represent the second set of changes, and so on.
InterSystems IRIS does not automatically remove nodes from ^DeepSee.Update global. For information on purging this global; see “Purging DSTIME.”
Enabling Cube Synchronization
Before you can synchronize a cube, you must enable the cube synchronization feature for that cube. To do so:
Make sure that cube synchronization is possible in your scenario. See “When Cube Synchronization Is Possible,” earlier in this chapter.
Add the DSTIME parameter to the base class used by that cube, as follows:
Parameter DSTIME="AUTO";Copy code to clipboard
The parameter value is not case-sensitive.
Also optionally add the following parameter to the base class:
Parameter DSINTERVAL = 5;Copy code to clipboard
This parameter primarily affects how entries are stored in the ^OBJ.DSTIME global; see “Structure of the Cube Synchronization Globals.” The form of the ^OBJ.DSTIME global has no effect on the behavior of the cube synchronization mechanism.
Recompile the base class and all cube classes that use it.
Rebuild these cubes.
Clearing the ^OBJ.DSTIME Global
This section describes how to clear the ^OBJ.DSTIME global. In some cases, you might want to periodically clear the ^OBJ.DSTIME global. For example, if you are not using cubes in Business Intelligence, you may want to clear the ^OBJ.DSTIME global to free up space.
You can set up a task in the Task Manager to periodically clear the ^OBJ.DSTIME global. To do so, create a new task with an OnTask() method such as the following:
Method OnTask() As %Status { set classname=$ORDER(^OBJ.DSTIME("")) while (classname="") { //check to see if this classname is contained in ^DeepSee.Cubes("classes") set test=$DATA(^DeepSee.Cubes("classes",classname)) if (test'=1) { kill ^OBJ.DSTIME(classname) } set classname=$ORDER(^OBJ.DSTIME(classname)) } q $$$OK }
This task clears ^OBJ.DSTIME entries if they aren’t being used by Business Intelligence cubes. Use the Task Schedule Wizard to schedule the task to run as often as necessary.
Using the Cube Manager
This section describes how to access and use the Cube Manager, which is designed to help you manage cube updates. You use it to determine how and when to update cubes. It adds tasks that rebuild or synchronize cubes at the scheduled dates and times that you choose. This section discusses the following topics:
Introduction to the Cube Manager
Introduction to update plans
How to access the Cube Manager
How to modify the registry details
How to register a cube group
How to specify an update plan
How to build all registered cubes
How to perform an on-demand build
How to unregister a cube group
How to see past cube events
How to restrict access to the Cube Manager UI
The Cube Manager tasks are visible in the Task Manager, which is discussed in “Using the Task Manager” in the System Administration Guide. InterSystems recommends that you do not modify these tasks in any way.
Introduction to the Cube Manager
The Cube Manager enables you to define the cube registry, which contains information about the cubes in the current namespace. In particular, it contains information about how they are to be built, synchronized, or both.
The cube registry defines a set of cube groups. A cube group is a collection of cubes that need to be updated together, either because they are related or because you have chosen to update them together. When you first access the Cube Manager, it displays an initial set of cube groups. Each initial cube group is either a single cube or a set of cubes that are related to each other (and thus must be updated as a group). You can merge these initial cube groups together as wanted. You cannot, however, break up any of the initial cube groups.
Each cube group is initially unregistered, which means that it is not included in the cube registry. After you register a cube group (thus placing it into the registry), you define an update plan for it. The Cube Manager creates automatic tasks that use these update plans. See the next section for details.
Introduction to Update Plans
The update plan for a cube group specifies how and when the cubes are to be updated. Each group has a default plan, which you can modify. You can also specify different update plans for specific cubes in the group. In both cases, the plan choices are as follows:
Build and Synch — Rebuild periodically, once a week by default. Also synchronize periodically, once a day by default.
This option is not supported for a given cube unless that cube supports synchronization (as described earlier in this chapter).
Build Only — Rebuild periodically, once a week by default.
Synch Only — Synchronize the cubes periodically, once a day by default.
This option is not supported for a given cube unless that cube supports synchronization (as described earlier in this chapter).Important:
Before you synchronize cubes from the Cube Manager, it is necessary to build the cubes at least once from the Cube Manager.
Manual — Do not rebuild or synchronize from the Cube Manager.
Instead, use any suitable combination of other tools: the Build option in the Architect and the %BuildCube(), %SynchronizeCube(), %ProcessFact(), and %DeleteFact() methods; the latter three methods are described later in this chapter.
Alternatively, you may manually rebuild the cube with a call to %DeepSee.CubeManager.Utils.BuildCube(). You may also manually synchronize the cube with a call to %DeepSee.CubeManager.Utils.SynchronizeCube().
For each plan (other than Manual), you can customize the schedule details.
For any namespace, the Cube Manager defines two tasks: one performs all requested cube build activity in this namespace, and one performs all requested cube synchronization activity in this namespace. Both of these tasks follow the instructions provided in the cube registry. Both tasks also automatically process cubes in the correct order required by any relationships.
The Cube Manager provides an Exclude check box for each registered group and cube, which you can use to exclude that group or cube from any activity by the Cube Manager. Specifically, the Cube Manager tasks ignore any excluded groups and cubes. Initially these check boxes are selected, because it is generally best to not to perform updates until you are ready to do so.
Accessing the Cube Manager
To access the Cube Manager, do the following in the Management Portal:
Switch to the appropriate namespace as follows:
Click Switch.
Click the namespace.
Click OK.
Click Analytics > Admin > Cube Manager.
If you have not used the Cube Manager in this namespace, it prompts you for information about the cube registry. In this case, specify the following information:
Cube Registry Class Name — Specify a complete class name, including package. This class definition will be the cube registry for this namespace.
Disable — Optionally click this to disable the registry. If the registry is disabled, the Cube Manager tasks are suspended. (Because there are no Cube Manager tasks yet, it would be redundant to disable the registry at this point.)
Update Groups — Specify how to update groups with respect to each other. If you select Serially, the tasks update one group at a time. If you select In Parallel, the tasks update the groups in parallel.
Allow build to start after this time — Specify the earliest possible build time.
You can change all these details later, apart from the class name.
Then click OK.
The system displays the Cube Registry page. You can view this page in two modes (via the View buttons). Click the left View button for tree view or click the right View button for table view.
Tree View
In tree view, the left area of the Cube Manager displays a tree of unregistered cube groups. For example:
The middle area displays a table (initially empty) with information for the registered groups. The following example shows what this table looks like after you have registered a group:
This area is color-coded as follows:
White background — The group or cube is included, which means that the Cube Manager tasks update it. See the Exclude option in “Specifying an Update Plan,” later in this chapter.
Gray background — The group or cube is excluded, which means that the Cube Manager tasks ignore it.
This area also lists (in italics) any subject areas based on a given cube, for example:
Note that you cannot specify update plans for the subject areas, because updates in a cube are automatically available in any subject area based on that cube. (So there is no need and no way to update a subject area independently from the cube on which it is based.)
In the right area, the Details tab (not shown) displays details for the current selection. You can make edits in this tab. The Tools tab provides links to other tools.
When the Cube Manager is in tree view, you can expand or collapse the display of all registered groups, which are shown in the middle area. To do so, use the Expand All or Collapse All button, as applicable, at the top of the middle area. These buttons do not affect the left area of the page, which displays the unregistered groups.
Table View
In table view, the Cube Manager lists all cubes in the current namespace, with their update plans. For example:
This table is color-coded as follows:
White background — The cube is included, which means that the Cube Manager tasks update it. See the Exclude option in “Specifying an Update Plan,” later in this chapter.
Gray background — The cube is excluded, which means that the Cube Manager tasks ignore it.
Pink background — The cube is not registered and therefore has no update plan.
The Group Name field indicates the group to which each cube belongs, and the Group Build Order field indicates the order in which each cube is to be built or synchronized within its group. The Cube Manager computes this order only for cubes in registered groups.
In the right area, the Details tab (not shown) displays details for the current selection. You can make edits in this tab. The Tools tab provides links to other tools.
Modifying the Registry Details
When you first access the Cube Manager, it prompts you for initial information. To modify these details later (other than the registry class name, which cannot be changed):
Display the Cube Manager in tree view.
In the middle area, click the heading that starts Registered Groups.
Edit the details on the right.
For information on the options, see the previous section.
Click Save.
Registering a Cube Group
To register a cube group:
Display the Cube Manager in tree view.
Expand the list of unregistered cubes on the left.
Drag the group from that area and drop it onto the Registered Groups heading in the middle area.
Or display the Cube Manager in table view, click the row for any cube in the group, and click Register Group in the right area.
In either case, the change is automatically saved.
Specifying an Update Plan
To specify the update plan for a cube group and its cubes:
Display the Cube Manager in tree view.
Click the group in the middle area.
In the Details pane on the right, specify the following information:
Name — Unique name of this group.
Exclude — Controls whether the generated tasks perform update activities for cubes in this group. Initially this option is selected, and the group is excluded.
The Cube Manager displays any excluded groups or cubes with a gray background.
Update Plan — Select an update plan.
Note that the Cube Manager does not permit you to use synchronization unless that cube supports it (as described earlier in this chapter). For example, you can choose the Build and Synch plan for the group, but the Cube Manager automatically sets the update plan to Build for any cube that does not support synchronization.Important:
Before you synchronize cubes from the Cube Manager, it is necessary to build the cubes at least once from the Cube Manager.
Build every — Use these fields to specify the schedule for the build task (if applicable).
Synch every — Use these fields to specify the schedule for the synchronization task (if applicable).
Build Cubes Synchronously — Select this to cause the system to build these cubes synchronously (if applicable). If this option is clear, the system builds them asynchronously.
Initially, these details apply to all cubes in the group. If you edit details for a specific cube and then later want to reapply the group defaults, click Apply to All Cubes in Group.
Optionally click a cube within this group (in the middle area) and edit information for that cube in the Details pane on the right.
The options are similar to those for the entire group, but include the following additional options, depending on whether the cube supports synchronization:
Post-Build Code — Specify a single line of ObjectScript to be executed immediately after building this cube. For example:
do ##class(MyApp.Utils).MyPostBuildMethod("transactionscube")Copy code to clipboard
Pre-Synchronize Code — Specify a single line of ObjectScript to be executed immediately before synchronizing this cube. For example:
do ##class(MyApp.Utils).MyPresynchMethod("transactionscube")Copy code to clipboard
If needed, to abort the synchronization, do the following in your code:
set $$$ABORTSYNCH=1Copy code to clipboard
Post-Synchronize Code — Specify a single line of ObjectScript to be executed immediately after synchronizing this cube. For example:
do ##class(MyApp.Utils).MyPostsynchMethod("transactionscube")Copy code to clipboard
In all cases, your code can perform any processing required.
Modify each cube as needed.
Click Save.
When you do so, the Cube Manager creates or updates the cube registry in this namespace. If the Task Manager does not yet include the necessary tasks, the Cube Manager creates them.
Merging Groups
You can merge one group (group A) into another (group B). Specifically this moves all the cubes from group A into the group B and then removes the now-empty group A.
To merge one group into another, use the following procedure. In this procedure, group A must not yet be registered, and group B must be registered.
Display the Cube Manager in tree view.
Drag group A (the group that contains the cubes that you want to move) from the left area and drop it into the group heading of group B (the target group) in the middle area..
Or use the following alternative procedure. In this procedure, both groups must already be registered.
Display the Cube Manager in table view.
In the middle area, click the row for any cube in group A (the group that contains the cubes that you want to move).
On the right, click Merge to another group and then select group B (the target group) from the drop-down list.
Click Merge..
Building All the Registered Cubes
The system provides a utility method that you can use to build all the registered cubes, in the correct order. The method is BuildAllRegisteredGroups() in the class %DeepSee.CubeManager.Utils. This method ignores the schedule specified in the registry but uses the build order specified in the registry.
Before you synchronize cubes from the Cube Manager, it is necessary to build the cubes at least once from the Cube Manager user interface.
Performing On-Demand Builds
The Cube Manager also provides options to build cubes on demand (that is, ignoring the schedule). In this kind of build, the Cube Manager rebuilds the requested cube as well as any cubes that depend on it.
To perform an on-demand build:
Save any changes to the cube registry.Important:
The build options are disabled if there are any unsaved changes.
Select a registered cube. To do so, either:
Display the Cube Manager in tree view and then click a cube in the middle area.
Display the Cube Manager in table view and click a cube that shows Yes in the Registered column.
On the right, clear the Exclude option.
Click Build Dependency List.
The Cube Manager then displays the build dialog box.
Click Build List.
The dialog box displays progress of the build.
When the build is done, click OK.
There are other ways to perform on-demand builds:
Display the Cube Manager in tree view. Click the header of the table in the middle area. Then click Build All Registered Groups. Continue as described previously.
Display the Cube Manager in tree view. Click a cube group in the middle area. Then click Build This Group. Continue as described previously.
Unregistering a Cube Group
To unregister a cube group:
Viewing Cube Manager Events
For certain events, the Cube Manager writes log entries to a table, which you can query via SQL. The table name is %DeepSee_CubeManager.CubeEvent. The CubeEvent field indicates the type of cube event. Possible logical values for this field include the following:
For information on other fields in this table, see the class reference for %DeepSee.CubeManager.CubeEvent.
Restricting Access to the Cube Manager
You may want to manage the cube update schedule without allowing users to change that schedule through the Cube Registry page. To restrict access to the Cube Registry page, set the UserUpdatesLocked attribute to "true" in either the RegistryMap or RegistryMapGroup objects within your saved cube registry. For example:
<RegistryMap Disabled="false" IndependentSync="false" SerialUpdates="false" UserUpdatesLocked="true">
When UserUpdatesLocked is set to "true" for a RegistryMap:
The registry’s Disable setting cannot be changed through the Details tab. For information on accessing this tab, see Modifying the Registry Details.
When UserUpdatesLocked is set to "true" for a RegistryMapGroup:
Each registered group’s Exclude check box is displayed but disabled
Each registered cube’s Exclude check box is hidden
Each registered group’s Update Plan is hidden
Each registered cube’s Update Plan is hidden
The red X button for removing registered groups is removed
The Build Frequency and Synch Frequency columns are left blank
The Build Dependency List is available for cubes, but the Build This Group button is disabled.
Using %SynchronizeCube()
Before you can synchronize a cube, follow the steps in “Enabling Cube Synchronization,” earlier in this chapter.
To synchronize a cube programmatically (that is, without the Cube Manager), call the %SynchronizeCube() method of the %DeepSee.Utils class, which has the following signature:
classmethod %SynchronizeCube(pCubeName As %String, pVerbose As %Boolean = 1) as %Status
For the specified cube (pCubeName), this method finds and applies all changes from the source data that have been made since the last call to this method.
If pVerbose is true, the method writes status information to the console. For additional arguments for this method, see the class reference.
You can call %SynchronizeCube() in either of the following ways:
Call the method from the part of your code that changes the data in the base class.
This is the approach used in the Patients sample.
Periodically call %SynchronizeCube() as a recurring task.
If %SynchronizeCube() displays the message No changes detected, this can indicate that you had not previously rebuilt the cube.
Disabling Cubes
In certain scenarios, you may wish to temporarily disable a cube. This can serve to prevent users from encountering errors when attempting to use a cube while its definition is being edited, or when correcting a known error. Unlike deleting a cube, disabling a cube preserves the code apart from whatever is manually edited. As a disabled cube becomes invisible to the Cube Manager, InterSystems strongly advises against disabling cubes which already have established relationships.
In order to disable a cube, perform the following procedure:
Log in to the Management Portal as a user with administrative privileges.
Ensure you are in the desired Analytics-enabled namespace.
Navigate to Home > Analytics and click GO.
Click Open and select the appropriate cube from the pop-up window.
In the Details pane to the right of the interface, you will see a checkbox labeled Disabled. Click this to disable the cube.
Once you have implemented the changes you wish to implement, you may reenable the cube by unchecking the Disabled box described above. You will be required to rebuild the cube when reenabling.
Purging DSTIME
For historical reasons and for convenience, the phrase purging DSTIME refers to purging the older entries from the ^OBJ.DSTIME global. It is necessary to purge this global periodically because it can become quite large.
To purge DSTIME for a given cube, do the following:
Call the REST API /Data/GetDSTIME. See “GET /Data/GetDSTIME” in Client-Side APIs for InterSystems Business Intelligence. Pass, as an argument, the full name of the source class of the cube.
This REST call returns the last ^OBJ.DSTIME timestamp processed for that source class on a given server. In the case of an async mirror setup, the timestamp retrieved from this REST service will be the most recent timestamp that can safely be purged on the primary production server.
Using the returned timestamp as an argument, call the %PurgeUpdateBuffer() method of %DeepSee.Utils so that you purge ^OBJ.DSTIME up to but not including the timestamp processed on the remote server. The default behavior for this method is to increment the top node of the local ^OBJ.DSTIME so that every purge will provide a new sync point to be propagated to the Business Intelligence server.
Updating Cubes Manually
As described in “When Cube Synchronization Is Not Possible,” it is sometimes necessary to update a cube manually. In these situations, your application must do the following:
Determine the IDs of the affected records in the base class.
Update the cube for those records by calling the %ProcessFact() and %DeleteFact() methods of %DeepSee.Utils.
As input, these methods require the ID of the affected row or rows.
%ProcessFact enables the developer to completely control single-ID inserts or updates into a DeepSee cube. In proivding that capability it bypasses the concurrency protection that are provided within %BuildCube and %SynchronizeCube to prevent multiple processes from attempting the same work.
When including %ProcessFact in custom code, it is strongly recommended that this code prevents multiple calls on the same cube, ID pair. Without this protection there is known potential to perform duplicate inserts into the fact table if %ProcessFact is simultaneously called on the same ID in multiple processes.
The following list provides information on these methods:
classmethod %Process updates the corresponding row of the fact table, the associated indices, and any level tables if affected.
If pVerbose is true, the method writes status information to the console.
classmethod %Delete deletes the corresponding row of the fact table and updates the indices correspondingly.
If pVerbose is true, the method writes status information to the console.
Other Options
This section discusses other options that are more advanced or less common:
How to inject a record into the fact table
How to prebuild dimension tables
How to update a dimension table manually
Using DSTIME=MANUAL
Instead of letting the system automatically update the ^OBJ.DSTIME global, you can update this global at times that you choose. To do so:
Specify DSTIME as "MANUAL" rather than "AUTO".
Then within your application, call the method %SetDSTimeIndex() of the class %DeepSee.Utils whenever you add, change, or delete objects of the class, or when you want to update the ^OBJ.DSTIME global.
This method has the following signature:
ClassMethod %SetDSTimeIndex(pClassName As %String, pObjectId As %String, pAction As %Integer, pInterval As %Integer = 0)Copy code to clipboard
Where:
pClassName is the full package and class name of the object that you have added, changed, or deleted.
pObjectId is the object ID for that object.
pAction is 0 if you updated the object, 1 if you added it, or 2 if you deleted it or want to delete the corresponding fact from the fact table without deleting the object. The value of pAction is used as the value of the resulting ^OBJ.DSTIME node. Note that facts are removed from a cube during synchronization if the corresponding record does not exist in the source class, or if a value of 2 is specified for pAction.
pInterval is an optional integer. If you specify this as a positive integer, the system uses time stamp subscripts in the ^OBJ.DSTIME and ^DeepSee.Update globals. See the discussion of the DSINTERVAL parameter in “Enable Cube Synchronization.”
Then, when you want to update a given cube, call the %SynchronizeCube() method of the %DeepSee.Utils class, as described previously.
Injecting Facts into the Fact Table
In rare cases, you might need the fact table to include records that do not correspond to any source records. In such cases, use the %InjectFact() method of the cube class.
This method has the following signature:
classmethod %InjectFact(ByRef pFactId As %String, ByRef pValues As %String, pDimensionsOnly As %Boolean = 0) as %Status
Where:
pFactId is the ID of the fact. Set this to "" for an insert. On return, this argument contains the ID used for the fact.
pValues is a multidimensional array of fact values. In this array, the subscript is the sourceProperty name (case-sensitive).
pDimensionsOnly controls whether the method affects both the fact table and dimension tables or just the dimension tables. If this argument is true, the method affects only the dimension tables. You use this argument if you prebuild the dimension tables as described in the next section.Caution:
Do not use this method to update dimension tables for levels that are based on source expressions. To add records to those tables, instead use an SQL UPDATE statement.
You can use %InjectFact() to update dimension tables for levels that are based on source properties.
Pre-building Dimension Tables
By default, the system populates the dimension tables at the same time that it builds the fact table. It is possible to prebuild one or more dimension tables so that they are populated before the fact table, if this is necessary for some reason.
To pre-build one or more dimension tables, do the following:
Implement the %OnBuildCube() callback in the cube definition class. This method has the following signature:
classmethod %OnBuildCube() as %StatusCopy code to clipboard
The %BuildCube() method calls this method just after it removes the old cube contents and before it starts processing the new contents.
In this implementation, invoke the %InjectFact() method of the cube class and specify the pDimensionsOnly argument as true.
For details on this method, see the previous section.
For example, the following partial implementation predefines the Cities dimension in the HoleFoods sample:
ClassMethod %OnBuildCube() As %Status { // pre-build City dimension Set tVar("Outlet.Country.Region.Name") = "N. America" Set tVar("Outlet.Country.Name") = "USA" Set tVar("Outlet") = 1000 Set tVar("Outlet.City") = "Cambridge" Do ..%InjectFact("",.tVar,1) Set tVar("Outlet") = 1001 Set tVar("Outlet.City") = "Somerville" Do ..%InjectFact("",.tVar,1) Set tVar("Outlet") = 1002 Set tVar("Outlet.City") = "Chelsea" Do ..%InjectFact("",.tVar,1) Quit $$$OK }
Notes:
It is necessary to provide a unique ID as well as a name for a member.
For completeness, this code should also provide the city population, longitude, and latitude, because the corresponding dimension table contains these values.
It is also necessary to provide values for any higher level members.
Updating a Dimension Table Manually
In some cases, there is no change to your base class, but there is a change to a lookup table that is used as a level. In these cases, you can update the cube in any of the ways described earlier in this chapter. If the only change is to a single dimension table, however, it is quicker to update the level table directly. You can do so via the %UpdateDimensionProperty() method of %DeepSee.Utils.
This method has the following signature:
classmethod %UpdateDimensionProperty(pCubeName As %String, pSpec As %String, pValue As %String, pKey As %String) as %Status
Where:
pCubeName is the name of the cube.
pSpec is the MDX member expression that refers to the level member to update. You must use the dimension, hierarchy, and level identifiers in this expression. For example: "[docd].[h1].[doctor].&[61]"
As a variation, pSpec can be a reference to a member property. For example: "[homed].[h1].[city].&[Magnolia].Properties(""Principal Export"")"
The system uses this argument and the pCubeName argument to determine the table and row to update.
pValue is the new name for this member, if any.
Or, if you specified a member property, pValue is used as the new value of the property.
pKey is the new key for this member, if any.
Specify this argument only if you specify a member for pSpec.
You can make three kinds of changes with this method:
Specify a new key for a member. For example:
Set tSC = ##class(%DeepSee.Utils).%UpdateDimensionProperty("patients","[docd].[h1].[doctor].&[186]",,"100000")Copy code to clipboard
By default, the key is also used as the name, so this action might also change the name.
Specify a new name for a member. For example:
Set tSC = ##class(%DeepSee.Utils).%UpdateDimensionProperty("patients","[docd].[doctor].&[186]","Psmith, Alvin")Copy code to clipboard
By default, the name is the key, so this action might change the key.
Specify a new value for some other property (both Name and Key are properties). For example:
Set memberprop="homed.h1.city.Pine.Properties(""Principal Export"")" Set tSC = ##class(%DeepSee.Utils).%UpdateDimensionProperty("patients",memberprop,"Sandwiches")Copy code to clipboard
Examples
The Patients sample includes utility methods that change data and that use either synchronization or manual updates as appropriate. To try these methods, you can use a dashboard provided with this sample:
Open the User Portal in the namespace where you installed the samples.
Click the dashboard Real Time Updates.
Click the buttons in the upper left area. Each of these executes a KPI action that executes a method to randomly change data in this sample. The action launches the method via JOB, which starts a background process.
Add Patients adds patients.
This action calls a method that adds 100 patients and calls %SynchronizeCube() after adding each patient.
Change Patient Groups changes the patient group assignment for some patients.
This action calls a method that randomly changes the patient group assignment for some percentage of patients and calls %SynchronizeCube() after each change.
Delete Some Patients deletes some patients.
This action calls a method that deletes 1 percent of the patients and calls %SynchronizeCube() after each deletion.
Change Favorite Colors changes the favorite color for some patients.
This action calls a method that randomly changes the favorite color for some percentage of the patients. In this case, the changed data is stored in the BI_Study.PatientDetails table, which is not the base table for the Patients cube. Hence it is necessary to use %ProcessFact() instead of %SynchronizeCube().
This block of code executes an SQL query to return all patients who are affected by the change to the data. It then iterates through those patients and updates the Patients cube for each of them.
Add Encounters adds encounters for some patients.
This action calls a method that includes logic similar to that for BI.Study.PatientDetails; see the previous item.
Change Doctor Groups changes the doctor group assignment for some of the primary care physicians.
This action calls a method that includes logic similar to that for BI.Study.PatientDetails.
These methods write log details to the global ^DeepSee.Study.Log. For example:
^DeepSee.Study.Log(1)="13 May 2011 05:29:37PM Adding patients..." ^DeepSee.Study.Log(2)="13 May 2011 05:29:38PM Current patient count is 10200"
|
https://docs.intersystems.com/irisforhealthlatest/csp/docbook/DocBook.UI.Page.cls?KEY=D2IMP_CH_CURRENT
|
CC-MAIN-2021-10
|
refinedweb
| 6,518
| 55.95
|
namespace to the global filesystem namespace. The conventional
mount point is /dev and the filesystem should be union mounted in order
to augment, rather than replace, the existing entries in /dev. This com-
mand is normally executed by mount(8) at boot time.
The options are as follows:
-o Options are specified with a -o flag followed by a comma separat-
ed string of options. See the mount(8) man page for possible op-
tions ex-
actly the same way as the real controlling terminal device.
FILES
/dev/fd/#
/dev/stdin
/dev/stdout
/dev/stderr
/dev/tty
SEE ALSO
mount(2), unmount(2), tty(4), fstab(5), mount(8)
CAVEATS
This filesystem may not be NFS-exported.
HISTORY
The mount_fdesc utility first appeared in 4.4BSD.
4.4BSD March 27, 1994 2
|
http://www.rocketaware.com/man/man8/mount_fdesc.8.htm
|
crawl-002
|
refinedweb
| 132
| 56.66
|
Implements C++ ABI-specific semantic analysis functions. More...
#include "/opt/doxygen-docs/src/llvm/tools/clang/lib/AST/CXXABI.h"
Referenced by clang::ASTContext::createMangleContext().
Adds a mapping from class to copy constructor for this C++ ABI.
Returns a new mangling number context for this C++ ABI.
Retrieves the mapping from class to copy constructor for this C++ ABI.
Returns the default calling convention for C++ methods.
Returns the width and alignment of a member pointer in bits, as well as whether it has padding.
Returns whether the given class is nearly empty, with just virtual pointers and no data except possibly virtual bases.
|
http://clang.llvm.org/doxygen/classclang_1_1CXXABI.html
|
CC-MAIN-2018-51
|
refinedweb
| 104
| 51.44
|
CcpNmr Analysis Macros
General principles
The CCPN program CcpNmr Analysis was primarily written for NMR spectrum assignment and analysis. It provides a means by which NMR data, such as spectra , chemical shifts and peak lists can be visualised and manipulated. For many analytical and structure determination and tasks Analysis acts a hub and becomes the primary means of managing CCPN data. The following tutorial assumes that you have installed and can start Analysis. The examples mostly require data, for demonstration purposes, and the downloadable demonstration project is sufficient for this.
Macros
A macro is a Python script that extends the functionality of the Analysis program, and takes advantage of the program's existing functionality. For example if you wanted to create a routine that manipulated a list of crosspeaks then Analysis can provide you with a means of loading the data, selecting the input, displaying the output and saving the result. Also, to further expedite the process, Python macros can make use of the large number of high-level functions that already exist within the CCPN programs. Hence for many common or tedious computational tasks you can choose from an array of functionality that is already written and tested, rather than having to write everything yourself.
Macros are not only the recommended way of adding small bits of bespoke functionality to Analysis (and hence CCPN in general), they also provide a convenient means of developing and testing code. Macros can be reloaded at any time, to take account of any changes to your Python script, so that you do not have to constantly restart Analysis while development takes place.
Argument Server
The Argument Server is the means by which all Analysis macros interact with the data in the currently active CCPN project. This is a link from your script to real data, and without it your Python scripts would have to do a whole lot more (and know about the innards of Analysis) just to access simple information. The Argument Server is a Python object that is passed as the first argument to a macro when it is run. It has many methods (functions that you can call from the object) which enable you to get hold of lots of useful data from within the CCPN project, and this will involve the graphical user interface if the user needs to choose between various options. For example, to name just a few things the Argument server can do: Get the current MemopsRoot (project), select spectra, select Restraint Lists, select Peak Lists, provide mouse-selected Peaks, give the current cursor coordinate etc...
Moving on
Eventually, if your Python script works and provides a functionality which would be useful to others, you can begin to think about where next to take the code. Your basic options are:
- Upload the macro unaltered to the CCPN web site for others to use.
- Put the functionality into a stand-alone application, perhaps making use of CCPN's Tkinter based graphical user interface library.
- Petition the CCPN team to include your code and/or ideas into Analysis. There are several instances of this happening.
Execution
For our first example of a macro the aim is simply to introduce the macro system. The macro will be a desperately simple Python script, but you can load it into Analysis so that it appears in a menu, then make some alterations and re-load the code and thus gain an appreciation of how macros are a convenient way to write CCPN-linked programs.
Firstly in a text editor write some simple Python code as follows, taking note that the first argServer attribute is always required and will be passed to the function whenever it is called:
def simpleExampleMacro(argServer):
project = argServer.getProject()
print 'Macro is using project "%s"' % project.name
Save this script to a file with an informative name e.g. "ExampleMacro.py". Beware of choosing a name for the file (which is effectively a Python module) that clashes with inbuilt Python modules like "test" or "math". If in doubt choose a name that is descriptive and erring towards verbose.
Now load this into CcpNmr Analysis by going to the menu option Macros::Organise Macros and click [Add Macro]. In the file browser, navigate to the spot where you saved the .py file (your choice) and click on the line of the file. Then in the lower "function" table click on "ExampleMacro" (or whatever you called your file) and then click [Load Macro]. Returning to the main macro table, double-click in the "In main menu?" column for the row of your script, such that it says "yes". You will now note that your function is mentioned in the Macros section of the main menu. By selecting this new option you will execute the function and will see the name of the project printed on the Python command line (in the window where you started Analysis).
It is a bit unfriendly to print text to the screen on the command line. In normal operation it would be better to display a small dialogue box for the user. To use a dialogue box for the message, change the script to the following:
def simpleExampleMacro(argServer):
project = argServer.getProject()
message = 'Macro is using project "%s"' % project.name
argServer.showInfo(message)
Now select Macros::Reload Menu Macros from the main menu, and only then re-run your script. Hopefully the resulting changes will be obvious. As a macro is simply a Python script you can put anything you like into it, drawing on examples given above for using CCPN's Python API. However, to give you a better idea of how this system may be used, we next show you a real CCPN macro which draws together several elements that have already been covered.
A Real-World Example
The following macro is a script that was written to display the secondary chemical shifts (sequence adjusted) for backbone atoms in a specified molecular chain, i.e. the difference between the observed chemical shift of a resonance and the value expected if it had a random coil structure. Here the macro will be discussed a few lines at a time, but you are expected to put all of the code into a single, contiguous block to create a file that you can test by loading, as detailed above. Don't forget to keep the indentation consistent (as shown in the code below), remembering that Python uses indentation to define block in functions, loops, conditional statements etc.
Firstly, use the def statement to specify the start of a function. We give the function an informative name and we accept one argument argServer which will be passed into the function. On the second line of the function (remembering to indent with spaces) we add an import statement so that we can use a function from the CCPN high-level function library. In this instance, the imported function does as its name suggests; it provides random coil chemical shifts - which we can compare to our data.
def printShiftDevFromCoil(argServer):
from ccpnmr.analysis.core.MoleculeBasic import getRandomCoilShift
Then we define the atomNames variable, which is a list containing the names of the protein backbone atoms that we want to get chemical shifts for. We also initialise a variable called lines, to which we will add lines of text to display the results. Initially this is just the title line containing the column headings that are derived from the atom names padded out to six characters.
atomNames = ['N','H','HA','C','CA',]
columnNames = [' %6.6s ' % an for an in atomNames]
lines = ' : %s\n' % ('|'.join(columnNames))
The next job is to get hold of some CCPN data model object from the project that is currently loaded into Analysis. This macro requires a list if chemical shifts, i.e. an Nmr.ShiftList object and a chain of residues; a MolSystem.Chain object. To get hold of these we simply use the functionality that is built into the Argument Server. If there is more that one Chain or ShiftList in the project then the user will be prompted graphically, in order to choose which one to use.
chain = argServer.getChain()
shiftList = argServer.getShiftList()
By querying the CCPN Chain object we get an ordered list of its residues and determine the length of that list. Note that if we were to call chain.residues we would get a unordered (frozen) set of residue objects and not the sorted list we require.
residues = chain.sortedResidues()
numRes = len(residues)
With the residues in hand we now loop though the list. This macro uses the built-in Python enumerate() function to not only loop through the residues but also provide a counter, which we denote i in this instance. Then inside the loop we initialise a blank list called context, which will contain a subsequence of five residues (in sequence order). We require a subsequence, rather than just a single residue so that we may perform a sequence dependent correction to the random coil chemical shift values.
for i, residue in enumerate(residues):
context = []
We fill in the subsequence by looping from the position two residues before the current residue to the position two residues after the current residue, adding Residue objects as we go with the append() command. Note that we use the counter from the current residue i, to create a new position j, but sometimes when the residue i is at the end of the sequence the j position would fall off the end of the sequence. In such circumstances the end residues are filled with None objects. Also note that j is the output of the range(i-2,i+3), not range(i-2,i+2): i.e. the second argument of the range() command is a limit that is not included in the output list.
for j in range(i-2,i+3):
if 0 <= j < numRes:
context.append(residues[j])
else:
context.append(None)
Next we create a text string to identify the residue. To do this we combine the .seqCode number and the .ccpCode attribute (e.g. "Lys"). Immediately following we define a new blank list for this residue, tableRow, which will contain all of the final results for this residue.
resId = '%3d %s' % (residue.seqCode, residue.ccpCode)
tableRow = []
Given that we have a residue, we can now loop through atoms. We loop through the list of atom names we have and then try to find an Atom of that name in the Residue.
The whole point of the macro is to measure chemical shifts and compare them to the random coil values, so we initialise a value delta, which will store this chemical shift difference. Initially the value is actually a single dash "-" character so that if no chemical shift is found then this null symbol will appear in the output. If there is a value delta will be overwritten with something more informative.
for atomName in atomNames:
delta = '-'
atom = residue.findFirstAtom(name=atomName)
If we cannot find an atom with one of the names it may be that we are looking for an 'HA' in a glycine residue that instead has 'HA2' and 'HA3'. Thus we add the clause that if we have not found an Atom for the name 'HA' we also try 'HA2'. Note that we do not add 'HA2' to our initial list of atom names because we still want to find its data in the 'HA' column, and not have an extra column.
if (not atom) and (atomName == 'HA'):
atom = residue.findFirstAtom(name='HA2')
Then there is a final check to make sure we have an atom. We would expect to be missing CB in glycine for example. If we do have an Atom we find its chemAtom: this is the reference to that kind of atom in the chemical compound template.
We need this kind of object because of the way that the function which provides the random coil chemical shift (imported at the beginning of the script) works. - It uses this template atom and a separate context (residue subsequence). The random coil shift is simply passed back by the function getRandomCoilShift().
if atom:
chemAtom = atom.chemAtom
coilShift = getRandomCoilShift(chemAtom, context=context)
With the Atom objects we follow the links to any assignments. This means getting hold of the AtomSet and ResonanceSet objects. As described earlier these objects link the residues Atoms to the Resonance objects which in turn carry the chemical shift data.
atomSet = atom.atomSet
resonanceSet = atomSet.findFirstResonanceSet()
If we managed to find a resonanceSet object for this Atom then it is assigned. We find the first resonance that it is assigned to and then the chemical shift (Shift object) that belongs in the ShiftList that was chosen at the start.
if resonanceSet:
resonance = resonanceSet.findFirstResonance()
shift = resonance.findFirstShift(parentList=shiftList)
If there is no recorded Shift then we cannot proceed any further. If there is a Shift object, we interrogate its .value attribute and take this away from the random coil value that we already have. Finally the values are used to fill in the text variable delta, which we can print to screen.
if shift:
delta = shift.value - coilShift
delta = '%.3f' % delta
We accumulate a delta text string for each of the atoms (even if we are missing data), and we add this text to the tableRow list which will contain all the delta values for the entire residue.
tableRow.append(' %6.6s ' % delta)
Once we have finished going though all of the atoms for this residue the row of text is complete, we join it with a "|" character to act as a separator, then it is made into a line (being careful that all of the formatting aligns) that joins the end of the other lines.
joinedText = '|'.join(tableRow)
lines += '%s : %s\n' % (resId, joinedText)
And finally we print out the results. We issue a plain print statement to get a blank line and then print the results. These will appear on the Python command line, where Analysis was started from.
print lines
Load and run this macro in Analysis to check that it works. remember to reload if you want to see the effect of any coding changes.
|
https://www.ccpn.ac.uk/v2-software/software/tutorials/python-api-course/ccpnmr-analysis-macros
|
CC-MAIN-2020-34
|
refinedweb
| 2,363
| 69.52
|
by.
Dan Hendricks, president of Open Source Maker Labs Startup 78: Growing the Startup Community in North County By Courtney Cromer...
The post Daily Business Report-July 10, 2018 appeared first on San Diego Metro Magazine.
## Lynis 2.6.6### Improvements* New format of changelog ()* KRNL-5830 - improved log text about running kernel version### Fixed* Under some condition no hostid2 value was reported* Solved 'extra operand' issue with tr command
Open source gives telecom providers more control that will be key for deploying 5G and MEC, says James.
Chris Messina (born January 7, 1981 in USA), aka FactoryJoe, is an open source and open standards advocate currently residing ...
The post Chris Messina (open source advocate) appeared first on Twitter Counter.
Dedicated open source users won't find it hard to use their favorite applications on non-Linux operating systems.
ostechnix: iWant is a free, open source and cross-platform commandline decentralized peer to peer file sharing application.
OpenCV (Open Source Computer Vision Library) is an open source computer vision library and has bindings for C++, Python and Java .
WordPress ontwikkelaar Jason Bobich heeft een open source client-side React app genaamd Just Write gebouwd. Met deze app kunnen gebruikers vanaf de front-end WordPress blogposts bewerken. Over Just Write Hoewel het nog een work-in-progress is, heeft de app al wel een demo waar nieuwsgierige testers mee kunnen experimenteren. Zij kunnen blogposts van WordPress sites beheren
Het bericht Just Write: een client-side React app verscheen eerst op WordPress Handleiding..
There has been a fundamental shift in the way code is developed in the past 15 to 20 years. Today, developers do far more re-using of existing code than creating code from scratch. Taking advantage of the millions of open source libraries available has become standard operating procedure. And this new model comes with tremendous benefits – both for developers, and for the business – allowing both to move and innovate with unprecedented speed. Ultimately, with everyone creating code this way, it has become a necessary practice in order to remain competitive.
But what about security? Shouldn’t open source code be more secure because it’s got millions of eyeballs on it? The reality is that it’s becoming increasingly clear that the “eyeball theory” is simply not playing out, and that open source code is just as vulnerable as in-house-developed code. In fact, in many ways, open source code is less secure, if you consider that reusable code means reusable vulnerabilities, and that a breach in one piece of open source code has far-reaching implications. And the bad guys know that attacking open source code gives them the most bang for their buck – one breach, millions affected. In addition, with the pace of open source libraries being generated, vulnerabilities are also being generated faster than anyone can keep track of.
How should security professionals approach this new threat landscape? If stopping open source library use is not an option, how do you secure its use? Our Virtual Summit, The Open Source Library Conundrum: Managing Your Risk, coming up at the end of this month, sets out to tackle this complicated and critical issue. We’re gathering experts across and beyond our company to give you advice and tips on all sides of this issue – the problem, the solutions, the process, and the technology. Of note is the keynote speaker for this summit, OWASP founder Mark Curphey. CA Veracode recently acquired Mark’s company SourceClear, which has a groundbreaking approach to open source library security – centered around the idea that the accuracy of your security testing of open source code is critical. For instance, you may be using a vulnerable open source library, but are you using the vulnerable part of that library? This approach and Mark’s expertise will be woven throughout the Summit.
Attend the Summit this summer to get:
Hope you can join us; get more details on the Summit sessions and how to register here.
La revue de presse hebdomadaire des technologies Big Data, DevOps et Web, architectures Java et mobilité dans des environnements agiles, proposée par Xebia. Craftsmanship Pourquoi tous les principes SOLID sont mauvais. Qu’entendez-vous par « Event-Driven »? Front 2016 JavaScript rising Stars Verdaccio, un repository privé, gratuit et open source pour npm Webpack, ES 2015, Chrome et source...
L’article Revue de Presse Xebia est apparu en premier sur Blog Xebia - Expertise Technologique & Méthodes Agiles..
Only one person can help you with that, and it is most effective to contact him directly.
I think you all know whom he meant. The whole R world on macOS is pretty much on his shoulders..
The post Only One Person Can Help You with That appeared first on All About Statistics.
Donations in social networks: explore voluntary donations in shareware, freeware, open source using ChipIn, Fundable for films, Wikipedia, Pligg, and social media development. Members want to show what they value..
has anyone tried shotCut? its open source, appears to have a minimalist but elegant UI (NVDA object nav worked fine on this one) and apparently has a ton of keyboard commands you can useso it seems promising.
Memory footprint and startup time are important performance metrics for a Java virtual machine (JVM). The memory footprint becomes especially important in the cloud environment since you pay for the memory that your application uses. In this tutorial, we will show you how to use the shared classes feature in Eclipse OpenJ9 to reduce the memory footprint and improve your JVM startup time.
In 2017, IBM open sourced the J9 JVM and contributed it to the Eclipse foundation, where it became the Eclipse OpenJ9 project. The J9 JVM has supported class sharing from system classes to application classes for over 10 years, beginning in Java 5.
PortableApps.com is proud to announce the release of Mozilla Firefox®, Portable Edition Legacy 52.9.0. It's the Extended Support Release of the popular Mozilla Firefox web browser bundled with a PortableApps.com Launcher as a portable app. It is intended for web developers and extension developers to test against..
Mozilla®, Firefox® and the Firefox logo are registered trademarks of the Mozilla Foundation and are used under license.
Update automatically or install from the portable app store in the PortableApps.com Platform.
MuseScore Portable 2.3.
Mozilla Thunderbird, Portable Edition 52.9.1 has been released. It's the popular Mozilla Thunderbird email client bundled with a PortableApps.com launcher as a portable app..
We.
A shout out is absolutely necessary for Adam Machanic (twitter) for picking the right blog meme that has been able to survive so long in the SQLFamily. This party has helped many people figure out fresh topics as well as enabled them to continue to learn..
INSERT INTO DBA.[AUDIT].[DefTracePermissions]
([SvrName]
,[EventTimeStamp]
,[EventCategory]
,[spid]
,[subclass_name]
,[LoginName]
,[DBUserName]
,[HostName]
,[DatabaseName]
,[ObjectName]
,[TargetUserName]
,[TargetLoginName]
,[SchemaName]
,[RoleName]
,[TraceEvent]
,[ApplicationName])
SELECT [SvrName]
,[EventTimeStamp]
,[EventCategory]
,[spid]
,[subclass_name]
,[LoginName]
,[DBUserName]
,[HostName]
,[DatabaseName]
,[ObjectName]
,[TargetUserName]
,[TargetLoginName]
,[SchemaName]
,[RoleName]
,[TraceEvent]
,[ApplicationName]
FROM OPENQUERY([SomeServer],
'DECLARE @Path VARCHAR(512)
,@StartTime DATE
,@EndTime DATE = getdate()
/* These date ranges will need to be changed */
SET @StartTime = dateadd(dd, datediff(dd, 0, @EndTime) - 1, 0)
SELECT @Path = REVERSE(SUBSTRING(REVERSE([PATH]),
CHARINDEX(''\'', REVERSE([path])), 260)) + N''LOG.trc''
FROM sys.traces
WHERE is_default = 1;
SELECT @@servername as SvrName,gt.StartTime AS EventTimeStamp, tc.name AS EventCategory,spid
,tv.subclass_name
,gt.LoginName,gt.DBUserName,gt.HostName
,gt.DatabaseName,gt.ObjectName,gt.TargetUserName,gt.TargetLoginName,gt.ParentName AS SchemaName
,gt.RoleName,te.name AS TraceEvent
FROM ::fn_trace_gettable( @path, DEFAULT ) gt
INNER JOIN sys.trace_events te
ON gt.EventClass = te.trace_event_id
INNER JOIN sys.trace_categories tc
ON te.category_id = tc.category_id
INNER JOIN sys.trace_subclass_values tv
ON gt.EventSubClass = tv.subclass_value
AND gt.EventClass = tv.trace_event_id
WHERE 1 = 1
AND CONVERT(date,gt.StartTime) >= @StartTime
AND CONVERT(date,gt.StartTime) <= @EndTime
and tc.name = ''Security Audit''
AND gt.TargetLoginName IS NOT NULL
ORDER BY gt.StartTime;');.
Once I query the data, I need to put it somewhere on my administrative server. The table setup for that is very straight forward.
USE [DBA]
GO
IF SCHEMA_ID('AUDIT') IS NULL
BEGIN
EXECUTE ('CREATE SCHEMA [AUDIT]');
END
CREATE TABLE [AUDIT].[DefTracePermissions](
[DTPermID] [bigint] IDENTITY(1,1) NOT NULL,
[SvrName] [varchar](128) NOT NULL,
[EventTimeStamp] [datetime] NOT NULL,
[EventCategory] [varchar](128) NULL,
[spid] [int] NULL,
[subclass_name] [varchar](128) NULL,
[LoginName] [varchar](128) NULL,
[DBUserName] [varchar](128) NULL,
[HostName] [varchar](128) NULL,
[DatabaseName] [varchar](128) NULL,
[ObjectName] [varchar](128) NULL,
[TargetUserName] [varchar](128) NULL,
[TargetLoginName] [varchar](128) NULL,
[SchemaName] [varchar](256) NULL,
[RoleName] [varchar](64) NULL,
[TraceEvent] [varchar](128) NULL,
[ApplicationName] [varchar](256) NULL,
CONSTRAINT [PK_DefTracePermissions] PRIMARY KEY CLUSTERED
(
[DTPermID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
After creating this table, I am ready to store the data. All I need to do is throw the audit query into an agent job and schedule it to run on a regular schedule. For my purposes, I usually only run it once a day...
La journée Oracle Code, du 3 juillet dernier, a été l’occasion de voir les logiciels et plateformes Oracle en oeuvre et les dernières nouveautés et tendances. Parmi les sessions intéressantes, nous pouvions voir MySQL Document Store. MySQL gère le stockage orienté document avec un soupçon de SGBDR, de NoSQL et de JSON Document. JSON Document est un objet avec une structure de données. Cette structure est implicite dans le document. Il est compact et standardisé. Ce format est supporté par défaut dans MySQL (via ECMA-404). De nombreuses fonctions lui sont rattachées : recherches ou encore agrégations, avec la possibilité de faire des requêtes. MySQL 8 rajoute d’ailleurs quelques fonctions à la partie JSON.
La partie Document Store est un élément non négligeable dans la base de données. Il ne possède pas de schéma (schemaless), il possède une structure de données flexible et bien entendu, il est JSON « ready ». Et on peut lui appliquer le principe CRUD : création, lecture, mise à jour et suppression. MySQL veut concilier, comme d’autres bases, le monde SQL et NoSQL. Pour ce faire, on dispose, sur la partie Document Store de plusieurs composants pour les développeurs : MySQL X Plugin, X Protocole, cluster InnoDB, de nouvelles API, d’un shell MySQL et des connecteurs. Si on résume, MySQL supporte donc le modèle hybride relationnel et NoSQL avec différents moteurs et de modèles de stockages.
Comme vous le savez, Oracle possède son offre de Cloud public : Oracle Cloud. Une des sessions permettait de voir comment utiliser Terraform, et donc l’infrastructure as code dans ce contexte et avec l’idée de DevOps (il faut bien le caser quelque part -:)). Terraform est un outil d’infra as code avec des versions open source et entreprises. La session a permis d’installer l’outil dans le cloud infrastructure d’Oracle puis de voir comment on crée son code d’infrastructures. Mieux vaut regarder les sessions en replay.
Autre session qui nous a bien intéressé : the path to pair programment in Che with Atom Teletype. Le speaker rappelle quelques fondamentaux sur Eclipse Che : il s’agit d’une version de l’IDE avec une interface web, des espaces de travail dans des conteneurs eux-mêmes pouvant s’exécuter avec un langage serveur tel que Eclipse JDT. L’outil supporte LSP, Language Server Protocol que l’on retrouve aussi dans Visual Studio. La partie co-édition du code a été la partie centrale de la session.
L’idée est de faire de l’édition de projets / codes à la Google Docs. Il s’agit de faire collaborer les développeurs pour faire du mentorat de code, des revues de code ou de l’édition commune. Atome Teletype est une extension aux éditeurs Atom pour faire du pair programmation et de l’édition concurrente en direct. On dispose de plusieurs librairies : teletype-client, teletype-server et teletype-crdt avec une partie communication basée sur CRDT (conflit-free replicated data type) et WebRTC. Typiquement, avec Teletype, on dispose d’un portail host et x invités. Il s’occupe de partager la session de programmation et partage les fichiers du portail host. Si vous ne connaissez, jetez-y un coup d’oeil.
Java a été un thème central de la journée. Parmi les sessions, on pouvait voir « boîte à outils mémoire de la JVM ». Ah la fameuse gestion mémoire, on pourrait en écrire des livres dessus. Il existe des mécanismes pour mesurer les performances, définir la taille mémoire. Par exemple, vous pouvez activer les logs du ramasse-miettes. Combien de développeurs Java y pensent ? En JRE 8, on peut utiliser le Parallèle GC. jVisualVM est un autre outil pour visualiser la mémoire de la JVM. Vous pouvez regarder du côté de GCViewer, les logs (pensez aux logs, je l’ai peut être dit plus haut). Pour éviter un out of memory error (on l’adore toutes et tous ce truc), augmentez la taille de la heap, redémarrer de temps en temps la JVM (ben si, pour la purger et la remettre en état). En tout cas, une session que nous vous recommandons !
Terminons par la session : accelerated Oracle JET - Visual JavaScript / HTML5 Cloud Development. Le développement web c’est un peu bord… la jungle : backbone, jQuery, metteur, Angular, React, etc. Oracle JET est un toolkit open source orienté entreprise pour vous aider à développer en JS, HTML5 et REST. Il supporte de nombreuses librairies open source comme Knockout.js, jQuery, Hammer, RequireJS. Et Oracle a introduit ses propres librairies : composants UI, modèles, internationalisation, responsive, etc. L’outil peut donc servir à développer des applications mobiles. L’idée de base est de proposer un développement visuel : approche low code, utiliser les technologies les plus récentes, focus sur les applications métiers. Bien entendu, on peut manipuler directement le code, ajouter la logique que l’on souhaite, étendre la plateforme (via des composants UI ou des librairies JS).
Découvrez l’ensemble des sessions d’Oracle Code :
François Tonic had a lively panel that included the COPU (Chinese Open Source Promotion Union), and representatives from local universities, George Neville-Neil, Alibaba, Stephen Walli of Microsoft, the President of the FreeBSD Foundation, and others. The panel was of particular interest as I was able to hear some of the struggles the local community has had, including respecting copyright, language and cultural barriers, and ensuring economic viability.
I look forward to continuing to assist the Chinese community in being more productive with not only Postgres but also Open Source. There is a wealth of culturally rich, intelligent, and inventive talent available that the PostgreSQL Global Development Group has yet to tap. It will be an exciting few years as both cultures adapt to work together, the contributor list grows, and we start seeing prominent Chinese developers assisting in the growth of PostgreSQL.
We make open source tools that enable you to provision, secure, and run any infrastructure for any application.
read more.
Xen is open-source royalty. This hypervisor, which runs and manages virtual machines (VMs), powers some of the largest clouds. You know their names: Amazon Web Services (AWS), Tencent, Alibaba Cloud, Oracle Cloud, and IBM SoftLayer. It's also the foundation for VM products from Citrix, Huawei, Inspur, and Oracle. But, with the release of its latest edition, Xen Project Hypervisor 4.11, there are major changes under the hood....
As a Red Hat Premier Certified Cloud and Service Provider (CCSP), ORock Technologies architected ORockCloud as a "pure-play" Red Hat cloud that incorporates a suite of Red Hat's open source solutions for enhanced flexibility, security features and control. These include: Red Hat Enterprise Linux; Red Hat OpenStack Platform; Red Hat Virtualization; Red Hat Ceph Storage; Red Hat CloudForms; Red Hat Ansible Tower; Red Hat Satellite; and associated cloud AP.
..
Apple is said to be working on some new domain-specific compilers.
Apple compiler engineer Chris Bieneman has posted a new job ad to the llvm-dev mailing list on Monday.
Apple is said to be working on some new domain-specific compilers.
Apple compiler engineer Chris Bieneman has posted a new job ad to the llvm-dev mailing list on Monday.
An open source credit-card reconfigurable instrumentation board from Red Pitaya in Slovenia is being used for a new radar warning and information system (RAWIS) for disaster management..
As AT&T continues down its network virtualization efforts using the open-source Open Networking Automation Platform (ONAP), the operator has acquired cybersecurity firm AlienVault, which uses open-source software to provide what the companies call “threat intelligence.” Financial details of the transaction were not disclosed; AT&T expects the deal to close in Q3 this year.
Malware has been discovered in at least three Arch Linux packages available on AUR (Arch User Repository), the official Arch Linux repository of user-submitted packages.
The malicious code has been removed thanks to the quick intervention of the AUR team.
Malware has been discovered in at least three Arch Linux packages available on AUR (Arch User Repository), the official Arch Linux repository of user-submitted packages.
The malicious code has been removed thanks to the quick intervention of the AUR team.
One day past the release of upstream Wine 3.12, the downstream Wine-Staging 3.12 is now available that continues incorporating hundreds of experimental/testing patches atop these bi-weekly Wine releases..
Faction Warfare is coming to Albion Online on July 31st with the next major update named Merlyn and it does sound quite promising..
Laziness is a desirable trait for software developers, and they admit so themselves. For example, Philipp Lenssen, a well-known German-born developer who ran a successful blog Google Blogoscoped, once wrote:
"Only lazy programmers will want to write the kind of tools that might replace them in the end. Only a lazy programmer will avoid monotonous, repetitive code. The tools and processes inspired by laziness speed up production."
In addition to developing tools that help others, each successful developer also has a special kit of must-have tools that allow them to enjoy a little laziness by taking on some of their responsibilities.
In this article, we’re going to review the best tools that you can also add to your own kit.
If you’re not taking advantage of time management apps, you’re definitely missing some great opportunities to improve your daily schedule and free more time for doing other things than work.
Rescue Time is a great option to use. This time management app gives you a clear picture of how you’re using your computer throughout the day, thus helping you to understand your daily habits.
To help you improve your daily routine, the app generates a daily report to show you what things are stealing your precious time. Most users of Rescue Time say they are shocked to discover how much time they waste every day that they could potentially use for something better.
The next item on our list is a great local AWS cloud stack that provides an easy-to-use and test framework for developing cloud applications. LocalStack creates a testing environment on your local computer while allowing to maintain the functionality of the real AWS cloud environment.
The free version of LocalStack has core AWS services, community updates, bug fixes, and other helpful functions so you can enjoy cost-effective testing on your local machine for no cost.
Email marketing continues to be a big source of revenues for online businesses in 2018, so more and more companies are looking for developers to design responsive emails for their campaigns.
That’s where Topol.io comes in. A visual, drag-and-drop HTML editor for creating such emails has a wide variety of elements to attract the attention of receivers and entice them to click on CTA buttons.
The tool was developed by professional marketers and web designers and provides a number of templates for you to work with (you can also start from scratch). The editor has an intuitive environment, so you’ll be creating beautiful emails in no time.
This is an internal deep learning tool designed for developers looking to get their ideas off the ground more easily. According to the developers of Kur, it allows to design, train, and evaluate deep learning models without ever needing to code, which is something that can accelerate the process of building and training deep learning models.
Collaboration on models and shared learning is also possible with the tool, so anyone interested in getting more knowledge of deep learning can share their models and work with others.
Scott Stephenson, CEO of Deepgram, the company that developed Kur, had this to say about the usefulness of the tool: "You can start with classifying images and end up with self-driving cars. The point is giving someone that first little piece and then people can change the model and make it do something different."
If you’re looking for a great alternative to stock images, you just found one. unDraw is essentially a large online collection of beautiful images that any developer can use free and without attribution to create apps, websites, and other products.
Each of the images has an editable code so you can animate with plain css and change colors to make sure that the image fits your project. Also, you’ll enjoy the fact that you can scale the images on UnDraw without quality change, add own colors, embed codes directly into your html, and use on-the-fly generator to customize main color.
This is one of the most valuable resources in terms of web typography. The quality of font selection is unbelievable and you can use them for personal purposes such as formatting a professional essay and commercial purposes such as website fonts.
Since the use of typography as an essential design element is a huge trend in web development now, Google Fonts will be a highly useful tool. Moreover, all fonts are optimized for interfaces, reading on mobile devices, and UI-optimized.
Here are some examples of a beautiful use of Google Fonts from WebpageFX for your inspiration.
A useful tool for developers who need to present data on various screens. It provides the tools one needs to present data in a professional and attractive way on any screen, from a tablet to a wall-mounted TV.
Drag-and-drop tools, premade widgets, and many other features allow to edit data easily and quickly.
This tool is one the most advanced team collaboration hubs for programmers out there. Organized conversations, searchable history, channel for collaboration, file sharing, voice and video calls, drag-and-drop images, videos, PDFs and other files, feedback, and easy threat management – all of this is possible with Slack.
Programmers who use Slack for team projects also love that it allows integration with Dropbox, Google Drive, SalesForce, and many other apps they use in their work (over 1,000 apps can be connected).
According to Q4 2017 Website Security Insider analysis from SiteLock, an average website is attacked 44 times a day, and about 1 percent of all websites out there is hacked every week. A major reason of why a large share of these websites are hacked is a weak (or even not-so-weak password).
Passbolt is a free, open source, self-hosted password manager that protects passwords using the latest technology and is specifically built for teams of developers.
The last item on our list is a go-to code editor of choice for thousands of web developers around the world. The reason why they chose Visual Studio Code is its extensibility, customizability, integrated Git Control, IntelliSense, and many other helpful features, all for free!
As you can see, lazy doesn't have to mean unproductive. Most developers are work-aholics so they don't have to work.
Do you have an tip or trick to make your life easier as a developer? Which tool makes you lazy? Post your comments below and let's discuss.
دیگر همه میدانند وردپرس به علت دسترسی راحت به پنل مدیریت و متن باز (open source) بودنش محبوب تمام جهان شده است. موضوع مهمی که در این سیستم وجود دارد، تیم قدرتمندی است که با دقت به بررسی باگهای امنیتی میپردازند تا مشکلات را در هر نسخه از وردپرس برطرف کنند. اما هکرها همیشه منتظر هستند تا شکافی را بیابند و دست به کار شوند. حال این شکاف میتواند در هسته وردپرس باشد، در قالب یا افزونهای که استفاده میکنید یا هر آنچه به وردپرس […]
نوشته ۵ تهدید امنیتی در وردپرس و راه حل آنها اولین بار در بیست اسکریپت. پدیدار شد.
Presentation Slides »
La aplicación Teléfono (Google Phone), que gestiona las llamadas telefónicas de forma nativa en todos los teléfonos Pixel, Nexus y aquellos terminales cuya capa de personalización no afecte a la app, es especialmente destacable por su función de filtrado de llamadas de spam.
Gracias a una base de datos con la que cruza todas las llamadas entrantes, que gestiona en cada teléfono, Google es capaz de detectar y marcar visualmente aquellas llamadas que otros usuarios han denunciado como SPAM. Ahora, también avisará cuando detrás de una de estas llamadas se encuentre un robot telefónico.
Desde que entró en funcionamiento esta función, la aplicación Teléfono es capaz de avisarnos de qué números de teléfono esconden un comercial particularmente pesado y/o supongan SPAM telefónico. Cualquier usuario puede bloquear un teléfono y reportarlo como SPAM. Cuando estos son suficientes, el número de teléfono se marca de forma especial para los siguientes a los que telefonee.
Esta función ya estaba en marcha desde la versión 19 de la aplicación y se sumó a las posibilidades del Caller ID, uno de los servicios iniciales de Teléfono de Google. La novedad llega de la mano de XDA Developers que, rebuscando en el código de la última beta de Google Phone 22 han descubierto un string interesante.
Según el código encontrado en la APK de la aplicación Teléfono de Google, estaría muy cerca de lanzarse por fin una herramienta con la que el Android Open Source Project lleva trabajando unas semanas: Call Screen. Esta nueva función usaría transcripciones de las llamadas en tiempo real para informarte si la llamada proviene de un robot.
No deja de ser irónico que la misma empresa que está haciendo más ruido con las llamadas artificiales (y, a su vez, empujando más la tecnología que permite comunicarse por vía telefónica con robots que suenan completamente humanos) también trabaje en un modo para identificarlos.
Una de las polémicas que despertó Google Duplex cuando se presentó fue, precisamente, que no parecía identificarse como robot. Con el Call Screen, es la misma Google la que permitirá identificarlos con una transcripción en directo, aunque el servicio aún tiene que entrar en funcionamiento.
La transcripción se realizará de manera local y no requiere conexión a internet de ningún tipo, así que no habría por qué temer que Google accediera a una copia escrita de nuestras conversaciones telefónicas, aunque se deberán asegurar que esta información tampoco es accesible para ninguna aplicación que tenga permisos para gestionar las llamadas telefónicas.
Vía | XDA Developers
En Xataka Android | TrueCaller, a fondo: el mejor aliado contra el spam telefónico
- La noticia
Google transcribirá las llamadas para detectar robots y mejorar el filtrado de SPAM
fue publicada originalmente en
Xataka Android
por
Toni Noguera
.
If you are looking for an enterprise-class open source network, application and server monitoring tool, there is no better option than Nagios. This article ...
The post Nagios: A Modular Monitoring Tool for Infrastructure and Networks appeared first on Open Source For You.
Blockchain doesn’t make sense to many people but with the introduction of this phone the concept will be easy to understand and develop further ...
The post Blockchain Phone is Real and it is Arriving appeared first on Open Source For You.
Liferay commerce and liferay analytics cloud to help business users and developers deliver insight-driven experiences to acquire and retain customers Liferay announced the release ...
The post Digital Experience Products to Support Customer Care appeared first on Open Source For You.
The power of Docker images is that they’re lightweight and portable—they can be moved freely between systems. You can easily create a set of standard images, store them in a repository on your network, and share them throughout your organization. Or you could turn to Docker Inc., which has created various mechanisms for sharing Docker container images in public and private.
The most prominent among these is Docker Hub, the company’s public exchange for container images. Many open source projects provide official versions of their Docker images there, making it a convenient starting point for creating new containers by building on existing ones, or just obtaining stock versions of containers to spin up a project quickly. And you get one private Docker Hub repository of your own for free.
To read this article in full, please click here
Servidor de Backup (Licença GPL).
Os clientes rodam em ambientes Linux e Windows.
O UrBackup é um sistema de backup Client/Server, Open Source, que através de uma combinação de backups de imagens e arquivos realiza segurança de dados e um rápido tempo de restauração.
Pré Requisitos de S....
So, can someone who uses only free and open source software find games that are polished enough to present a solid gaming experience without compromising their open source ideals? Absolutely. While open source games are unlikely to ever to install and play it..
Press Coverage
Geospatial Blog, USA:
For help using ZAP:
Information about the official ZAP Jenkins plugin:
To learn more about ZAP development:
Justification for the statements made in the tagline at the top;)
Popularity:
Contributors:
Hasura GraphQL Engine Aimed at Companies Seeking to Modernize IT and Fast-Track Application Development Cycles by adopting GraphQL
(PRWeb July 11, 2018)
Read the full story at
Dans la pléthore des gestionnaires de mots de passe disponibles, il faut désormais compter Firefox Lockbox. Pourquoi Mozilla a-t-il créé un coffre-fort mobile dédié, alors que les versions iOS et Android de Firefox savent synchroniser les mots de passe avec la version de bureau ? Sûrement parce que les utilisateurs de bureau n’utilisent pas Firefox sur mobile.
En se connectant avec son compte Firefox, on retrouve donc dans Lockbox tous les mots de passe enregistrés dans le navigateur. L’application est extrêmement limitée : on peut juste consulter les mots de passe et les copier. Pas d’édition, ni d’extension, peu d’options de tri…
Ce dépouillement s’explique par le fait Firefox Lockbox est une expérimentation (elle fait partie du programme Test Pilot) visant à mesurer l’intérêt du public. L’application n’est pas encore disponible dans l’App Store français pour le moment, ni sur Android. Elle est open source et a un forum dédié pour partager son avis et ses idées.
Hace unos días ARM creaba un sitio web curioso: riscv-basics.com, ahora desaparecido pero accesible a través de Internet Archive. Esas páginas fueron creadas con un solo objetivo: crear miedo, incertidumbre y dudas con respecto a la plataforma RISC-V.
Lo curioso es que el efecto ha sido el contrario. ARM ha tenido que retirar la página ante las críticas de sus propios empleados, y la plataforma RISC-V ha salido reforzada a pesar de estar aún en pañales. Justo lo contrario de lo que pretendían en ARM, donde parece que la filosofía Open Source de dicha iniciativa plantea una amenaza real a su posición de privilegio.
Ese sitio web creado por ARM la firma hablaba de cinco áreas en las que RISC-V planteaba propuestas aparentemente débiles y con futuro incierto. Se centraban en el coste, el ecosistema, la fragmentación, la seguridad y la garantía de sus diseños.
Las críticas trataban en todos los casos de destacar las barreras de esta especificación para núcleos de proceso Open Source que algunos ven como una alternativa interesante para el futuro. Mientras que un fabricante debe pagar a ARM una licencia para usar sus diseños (y más aún si quiere modificarlos), no hay royalties para quienes quieren aprovechar los diseños RISC-V.
Hay ya diversas empresas tratando de impulsar el diseño y fabricación de estos chips, pero en ARM dejaban claro que sus soluciones eran comparativamente más baratas (a pesar de no ser Open Source) y disfrutaban de un ecosistema muy nutrido (cierto, pero RISC-V está muy verde) y una fragmentación casi inexistente debido a que solo ellos se encargan de stos diseños.
Aún así los diseños ARM han ido derivándose gracias a empresa como Apple o Samsung, que han ido más allá de las propuestas de ARM, por lo que esa fragmentación, aunque no importante, existe. Es cierto que esa apertura de RISC-V plantea mucha mayor diversidad en este ámbito, pero es imposible saber a estas alturas si eso será o no un problema si la plataforma acaba cuajando.
Tampoco hay certezas en temas de seguridad. Los ARM se vieron afectados por el caos que provocaron Spectre y Meltdown, pero no ocurrió lo mismo con RISC-V, que no tenían esos niveles de ejecución especulativa.
A la hora de ofrecer garantías de diseño nuevamente las certezas son pocas: es verdad que ARM es sólida en este ámbito, pero no hay razón para pensar que la RISC-V Foundation quiera descuidar ese apartado y no tratar de garantizar que los desarrollos RISC-V no cumplen todos los requisitos necesarios para que tengan futuro.
La campaña de ARM ha provocado según The Register que los propios empleados de la empresa critiquen esta acción. A esas críticas se han unido las de diversas personalidades del mundo Open Source y de la comunidad de expertos.
ARM’s negative campaign against RISC-V can only backfire. Also, their points are kind of weak, this was attempted before against open source, and all it achieved was eggs on people’s faces— Miguel de Icaza (@migueldeicaza) 9 de julio de 2018
ARM’s negative campaign against RISC-V can only backfire. Also, their points are kind of weak, this was attempted before against open source, and all it achieved was eggs on people’s faces
El mensaje de Miguel de Icaza, co-creador de GNOME y de Xamarin (ahora parte de Microsoft) es por ejemplo revelador, y de hecho ataques similares fueron lanzados contra Linux en el pasado con un resultado similar: en lugar de generar miedo, incertidumbre y dudas (FUD, por 'Fear, Uncertainty and Doubt') el efecto era el contrario, y estas campañas han hecho que este sistema operativo salga reforzado una y otra vez.
Con la plataforma RISC-V ha ocurrido lo mismo, y el movimiento le ha dado una publicidad gratuita que los que apoyan esta alternativa seguro que aprecian. Curiosamente no ha habido comentarios a la campaña por parte de la RISC-V Foundation, que se ha mantenido neutral en una batalla que no buscaba y que ha ganado sin pretenderlo.
Ahora, claro, queda por ver si RISC-V realmente puede plantear una amenaza a los diseños de ARM. Es lo que intentan por ejemplo empresas como SiFive, y algunos ya apuestan por una futura Raspberry Pi basada en uno de estos procesadores. Sería un interesante comienzo para acercar estos micros al gran público, desde luego.
Vía | The Register
En Xataka | RISC-V frente a ARM y x86: el amanecer de los procesadores personalizados es Open Source
Desafiando todos los obstáculos: los impactantes retratos y fotografías de acción del Embajador de Canon Samo Vidic
ZeroPhone es el móvil Open Source de 50 dólares basado en una Raspberry Pi Zero
RISC-V frente a ARM y x86: el amanecer de los procesadores personalizados es Open Source
- La noticia
Lo único que ARM ha conseguido al ir contra RISC-V es darle publicidad a un rival en pañales
fue publicada originalmente en
Xataka
por
Javier Pastor
.
Litecoin presupune un proiect open source, transferul de LTC bazandu-se pe un protocol cryptografic deschis. Crearea LTC a fost inspirata de cryptomoneda-rege, de catre Charles Lee, angajat Google, cu sprijinul membrilor din comunitatea Bitcoin. Lansarea Litecoin a avut loc in octombrie 2011. In noiembrie 2013, valoarea Litecoin a cunoscut o crestere masiva, de la aproximativ […]
The post Vinde Litecoin rapid si simplu pe platforma de trading appeared first on Bitcoin Romania.
Originally posted on:
Recently HA! got mentioned on DotNetRocks. (If you're interested, it's here at around the 30 minute mark.)
The whole show, about Open Source, is actually quite good. So even if you don't care about HA!, give the show a listen.
Originally posted on:
Yesterday, when I mentioned the possibility of taking HA! open source, I got some terrific feedback (more than expected, in fact) in my comments section and also some private emails. One of the emails suggested I look into the Microsoft Shared Source Initiative instead of some of the more restrictive Open Source licensing options I had mentioned previously. (FYI: The licenses published on this site are intended for people using MS source code, but it wouldn't take much tweaking to adapt one of them to my needs here. The Community License is a good example.)
Along with this licensing model, a potential new home for HA! was recommended, in the form of CodePlex. I haven't spent much time there yet, but if I do end up cracking open the source code for HA! this seems like a good place to be.
As always, your thoughts and (likeminded or dissenting) opinions are welcome on this subject. Just keep it friendly.
Percona announces the release of Percona Server for MongoDB 3.6.5-1.3 on July 11, 2018. Download the latest version from the Percona web site […]
The post Percona Server for MongoDB 3.6.5-1.3 Is Now Available appeared first on Percona Database Performance Blog. Partner Conference Asia Pacific -- Red Hat, Inc. (NYSE: RHT), the world's leading provider of open source solutions, today showcased the uptake of Red Hat OpenShift Container Platform in Asia Pacific by many of the region's leading independent software vendors (ISV).."
With few exceptions, it seemed like every 3D printer at the first inaugural East Coast RepRap Festival (ERRF) was using a hotend built by E3D. There’s nothing inherently wrong with that; E3D makes solid open source products, and they deserve all the success they can get. But that being said, competition drives innovation, so we’re particularly interested anytime we see a new hotend that isn’t just an E3D V6 clone.
The Mosquito from Slice Enginerring is definitely no E3D clone. In fact, it doesn’t look much like any 3D printer hotend you’ve ever seen before. Tiny and spindly, the look …read more
The Open Source Electronic Health Record Alliance (OSEHRA) will host its 7th Annual Open Source Summit: The Open Road for Government Innovation from Wednesday, July 18 through Friday, July 20, 2018 at...
Read the full story at
After mentioning a vague roadmap to open-sourcing the dev.to codebase, we've finally decided on a date for the launch: August 8 (8/8)..
KernelShark, the open source graphical user interface or tracing data that gives users a view of the events happening within the Linux kernel, has proven useful for many kernel developers—but it’s not without its limitations. That’s why we’re now in the process of completely rewriting KernelShark, rebuilding it on a more solid platform and readying it
The post KernelShark — The Future of Trace Data Visualization appeared first on VMware Open Source Blog..
Sponsors
changelog2018
Featuring
Notes and Links
OSTI launched the alpha version of DOE CODE in November 2017. DOE CODE is the new software services platform and search tool for software resulting from DOE-funded research. DOE CODE is an open source platform that replaces the Energy Scien• Young Girls (“Hi, I’d like to buy some...” This one is not going to end well AT ALL.)• Mowing the Lawn • Loaf• White-Haired Lady (DEA, your fascination with women at either end of the age spectrum is kinda freaking me out...)• Shoes•.
[ Comment on:
Stuff I don't like:.
On one side you have the world’s richest, who have so much money they couldn’t spend it in ten lifetimes, so they invest heavily in space exploration and escaping planet Earth because they have accepted society is headed to an inevitable collapse (and it likely is), which they (and the millions they have sway over) largely contribute to. So they weasel around at secret retreats wondering how to keep their small armies of security forces loyal and foreign sanctuaries secure when money ceases to have any value and the dying hordes lay siege to their oases.1
On the other side are poor people with sensible ideas to create viable, open solutions now that can help counter society’s ills immediately while there’s still time to stave off disaster. Yet they need a moderate sum for seeing progress through to success, struggling to find what would be a drop in the lake for any one of the billionaire shitbags who have already thrown in the towel on us.2
Humanity does not make sense. I’m not sure it ever did. But one thing that does make sense? Supporting projects like OSE.
Maybe we’ll get lucky and the billionaires will rocket off to Mars early, we’ll save the Earth, and be free of the poopsacks too. \o/
__________________________________
1. Survival of the Richest
2. Open Source Ecology and its Global Village Construction Set
Le Paris Open Source Summit, 1er événement open source européen, lance son appel à conférences. Plus de 200 conférences seront animées les 5&6 décembre prochains aux Docks de Paris. Le comité de programme 2018 invite tous les acteurs de l’open source et du numérique ouvert à proposer une conférence. Trois thématiques sont retenues pour cette édition 2018 : TECH, SOLUTIONS et ECOSYSTEM. L'appel à conférences est ouvert jusqu'au vendredi 31 août 2018 minuit sur : 3 THEMATIQUES A L'HONNEUR TECH La thématique TECH est destinée aux technophiles, à ceux qui font tourner nos infrastructures, celles-là même où l'adoption massive du logiciel libre a commencé, à ceux qui bâtissent des applications et globalement à tous ceux qui innovent encore et toujours avec les technologies de demain issues de l’open innovation. Elle ouvrira le capot des applications d’aujourd’hui pour explorer toutes les couches qui les font tourner – l’infrastructure du datacenter (cloud, containers), la gestion des plateformes dans une dynamique DevOps et les innovations technologiques autour des développements, des données, de l’intelligence artificielle et de l'utilisateur final … sans oublier les sujets encore émergents ! SOLUTIONS La thématique SOLUTIONS est destinée aux utilisateurs et décideurs, ou toute personne / organisation qui souhaite trouver des réponses opérationnelles en Open Source. Un accent sera mis sur des témoignages, des retours d'expérience de réalisations de projets, des présentations de solutions répondant à des besoins métiers et/ou transverses. En éclairant les tendances majeures du secteur, cette thématique a pour objectif d'accompagner les utilisateurs et clients dans leurs choix de solutions Open Source. ECOSYSTEM La thématique ECOSYSTEM explore les enjeux du Libre bien au-delà du logiciel et s’ouvre aux autres modèles ouverts : Open Data, Open Hardware, Open Content… qui contribuent à rendre l’ouverture mainstream dans notre société, y compris dans nos textes législatifs. Dans l’optique de renforcer le rôle crucial du numérique ouvert dans les transformations numériques, les questions de transparence, de souveraineté et plus largement d’éthique seront centrales, répondant à des enjeux clés en matière de confiance. Une tribune particulière sera offerte aux acteurs des écosystèmes d’innovation ouverts qui font le choix de la mutualisation en développant des communs pour innover plus efficacement dans leur secteur : santé, finance, spatial, mobilités, culture, droit, énergie, open gov etc.LE FIL ROUGE DU PROGRAMME 2018 : OPENING THE DIGITAL REVOLUTION L’édition 2018 mettra en lumière l’importance de l’Open Source dans la révolution numérique et son impact croissant dans la transformation de nombreux métiers / secteurs, poussée par les technologies émergentes comme la Blockchain, l’Internet des objets, le Cloud, l’Intelligence Artificielle ou le Big Data. Le numérique ouvre d’énormes opportunités d’innovations qui nécessitent cependant un contexte de confiance et de cybersécurité pour se concrétiser et qui doivent donc être associées à une logique d’ouverture, de mutualisation, de pérennité et de souveraineté. La mainmise des GAFAM sur nos données et leur exploitation, les monopoles créés par ces acteurs américains et leurs équivalents chinois, ont montré les dérives et dangers d’une telle hégémonie et nécessitent également des réponses souveraines afin de restaurer la confiance dans le numérique. L’Open Source et les modèles ouverts, avec leur approche collaborative, de partage et de transparence, sur lesquels repose aujourd’hui massivement le numérique, est une réponse à ces nécessités. Cette édition 2018 d’OSS Paris aura à cœur de proposer une approche métier des solutions Open Source. OSS Paris 2018 réunira l’ensemble des acteurs de l’écosystème Européen et de la Francophonie en permettant de rencontrer les faiseurs et contributeurs qui créent les outils et technologies, mais également les décideurs utilisateurs et consommateurs qui cherchent des solutions ou s’interrogent sur leur stratégie Open Source.LE COMITE DE PROGRAMME 2018 Élu pour la seconde année consécutive à la tête du comité de programme du Paris Open Source Summit 2018, Pierre Baudracco, fondateur de la société BlueMind, s'est entouré de personnalités reconnues du monde de l'Open Source pour élaborer ce programme 2018 : VP Ecosystem : Caroline CORBAL, Consultante, Inno3 VP Tech : Stéphane VINCENT, Directeur des Activités RUN, Alter Way VP Solutions : Laurent MARIE, Président, Worteks VP International : Patrick KOUASSI, Directeur Smile Côte d’Ivoire VP Grand Utilisateur : Le CIGREF nevil seafaring butler that can help you sail the seas of continuous delivery.”
— James Strachan
“The idea of Jenkins X is to give all developers their own nevil seafaring butler that can help you sail the seas of continuous delivery.”
— James Strachan
Jenkins X helps you automate your CI/CD in Kubernetes – and you don’t even have to learn Docker or Kubernet.
jx.
sudo mv
.bashrc.
helm
us-west1-a
n1-standard-2
For the GitHub name, type your own (e.g., mraible) and an email you have registered with GitHub (e.g., matt.raible@okta.com). I tried to use oktadeveloper (a GitHub organization), and I was unable to make it work.
mraible
matt.raible@okta.com
oktadeveloper.
jx console.
pom.xml
Create a bare-bones Spring Boot app from Cloud Shell:
jx create spring -d web -d actuator
This command uses Spring Initializr, so you’ll be prompted with a few choices. Below are the answers I used:
java
com.okta.developer
okta-spring-jx-example
TIP: Picking a short name for your artifact name will save you pain. Jenkins X has a 53 character limit for release names and oktadeveloper/okta-spring-boot-jenkinsx-example will cause it to be exceeded by two characters.
oktadeveloper/okta-spring-boot-jenkinsx-example:
Merge status checks all passed so the promotion worked!
Application is available at:
NOTE: Since Spring Boot doesn’t provide a welcome page by default, you will get a 404 when you open the URL above..
jx edit environment
Now that you know how to use Jenkins X with a bare-bones Spring Boot app let’s see how to make it work with a more real-world example.
Over the last several months, I’ve written a series of blog posts about building a PWA (progressive web app) with Ionic/Angular and Spring Boot.):
{yourUsername}:
okta-jenkinsx.
spring-boot-angular).
npm install
maven
nodejs
holdings-api.
--unsafe-perm
Jenkins X relies on Spring Boot’s Actuator for health checks. This means if you don’t include it in your project (or have /actuator/health protected), Jenkins X will report your app has failed to startup.
/actuator/health().
holdings-api/src/main/java/.../SecurityConfiguration.java();
}
}
Since this project builds in a sub-directory rather than the root directory, update ./Dockerfile to look in holdings-api for files.
./Dockerfile
holdings-api:
Jenkinsfile
mvn
-Pprod
//.
In short, we make identity management a lot easier, more secure, and more scalable than what you’re probably used to. Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:
Are you sold? Register for a forever-free developer account, and when you’ve finished, come on back so we can learn more about CI/CD with Spring Boot and Jenkins X!
After you’ve completed the setup process, log in to your account and navigate to Applications > Add Application. Click Web and Next. On the next page, enter the following values and click Done (you will have to click Done, then Edit to modify Logout redirect URIs).
Jenkins X
Open holdings-api/src/main/resources/application.yml and paste the values from your org/app into it.
holdings-api/src/main/resources/application.yml
okta:
client:
orgUrl:
token: XXX
security:
oauth2:
client:
access-token-uri: /oauth2/default/v1/token
user-authorization-uri: /oauth2/default/v1/authorize
client-id: {yourClientId}
client-secret: {yourClientSecret}
resource:
user-info-uri: :
token
XXX
OKTA_CLIENT_TOKEN:
holdings
Holdings
Cryptocurrency Holdings
After performing these steps, you should be able to navigate to and log in after running the following commands:
cd holdings-api
./mvnw -Pprod package
java -jar target/*.jar
Storing environment variables locally is pretty straightforward. But how do you do it in Jenkins X? Look no further than its credentials feature. Here’s how to use it:.
OKTA_APP_ID
E2E_USERNAME
E2E_PASSWORD
E2E-*
You can access these values in your Jenkinsfile by adding them to the environment section near the top.
environment.
holdings-api/src/test/java/.../cli/AppRedirectUriManager.java.
mvn exec:java.
http://{yourPreviewURL}/login
http://{yourPreviewURL}.
e2e-update
e2e-test
npm e2e
npm run
Instead of using a TRAVIS environment variable, you’ll notice I’m using a CI one here. This change requires updating crypto-pwa/test/protractor.conf.js to match.
TRAVIS
CI
crypto-pwa/test/protractor.conf.js.
./mvnw verify -Pprod,e2e:
jenkins-maven
jenkins-nodejs
.
--disable-dev-shm-usage
chromeOptions
--headless:
crypto-pwa/e2e/spec/login.e2e-spec.ts
should show a login button
it(...)
xit(...)
defaultTimeoutInterval.
To learn more about Spring Boot, Jenkins X, and Kubernetes, check out the following resources:.
react-scripts
npm
yarn
To install create-react-app and yarn, simply run:
create-react-app
npm i -g create-react-app@1.5.2 yarn@1.7.0
NOTE: I’ll be adding version numbers to help future-proof this post. In general though, you’d be fine leaving out the version numbers (e.g. npm i -g create-react-app).
npm i -g create-react-app
Now bootstrap your application with the following commands:
create-react-app my-react-app
cd my-react-app
yarn start
The default app should now be running on port 3000. Check it out at.:
public/index.html
head
<link rel="stylesheet" href="">
You can separate components into separate files to help keep things organized. First, create a couple new folders in your src directory: components, and pages
src
components
pages
mkdir src/components
mkdir src/pages
Now create an AppHeader component. This will serve as the navbar with links to pages, as well as show the title and whether you’re logged in.
AppHeader}>
</main>
</Fragment>
);
export default withStyles(styles)(App);
Material UI uses JSS (one of many flavors in the growingly popular trend of CSS in JavaScript), which is what withStyles provides.
withStyles.
CssBaseline
src/index.css
Hello World:
src/index.js
index.css
import './index.css';
if (module.hot) module.hot.accept();
At this point, your app should look like this:::
.env.local
-admin
NODE_ENV
REACT_APP_:
Router
Security.
Route
path
/
ImplicitCallback
/implicit/callback
---.
<input type="number" value={3} />
type
number
setState
props
state
this.props
this.state.
auth
authenticated
user
null
menuAnchorEl.
withAuth.
this
onClick
class LoginButton extends Component {
// ...
login = () => this.props.auth.login();).
render().
this.props.auth.isAuthenticated()
true
false:
LoginButton
div
flex
---' });: process.env.REACT_APP_OKTA_CLIENT_ID,
issuer: `${process.env.REACT_APP_OKTA_ORG_URL}/oauth2/default`,
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(async (req, res, next) => {
try {
if (!req.headers.authorization) throw new Error('Authorization header is required');
const accessToken = req.headers.authorization.trim().split(' ')[1];
await oktaJwtVerifier.verifyAccessToken(accessToken);
} catch (error) {
next(error.message);
}
});
It feels funny to be writing a “Hello World” blog entry in a new technical blog so far into my adventures with Python. January 2005 and my first entry in my Python technical blog, which marked the very early days of me discovering Python and falling in love with it, doesn’t seem so very long ago.
This was only a year or so before I started my first programming job, with a small London startup called Resolver Systems. We were building a Windows desktop spreadsheet application, using IronPython, with Python embedded as the calculation engine for the spreadsheet. I can’t find a blog entry when I first started working with the Resolver team, but in December 2006 I wrote a post Happy Birthday Resolver.
Since then I’ve had many more adventures including working freelance building web applications with Silverlight and IronPython in the browser, web application development with Django for Canonical, Go development working on a devops tool called Juju and working for Red Hat Ansible as a test engineer.
Python and the Python community has been very good to me in providing me with friendship, intellectual stimulation, a passion for engineering and a career. My involvement in the community included running Planet Python for many years, helping maintain the python.org website, becoming a Python core developer and helping maintain unittest whilst writing and contributing mock to the Python standard library plus at various points helping organise and speaking at all of PyCon in the US, EuroPython and PyCon UK. I was organiser and compere of the Python Language Summit from 2010 to 2014 and the Dynamic Languages VM Summit at PyCon 2011. I’ve lost track of the various conferences I’ve spoken about; spanning .NET, Python specific conferences and general programming like the ACCU conference. I’ve keynoted at PyCon India and PyCon New Zealand, probably the greatest privileges of my career so far.
I’m not saying any of this to boast (mostly), many of my contemporaries and those who are newer to the Python and programming communities have found as much of a passion and a sense of belonging in the Python community as I found. It’s fun to reminisce because it’s been such an enjoyable trip and one that’s far from over.
Alongside that, since 2011, I’ve done Python training on behalf of David Beazley. Teaching Python, both the introduction course and the super-advanced Python Mastery course, has been the most fun thing I’ve done professionally with Python. This is one of the reasons I’ve decided it’s time to branch out as a freelance Python programmer, trainer, contractor and consultant.
This blog entry is both a “Hello World” for the blog and for my new venture Agile Abstractions. I’m available for contract work, specialising in the automated end-to-end testing of systems.
The training courses I offer are listed here:
For custom training packages or any enquiries contact me on michael@python.org.
If you’re at EuroPython in Edinburgh this year, or PyCon UK in Cardiff, then hopefully I’ll see you there!
This website is built with Jekyll using the open source Jekyll Now and hosted on Github Pages. It’s a lovely and simple workflow for geeks to build and host websites that include a blog. It reminds me of the heady days of 2006 and my static site generator rest2web. individual'sa's Weekly Newsletter.
Hey, you’re cool, right?.
etiquetas: heyphone, open source, tailandia
» noticia original ().
Así lo explicaba en Facebook Phil Karn, ex-ingeniero en Qualcomm que se había mostrado interesado por cómo los equipos de rescate y salvamento habían solventado el apartado de las comunicaciones.
Uno de los dispositivos utilizados —hubo otros, como un sistema desarrollado por una empresa israelí— para que los equipos de rescate se comunicaran entre ellos y los niños atrapados con su entrenador fue el HeyPhone, que precisamente fue creado para rescates en cuevas y que su creador no patentó: toda la documentación, esquemas e información para construir el dispositivo está disponible públicamente.
Esta radio de comunicación utiliza la banda de baja frecuencia de 87 kHz, y además hace uso de una antena que "consiste en dos estacas clavadas en el suelo a unos 20 m de distancia".
Al fluctuar la corriente entre las estacas eso permite a la radio conectarse a otra antena que esté a unos pocos cientos de metros de distancia, siguiendo el mismo principio que las antenas de dipolos terrestres que se usaron por ejemplo en misiones militares en Estados Unidos usando frecuencias ELF (Extremely Low Frequencies) que van de los 3 Hz a los 3 kHz.
El ingeniero y radioaficionado que diseñó este dispositivo, John Hey, murió en 2016, pero seguramente hubiera estado feliz por su contribución a esta operación de rescate. Es curioso, pero en el sitio web oficial del dispositivo indican que "ya no se recomienda" y en su lugar se recomienda buscar "un diseño más moderno".
Imagen | SUI
Vía | Phil Karn en Facebook
Más información | HeyPhone
En Magnet | La cueva de Tailandia representa todo lo que está mal con la visión del mundo de Elon Musk
Lo único que ARM ha conseguido al ir contra RISC-V es darle publicidad a un rival en pañales
Qué es del movimiento maker, 10 años después que fuese a cambiar el mundo
- La noticia
En el rescate de los niños en Tailandia hubo otro héroe: el "HeyPhone" y su filosofía Open Hardware
fue publicada originalmente en
Xataka
por
Javier Pastor
.
CivicPlus, which offers a suite of website-focused services to local government, has bought out another company for its open-source content management system — the third acquisition the company has made since the start of 2017.
The new product, CivicCMS, will actually be the company’s second CMS. It already offered its own system, called CivicEngage. Going forward, it expects to sell CivicEngage more to its larger customers and CivicCMS to smaller ones.
“Over the past 20 years working with local governments, we have learned that the technology needs of smaller municipalities vary greatly from large cities and counties both from an end user and an administrative perspective,” said CivicPlus CEO Brian Rempe in a press release. “By adding a dedicated solution that allows us to service a wider spectrum of municipalities, we will be better able to offer scalable solutions to all local governments. It will also allow us to continue evolving our CivicEngage CMS to fit the needs of larger cities and counties.”
The description doesn’t exactly jibe with CivicPlus’ own marketing — on its website, CivicPlus states that “our (CivicEngage) CMS is ideal for Small to Large Cities, Towns/Townships, Counties/Parishes, Emergency Management Organizations, Fire Authorities/Departments, Law Enforcement/Public Safety Organizations, Port Authorities, Water Authorities, and Municipal Intranets.”
The new CMS, which it brought into the fold by way of acquiring the Massachusetts-based company Virtual Towns & Schools, is based on the open-source Drupal platform. According to the press release, VTS has more than 600 clients, many of them in the Northeastern U.S. As its name suggests, it serves local government as well as school districts.
CivicPlus has been on something of an acquisition spree lately. In January 2017 it acquired Rec1, using its software to launch a parks and recreation product. Then in October that year it bought up BoardSync and turned its technology into an agenda and meeting management product.
Editor's note: The headline of this article was adjusted to avoid confusion about VTS' open source status..
<
|
https://googlier.com/search/2018_07_11/open%20source.html
|
CC-MAIN-2018-30
|
refinedweb
| 10,024
| 51.58
|
PGL is a library that encapsulates plot capabilities in a MFC project for VC6 and VC7. It is designed to be able to easily plot data generated in a project without the need of any external software. In fact, with
CView and
CDialog derived classes, you can have your app display chart in 5 minutes.
The aim of
PGL is not to have a user-friendly environment but rather being able to generate any plot from the source code.
PGL was originally using
OpenGL to raster graphics but now it uses
GDI+ (so you need to install Microsoft SDK to compile
PGL).
A UML diagram is available in pdf here. It is not complete but it should help you in understanding the library.
PGLin one of your projects:
GDI+(part of Microsoft SDK).
PGLbinaries to your path. (by default it is C:\Program Files\PGL\bin)
That's it!
#include "PGL.h"
PGLis using
GDI+, you must initialize it :
CWinAppderived class
ULONG_PTR m_ulGdiplusToken;
GDI+
// initialize <code>GDI+ (gdi+ is in Gdiplus namespace) Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::GdiplusStartup(&m_ulGdiplusToken, &gdiplusStartupInput, NULL);
GDI+.
// shutdown GDI+ Gdiplus::GdiplusShutdown(m_ulGdiplusToken);
Your project should work fine now.
All these examples are accessible in the source. See the example menu of TestPGL.
pX,pYof size
nPoints( note that you can also pass data as
std::vector<double>to
PGL).
Here's the code I used to generate the data: a simple sinusoid. Note that the y are in [-1.1, 1.1] but
PGL will handle axe labelling the have nice units.
// generate data int nPoints = 50; double* pX=new double[nPoints]; double* pY=new double[nPoints]; for (UINT i=0;i< nPoints;i++) { pX[i]=i; pY[i]=sin(i/(double)nPoints*2*3.14)*1.1; }
CPGLGraph* pGraph = new CPGLGraph;Note that you can check all
PGLobject with
ASSERT_VALIDsince they all inherit from
CObject.
CPGLLine2D* pLine = new CPGLLine2D;
PGLwill handle the memory afterwards. That is, it will delete the pointers of data at the object destruction. This means
pX,pYMUST have been allocated on the heap !
pLine->SetDatas( nPoints /* number of points */, pX /* x(i) */, pY /* y(i) */);
pGraph->AddObject(pLine);
PGLscale the plot (automatically)
pGraph->ZoomAll();
CPGLGraphBitDlg graphdlg(this, pGraph); graphdlg.DoModal();
PGL.
PGL.
In this examples, we approximate the previous line. Starting from the previous example,
CPGLLine2D* pLine = new CPGLLine2D;to
CPGLLine2DLOD* pLine = new CPGLLine2DLOD;
pLine->SetTol(0.05);
pLine->ShrinkNorm(0.1,0.02);
We start from the second example and add the following line of code before calling
ZoomAll().
CPGLAxe2D* pAxis = pGraph->GetAxe();
pAxis->SetTitle(str);or
pAxis->GetTitle()->SetString(str);
pAxis->GetTitle()->SetColor(0 /* red */,0.5f /* green */, 0 /* blue*/ /* alpha optional */);
pAxis->SetShowGrid(1,FALSE);
pAxis->GetRightLabel()->Show(TRUE); pAxis->GetRightLabel()->SetString("This is the right label");
pAxis->GetRightNumber()->Show();
pAxis->SetTopSecondTicksNb(5);
// enable time labelling pAxis->SetTimeLabel(TRUE); // set origin, time step and format (see COleDateTime.Format for details) pAxis->SetTimeLabelFormat(COleDateTime::GetCurrentTime() /* Time at zero. */, COleDateTimeSpan(0,0,30,0) /* Time per unit */, "%H:%M:%S" /* String format */);
PGLin many ways. In fact you can add plots to plots, and so on.
The class
CPGLGraphis inherited from a generic plot class :
CPGLRegion. You can either
Divide(m,n)to divide the region in an array of m rows and n columns (Note that this method erase all object in the region). After that, you can access the elements with
GetChilds(i)(the regions are created row by row). You can get the number of children with
GetNChilds():
// allocated somewhere CPGLRegion* pRegion; // dividing pRegion->Divide(m,n); // accessing region at row 2 and column 1 (zero based index) CPGLRegion* pChildRegion = pRegion->GetChild(2*n+1);
AddRegion. To use this method you must
SetNormBBox(...)to set the bounding box (in Normalized coordinates with respect to the parent region)
CPGLRegion* pChildRegion = pRegion->AddRegion(); pChildRegion->SetNormBBox(0.1 /* llx */ , 0.2 /* lly */ , 0.7 /* urx */ , 0.8 /* ury */);
The sources of
PGL are provided. Open the workspace
It contains 6 projects :
PGL. Multi-layer graphic interface to export in multiple graphic format such as EPS or SVG.
PGL. The graphic library.
General
News
Question
Answer
Joke
Rant
Admin
|
http://www.codeproject.com/KB/miscctrl/pgllib.aspx
|
crawl-002
|
refinedweb
| 688
| 58.79
|
In BASH you might quite often use
sort -n to ensure that strings are sorted as if they were numeric (i.e. so 12a,2a,4a is sorted into the order you'd expect based on the integers at the front).
There isn't a direct way to do this to a list in Python, so you need a wrapper to help implement the functionality
sort -n
import re def sorted_nicely( l ): """ Sorts the given iterable in the way that is expected. Required arguments: l -- The iterable to be sorted. From and """ convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] return sorted(l, key = alphanum_key)
a = ['1a','12a','21c','3b','4a','5a'] print sorted(a) # ['12a', '1a', '21c', '3b', '4a', '5a'] print sorted_nicely(a) # ['1a', '3b', '4a', '5a', '12a', '21c']
|
https://snippets.bentasker.co.uk/page-1804141022-Sort-list-as-if-it-were-numbers-Python.html
|
CC-MAIN-2019-09
|
refinedweb
| 145
| 70.13
|
On Sun, 2020-09-13 at 20:31 +0200, Thomas Deutschmann wrote: > You maybe all remember what happened to stable-bot: Years ago, > kensington created stable-bot on his own as PoC which revolutionized the > way how we do package stabilization in bugzilla. The service run on his > own infrastructure. Because of the benefit of the service the bot > provided, arch team’s workflow became dependent on stable-bot. We were > lucky that stable-bot just worked most of the time until the service was > down for a while. Nobody was able to help here: Kensigton himself was > unavailable, nobody had the sources… the end of the story: mgorny > created nattka which replaced stable-bot. > > However, we are still facing the same problem:
No, we're not. Don't you see the huge difference between proprietary closed-source software and free software? > Only one person is involved in development How is that a problem? It is quite normal that simple tools are developed primarily by one person, and nattka is not exactly rocket science. That said, nobody is stopping others from working on it, there are surely some improvements to be done. > and knows how to run it. Everything is documented and fully contained in puppet. Deploying it to new server is as trivial as enabling it on host in question. > In case something will > break again and Michał will be unavailable, we can’t just push a fix and > watch a CI pipeline picking up and deploying new nattka. Who is 'we' here? Our Infra does not use 'CI pipelines', it uses Gentoo packages. Deploying a new version means bumping the package, waiting for rsync to distribute it (meh!) and telling puppet to upgrade. No buzz words involved, sorry. > Instead someone will have to fork repository from Michał’s private > repository at GitHub, make the changes It's not private, it's public. And to be honest, forking it on GitHub will certainly take less time and effort than dealing with git.gentoo.org (which needs to happen via Infra). > and hope that anyone within infrastructure team can > help to deploy fixed nattka. Are you suggesting there is a problem with Gentoo Infrastructure? I really don't see where this is going. You're concerned that Infra can't handle it, yet you actually ask to make it more reliant on Infra... > This is what the motion is about: This is not about that Gentoo depends > on single persons or things like that. It’s about the idea to > *formalize* the requirement that any service and software which is > critical for Gentoo (think about pkgcore) should live within Gentoo > namespace (), i.e. be accessible for *any* > Gentoo developer and deployments should be based on these repositories. You should weigh your words more carefully. Otherwise, we're going to end up forking the whole base-system, kernel... > Or in other words: Make sure that we adhere to social contract even for > critical software and services Gentoo depends on. So that we will never > ever face the situation that something we depend on doesn’t work > anymore. I fail to see how this is going to actually accomplish the goal. Having a different pipeline for committing does not make stuff not break, nor makes it more likely for people to fix it. In fact, I dare say having nattka on GitHub increases the chances of someone (esp. non-developer) submitting a fix, compared to obscure git.gentoo.org with no clear contribution pipeline. > Taking care of working pipelines before something is broken > should also help us in case something stops working so we don’t have to > figure out how to fix and re-deploy when house is already burning (like > portage: In case Zac can't do a release for some reason, in theory, > every Gentoo developer would be able to roll a new release). Please tell me how rolling a new release of nattka is exactly harder than rolling a release of Portage? I'm pretty sure most of Gentoo developers can figure out how to use GitHub, how to fork a repository, and if they use Python they can probably deal with pretty standard setup.py. Deployment can't be done without Infra's help anyway. -- Best regards, Michał Górny
signature.asc
Description: This is a digitally signed message part
|
https://www.mail-archive.com/gentoo-dev@lists.gentoo.org/msg90525.html
|
CC-MAIN-2022-33
|
refinedweb
| 722
| 64.1
|
I often hear of the “Source Code Compatibility” between Silverlight and Windows Presentation Foundation and so today I thought I’d try it out a little bit.
Personally, I don’t view this as;
Take your SL source code, add a few bits and pieces and you have a WPF application. Add a bit of conditional compilation where necessary.
I don’t have a perfect picture of it in my head but I see it more as perhaps;
Build both a Silverlight and a WPF UI. Try and build components that can be built to underpin both. Most of what you’ve got will build/work on both frameworks and then you’ll perhaps have a remaining 10% or so that’s similar but different enough to want to separate out to being WPF/Silverlight specific.
I still think it sounds challenging and I’m not sure how you’d do (e.g.) source code compatibility between Silverlight controls that are using the VSM and WPF controls that aren’t. That feels like a tricky one to get right and I suspect that there are a whole bunch of other areas that need a lot of thought to try and get this to work.
You could argue that you pick a control set that’s common across both Silverlight and WPF ( i.e. the common Microsoft control set and perhaps a 3rd party control set that supports both ) and use those. That might help a whole lot in raising you above the WPF/Silverlight differences.
I can definitely see that you can re-use your knowledge and skills across the 2 frameworks. That’s a given. I can also see that you’d re-use a whole bunch of XAML by just lifting it from one framework to the other, changing a few bits and pieces (like the namespace :-)) and then getting it linked up with some code and running.
Anyway…I wanted to experiment and so I thought that I would port an existing Silverlight application to WPF.
I chose Silverlight Airlines.
On reflection, this was probably a bad choice 🙂 From looking at the source for Silverlight Airlines you can tell ( I think ) that it was written for Silverlight V1.1 rather than Silverlight V2.0 in that it does quite a lot of dynamic loading of XAML rather than use the control model that showed up in V2.0. It’s nicely structured there so you can pretty quickly get to grips with it.
I chose to do what I call a “literal” port of it in the sense that I just took what was there and hacked at it until I had it running on WPF. I made no attempt to do things in any kind of “better” way but just tried to get it across to WPF. There are some specific things around resizing that I don’t think you would do in a world of Grid and so on but the code is all Canvas based from the V1.1 preview.
I’d say that it took me about 60 minutes and of those 60 minutes I reckon I spent around 45 just monkeying around trying to figure out what to set the build option on my XAML files to and why the XAML files weren’t being loaded by Application.LoadComponent and so on.
The last 15 or so minutes were probably spent in a debugger trying to figure out why certain animations weren’t where they were expected to be and switching a few calls to FindName() to look into Resources collections.
I put the source code here for download. This is not my code and so I possibly have no rights to distribute it but it’s a public sample so I figured no-one would mind. If you do mind, mail me and I’ll remove it and update the post.
Here it is running on Vista in all it’s glory 🙂 Don’t worry about the crazy looking colours – that’s just my desktop shining through the glass.
|
https://mtaulty.com/2008/08/28/m_10706/
|
CC-MAIN-2019-51
|
refinedweb
| 678
| 75.84
|
In an earlier postings I described the project that I’ll be creating with Phil Japikse and Michael Crump, code-named Conference Buddy. In a recent posting we looked at a wire-frame that illustrated some of the data we’ll be collecting. In another post, I described how I might use the flip-view to move among the various data-gathering and display “pages.”
Once we gather the data, we’d like to save it to a format that will be consistent across Windows 8 C# and Windows 8 Javascript, as well as Windows 8 Phone. For now, we’ve settled on JSON as a common persistence and wire-format. While JSON stands for JavaScript Object Notation, there are good libraries for converting .NET objects to JSON and back. We’ll be using one of the most popular: JSON.NET – an open source serializer for converting between .NET objects and JSON.
You can download JSON.NET from CodePlex or through NuGet; we’ll do the latter for this posting.
To get started, we return to our earlier FlipView project, and we’ll add a Customer class to hold the data gathered on the first page,
public class Customer{ public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Title { get; set; } public string Company { get; set; } public string PhoneNumber { get; set; }}
All we need do now is to move the data entered by the user into an instance of Customer and serialize it to JSON (we’ll cover writing the actual file to local storage in a subsequent posting).
In keeping with eliminating chrome from the application and moving buttons and other navigation to the AppBar, we’ll add our Save and Delete buttons to an AppBar for this application as described in this blog post.
The job of the Save button event handler is to extract the data from our TextBoxes and to populate a Customer object,
private void Save_Click( object sender, RoutedEventArgs e ){ Customer cust = new Customer(); cust.Company = Company.Text; cust.Email = Email.Text; cust.FirstName = FirstName.Text; cust.LastName = LastName.Text; cust.PhoneNumber = PhoneNumber.Text; cust.Title = Title.Text;
With the Customer object populated, we’re ready to serialize to JSON. The first task is to load the JSON.NET library, which we do using NuGet. To do so, click on Tools –> Library Package Manager –> Package Manager Console. This will open the console window at the bottom of your screen, providing you the Package Manager prompt ( PM> ). Enter the command to load Json.NET:
PM> Install-Package Newtonsoft.Json
Remember to put in the hyphen between Install and Package. A few seconds later the package will have been installed.
Add a using statement to the top of your file,
using Newtonsoft.Json;
and you are ready to go. The actual serialization requires just one line of code,
string JSON = JsonConvert.SerializeObject( cust );
That’s it! With that you’ve serialized the information from the user into a JSON string (as shown in the figure. Click on the figure to see full size).
All that’s left is to implement Delete_Click which will clear out the entries in the data form. Since we want to do so after serializing the data as well, we’ll factor that out into a helper method,
Here’s the complete code for both button handlers and for the helper method, ); ClearFields();}private void ClearFields(){ Company.Text = string.Empty; Email.Text = string.Empty; FirstName.Text = string.Empty; LastName.Text = string.Empty; PhoneNumber.Text = string.Empty; Title.Text = string.Empty;}private void Delete_Click( object sender, RoutedEventArgs e ){ ClearFields();}
We’ve gathered information from the user and stored it into a JSON string. The next step is to write that to LocalStorage and then, eventually, to a service on the Web for back-end processing.
Download Source Code
|
http://www.telerik.com/blogs/windows-8-storing-json-data-for-conference-buddy
|
CC-MAIN-2017-22
|
refinedweb
| 642
| 62.98
|
--- a +++ b/index.html @@ -0,0 +1,53 @@ +<html> +<title>CodeHelper</title> +<body> +<h1>The CodeHelper plugin</h1> +Written by Shlomy Reinstein, November 2010. +<h2>Introduction</h2> +<p> +The CodeHelper plugin provides a dockable window that shows either a static call +tree of a selected function, or a reference tree of a selected identifier. The tree +shows the functions calling / referring to the identifier, and each such caller node +can be expanded to see its own callers. When you select a caller, the actual calls from +it are shown in a list on the right - clicking each item in the list opens the buffer +containing the call and jumps to its location in the buffer. +</p> +<p> +CodeHelper works in the context of a <b>ProjectViewer</b> project. It finds +callers / references only in the current project. CodeHelper relies on two +other plugins to provide it with the information it needs: <b>CtagsInterface</b> and +<b>LucenePlugin</b>. To show a static call tree, it first searches the Lucene index +of the current project for all occurrences of the function name. It invisibly opens +each of the files containing occurrences of the function name in jEdit, and uses +jEdit syntax highlighting to filter out occurrences inside comments and strings. Then, +it uses CtagsInterface to find the closest function above the occurrence line +as a caller. It also uses CtagsInterface to filter out function prototypes. +Finally, it presents the callers in a tree. Clicking each caller shows the calls from +it on the right of the dockable. Expanding a caller will cause the same algorithm to +run on the caller's name, to find all its callers. +</p> +<h2>Prerequisites</h2> +CodeHelper requires <b>CtagsInterface</b>, <b>LucenePlugin</b> and +<b>ProjectViewer</b>. Moreover, it does *not* create a Lucene index and a tag index on +its own; it requires that these already exist when you use its actions (static call +tree / reference tree). To allow CodeHelper to work for a project, do the following: +<ol> +<li>Switch to the project in ProjectViewer. +<li>Right click the project and select <b>Add project to tag index</b>. +<li>Right click the project and select <b>Create Lucene index for project</b>. +<li>Wait until the tag index and Lucene index are ready, and then you can start using +CodeHelper for the project. +</ol> +<h2>Notes</h2> +This plugin is mainly useful for computer languages where names are global and unique. +It is not so useful for object oriented languages - such as C++ and Java - where a +program can define many functions with the same name (but in a different namespace / +class). For example, in Java, if you try to look for callers of "actionPerformed", +you will get the list of all callers of all functions with this name, no matter which +class they are. +<h2>Feedback</h2> +</a> +Any feedback would be most welcome. Please send your feedback to the <b>jedit-users</b> +or <b>jedit-devel</b> mailing list. +</body> +</html>
|
http://sourceforge.net/p/jedit/CodeHelper/ci/592ce80b4743c85bf1f03afe1b4f568bc386ded3/tree/index.html?diff=b10acf5c6b18368ed8a79a5bab989048780fa8b2
|
CC-MAIN-2015-27
|
refinedweb
| 502
| 61.26
|
I ''
[Edited Dec 6, 2010 to mention another solution based on zip and iter.]
Suppose you want to divide a Python list into sublists of approximately equal size. Since the number of desired sublists may not evenly divide the length of the original list, this task is (just) a tad more complicated than one might at first assume.
One Python Cookbook entry is:
def slice_it(li, cols=2): start = 0 for i in xrange(cols): stop = start + len(li[i::cols]) yield li[start:stop] start = stop
which gives the exact number of subsequences, while varying the length of the subsequences a bit if necessary. It uses Python's slicing feature to get the lengths.
That was written in response to an earlier cookbook entry which had the following one-liner:
[seq[i:i+size] for i in range(0, len(seq), size)]
I like that it's a one-liner but don't like a couple of things about it. If your goal isn't a particular sublist length but rather to divide the list up into pieces, you need another line to compute the size. And then it doesn't turn out too well. Suppose you want to divide a string of length 10 into 4 substrings:
>>> size=10/4 >>> size 2 >>> seq = [1,2,3,4,5,6,7,8,9,10] >>> [seq[i:i+size] for i in range(0, len(seq), size)] [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
This leaves us with one substring more than desired.
Try setting size to 3 to get fewer substrings:
>>> size=3 >>> [seq[i:i+size] for i in range(0, len(seq), size)] [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
This leaves us with dissimilar lengths.
Here's a briefer one-liner using the slice idea, which doesn't require you to compute the length in advance, and does give the exact number of subsequences you want and with lengths that are more appropriately divided:
[seq[i::num] for i in range(num)]
The drawback here is that the subsequences are not actually subsequences of seq; seq is sliced and diced. But, in many situations that doesn't matter. In any case, all the elements are in the output and the subsequences are as close as possible to the same length:
>>> seq = [1,2,3,4,5,6,7,8,9,10] >>> [seq[i::num] for i in range(num)] [[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]
Update: I just read about a clever and interesting solution involving zip and tier that works in Python 2.7:
>>> items, chunk = [1,2,3,4,5,6,7,8,9], 3
>>> zip(*[iter(items)]*chunk)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Read a full explanation at Go deh! The disadvantage from a practical point of view is that the if the list of items is not evenly divisible into chunks, some items get left out. But I still like it because it's illuminating about the nuances of iterators.
A while ago I posted a suggestion for how to eliminate some mindless code in python __init__() methods when you want to assign instance attributes from __init__() args.
Henry Crutcher postedhis own solution on Thursday in the Python Cookbook.
I've combined the two approaches in a comment to that post (on the same page). I think it's getting to be a good solution.
The.
[Most!
Here's a quite complete Singleton mixin class for Python, including such niceties as thread safety for singleton creation. Public domain. Based in part on ideas I found on this wiki page, followed by a substantial number of enhancements based on comments posted below and based on my own additional needs. If you find it useful and think of ways to improve it, please post a comment here.
Lately I've noticed some discussion of the evilness of singletons. One poster says:.
My singleton mixin source includes unit tests showing that at least rudimentary subclassing does work with the approach used here. I haven't run into any problems in real life either, although I use singletons sparingly.
If anyone has examples or thoughts about problems with subclassing with this mixin, please post a comment.
Update, July 28, 2009: Now optionally allows multiple calls to getInstance() which all include arguments. See the docstring for more. Update, July 27, 2009: I try to keep the Singleton version here in sync with our svn version, so that any enhancements or fixes will be included. The code, still at the original link (above), has been modified today to add thread safety for singleton creation, and also incorporates ideas from some of the recent comments people have posted here. In particular, singleton construction can now handle keyword arguments.
|
http://feeds.feedburner.com/garyrobinson/python
|
CC-MAIN-2018-51
|
refinedweb
| 803
| 66.17
|
Details
- Type:
Umbrella
- Status: In Progress
- Priority:
Major
- Resolution: Unresolved
- Affects Version/s: 0.8.1
- Fix Version/s: None
- Labels:None
Description
So I am curious what the plan is for the longterm future of MRUNIT?
I think currently MRUNIT is useful for just unit testing a single mapper or reducer but currently there is a void for testing more complicated features such as MultipleInputs, MultipleOutputs, a driver class, counters, among other things. I wonder if instead of adding support to the current MRUNIT framework for these extra features it would more useful to add in hooks to the existing LocalJobRunner and MiniMRCluster classes to provide methods to more easily verify file output from text files, sequence files, etc. This would allow MRUNIT to test driver classes, MultipleInputs, MultipleOutputs, etc. MRUNIT would also then test against the real hadoop code instead of an implementation that mimics hadoop which can miss some bugs such as the ReduceDriver that did not reuse the same object until 0.8.0. MRUNIT would also keep up with new map reduce features instead of us having to implement fake versions of them
I understand that performance would be an issue due to the file I/O but I wonder how fast the LocalJobRunner would be if we wrote a new class that extending FileSystem to allow users to write out fake files to memory and make the LocalJobRunner read from them
Activity
- All
- Work Log
- History
- Activity
- Transitions
That's a pretty good idea!
I think initially I will just write the new api but have the new api use the existing framework in order to get the new api out sooner. Then later we can change the framework behind the scenes without any effect on the users
I think we should also support the current run() method if users want to test the output in some weird way. If they called run() they would set a flag that would prevent runTests() from running.
The other question is how do we go about getting this in jenkins?
I think sub projects are out of style for whatever reason. The package structure question is a good one, let's think about that one for a bit? You should be able to start with a new separate package and then refactor it when we decide on a new one. Maybe start with: org.apache.mrunit.mapreduce?
What should the new package structure be?
I noticed the groupId is now org.apache.mrunit, should we use that or is the plan for MRUNIT upon graduation to become a subproject of hadoop so we should keep org.apache.hadoop.mrunit?
Cool!
Ok that sounds good. I will start this work in a branch to prevent effecting regular releases.
I will convert this JIRA to a Umbrella and put the following as Sub tasks of this JIRA along with other relevant requirements as they come up:
MRUNIT-13 - Add support for MultipleOutputs
MRUNIT-64 - Multiple Input Key, Value Pairs should be supported
Running a generic Map Reduce driver (via local job runner) and validating the output
I also think we'd only have to support the o.a.h.mapreduce api since mapred will be going away at some point.
That looks good. As I understand it we would create a new MRUnit API with new package name. The old MRUnit api would not be changed but deprecated. I would like to see the old api deprecated but supported for bug fixes for a long period, like a couple of years. We haven't seen many bugs so I think that would require little effort.
Things I'd like to see:
-MultipleOutputs via
MRUNIT-13
-Multiple input key/value pairs via
MRUNIT-64
-Cleaner API
-Running a generic Map Reduce driver (via local job runner) and validating the output
We use an annotation on the class to specify the mapper/reducer classes because we can use arrays which is required for PipelineMapReduceDriver which isnt possible with declaring the classes in the generic type. Users could also easily leave off mapper/reducer classes in the generic type.
We then need a way to read these annotations. We either make all testclasses extend DriverTest because we can use this.getClass() to get a reference to the actual user class in order to use Reflection to read the annotations at runtime. Or we use all static methods with thread locals and use Thread.currentThread().getStackTrace() to search for the annotations. We may want to use thread locals even if we extend DriverTest because some people may want to use the concurrent JUnit runners which can run multiple methods in parallel.
Lastly, we use a @Before method in the superclass Driver to cleanup the state and the @After method does the runTest call so an example would be:
@MapTest(IdentityMapper.class)
public class IdentityMapperTest {
@Test
public void testMap()
}
This eliminates the driver, the need to specify the mapper/reducer class in every method, the run call. I dont think it could be much simpler than this. We could also allow multiple key, value pairs into a given mapper for
MRUNIT-64 or multiple keys into a reducer with a method that took a varargs value.
We could put all this in a new package structure and deprecate the old api which would fix
MRUNIT-76
Yes I agree, they are redundant, unfortunately it's exposed to the public so I don't think we can remove the method signatures.
I was thinking about what we should do longterm.
MRUNIT-13 has been open for some time. I don't know if that requires a much full featured test framework ala Local Job Runner or if we can fulfill that requirement with MRUnit. That patch attached to that JIRA is an omnibus patch which changes a bunch of mrunit.
With the builder syntax is it necessary to have withInput and addInput, shouldnt we just have addInput return "this" instead of having all these repetitive methods all over the source code?
I dont know much about creating annotations either but we may be able to reduce some of the repetitive code with them.
I agree JUnit and perhaps TestNG compatibility is a very good thing.
The driver today can do that builder syntax so all my example above is eliminating is the creation of the driver. Not entirely sure it's worth the effort.
I am not sure how we'd get rid of calling run? Maybe an annotation could do that, I am not annotation expert by any means.
I would think we should still be compatible with JUnit due to the good support from IDE's
I agree that @MapTest(mapper = IdentityMapper.class) should not go on the method but the class. I am not sure we want to extend MapperTest<CoolMapper.class>. JUnit used to do this but went a way from that to do assertion based testing.
I think the withInput(key, value).withOutput(key, value) is a good idea but it would be ideal to not have to call run() everytime. There also needs to be a withJobConf(conf) or a withJobConfParam("key", value)
Here is Mockito:
It basically used static methods with thread locals to give you something very litterate. We, if we chose too, would be emulating it's syntax. For example:
test(mapper) .withInput(new LongWritable(1), new Text("hi")) .withOutput(new Text("hi"), new LongWritable(1)) .withCounter("MyGroup", "MyCounter", 1) .run();
The method called "test" might be a bad choice.
I'm not familiar with Mockito... yet
Could you put together some code example how would you imagine using Mackito for writing tests? Just to give an idea what you're thinking about.
Hi,
I for eliminating typing as well. I am a huge fan of Mockito. Their literate syntax is very easy to use.
I quite like Jim's idea. I'm looking forward to simplify usage even more. I could imagine even more simplification to save any necessary typing. For example something like:
class CoolMapperTest extends MapperTest<CoolMapper.class> {
public testProperArguments()
}
I'm expecting here that user will have one test class per one mapper (reducer, map reduce pair) which is something that I'm already doing in my tests to keep them clean. I'm not sure whether others are doing it as well. Another important note here is that I'm expecting that MapperTest will execute all methods starting with name "test" to set up testing environment (inputs, outputs, counters, ...). However test itself would be executed by MapperTest and user wouldn't have any control over it which might be limiting for some use cases. However those problems might be address by exposing API in MapperTest that can override default behavior.
Another way to make using mrunit cleaner would be to really take advantage of assertions to cut out the boilerplate code.
For example you could have
@MapTest(mapper = IdentityMapper.class)
public void mapTest()
I am not too familiar with making up Assertions but we would need to a way to then reference the driver or else all the methods would have to be static which would not be ideal.
JUnit uses assertions all over their library, we should be able to use them too
I have been struggling with how to implement multiple input/outputs as I don't see a clear way to implement then in MRUnit today. That would be a good initial goal of an expansion.
I think that is up to us, I agree there is a void in the integration testing space. It would be nice if we had a very easy interface to run drivers and validate the output.
I do have questions about the annotation based API (assuming there is no need to extend a provided parent test class).
1) How do you intend to check for input/ouput types? I don't see how that can be done without exposing a context (like the typed driver or a parent class). It wouldn't be enforced anymore?
2) How do you intend to check for methods which should not be called eg withKeyGroupingComparator during a reducer test? I don't see how that can be done without exposing a context. It wouldn't be enforced anymore?
3) I like the idea of a in memory FileSystem implementation. I know Cascading 2 has now a local mode which sounds a bit similar. But it might too abstract or too strongly tied to Cascading concepts to be of any use to MRUnit. This feature would be also be a must for pig/hive when you want to run the same query but locally without the cluster latency. So it would be interesting to see if something already exist around Hadoop.
|
https://issues.apache.org/jira/browse/MRUNIT-69?focusedCommentId=13217922&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
|
CC-MAIN-2015-32
|
refinedweb
| 1,794
| 62.27
|
Introduction
In the previous post we implemented a video driver so that we are able to print text on the screen. For an operating system to be useful to the user however, we also want them to be able to input commands. Text input and output will be the foundation for future shell functionality.
But how does the communication between the keyboard and our operating system work? The keyboard is connected to the computer through a physical port (e.g. serial, PS/2, USB). In case of PS/2 the data is received by a microcontroller which is located on the motherboard. When a key is pressed, the microcontroller stores the relevant information inside the I/O port
0x60 and sends an interrupt request IRQ 1 to the programmable interrupt controller (PIC).
The PIC then interrupts the CPU with a predefined interrupt number based on the external IRQ. On receiving the interrupt, the CPU will consult the interrupt descriptor table (IDT) to look up the respective interrupt handler it should invoke. After the handler has completed its task, the CPU will resume regular execution from before the interrupt.
For the complete chain to work we need to do some preparations during the kernel initialization. First, we have to setup the correct mapping inside the PIC so that our IRQs get translated to actual interrupts correctly. Then, we must create and load a valid IDT that contains a reference to our keyboard handler. The handler then reads all relevant data from the respective I/O ports and converts it to text that we can show to the user, such as
LCTRL or
A.
Now that we know the high level overview of what we need to do, let's jump into it! The remainder of this post is structured as follows. The next section focuses on defining and loading the IDT. Afterwards we will implement the keyboard interrupt handler and register it. Last but not least we extend the kernel functionality to execute the newly written code in the correct order.
The source code is available at GitHub. The code examples of this post use type aliases from
#include <stdint.h> which are a bit more structured than the original C types.
uint16_t corresponds to an unsigned 2 byte (16 bit) value, for example.
Setting Up The IDT
IDT Structure
The IDT consists of 256 descriptor entries, called gates. Each of those gates is 8 bytes long and corresponds to exactly one interrupt number, determined from its position in the table. There are three types of gates: task gates, interrupt gates, and trap gates. Interrupt and trap gates can invoke custom handler functions, with interrupt gates temporarily disabling hardware interrupt handling during the handler invocation, which makes it useful for processing hardware interrupts. Task gates cause allow using the hardware task switch mechanism to pass control of the processor to another program.
We only need to define interrupt gates for now. An interrupt gate contains the following information:
- Offset. The 32 bit offset represents the memory address of the interrupt handler within the respective code segment.
- Selector. The 16 bit selector of the code segment to jump to when invoking the handler. This will be our kernel code segment.
- Type. 3 bits indicating the gate type. Will be set to
110as we are defining an interrupt gate.
- D. 1 bit indicating whether the code segment is 32 bit. Will be set to
1.
- DPL. 2 bits The descriptor privilege level indicates what privilege is required to invoke the handler. Will be set to
00.
- P. 1 bit indicating whether the gate is active. Will be set to
1.
- 0. Some bits that always need to be set to
0for interrupt gates.
The diagram below illustrates the layout of an IDT gate.
To create an IDT gate in C, we first define the
idt_gate_t struct type.
__attribute__((packed)) tells
gcc to pack the data inside the struct as tight as they are defined. Otherwise the compiler might include padding to optimize the struct layout with respect to the CPU cache size, for example.
typedef struct { uint16_t low_offset; uint16_t selector; uint8_t always0; uint8_t flags; uint16_t high_offset; } __attribute__((packed)) idt_gate_t;
Now we can define our IDT as an array of 256 gates and implement a setter function
set_idt_gate to register a
handler for interrupt
n. We will make use of two small helper functions to split the 32 bit memory address of the handler.
#define low_16(address) (uint16_t)((address) & 0xFFFF) #define high_16(address) (uint16_t)(((address) >> 16) & 0xFFFF) idt_gate_t idt[256]; void set_idt_gate(int n, uint32_t handler) { idt[n].low_offset = low_16(handler); idt[n].selector = 0x08; // see GDT idt[n].always0 = 0; // 0x8E = 1 00 0 1 110 // P DPL 0 D Type idt[n].flags = 0x8E; idt[n].high_offset = high_16(handler); }
Setting Up Internal ISRs
An interrupt handler is also referred to as a interrupt service routines (ISR). The first 32 ISRs are reserved for CPU specific interrupts, such as exceptions and faults. Setting these up is crucial as they are the only way for us to know if we are doing something wrong when remapping the PIC and defining the IRQs later. You can find a full list either in the source code or on Wikipedia.
First, we define a generic ISR handler function in C. It can extract all necessary information related to the interrupt and act accordingly. For now we will have a simple lookup array that contains a string representation for each interrupt number.
char *exception_messages[] = { "Division by zero", "Debug", \\ ... "Reserved" }; void isr_handler(registers_t *r) { print_string(exception_messages[r->int_no]); print_nl(); }
To make sure we have all information available, we are going to pass a struct of type
registers_t to the function that is defined as follows:
typedef struct { // data segment selector uint32_t ds; // general purpose registers pushed by pusha uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax; // pushed by isr procedure uint32_t int_no, err_code; // pushed by CPU automatically uint32_t eip, cs, eflags, useresp, ss; } registers_t;
The reason this struct is so complex lies in the fact that we are going to invoke the handler function (which is written in C) from within assembly. Before a function is invoked, C expects the arguments to be present on the stack. The stack will contain some information already and we are extending it with additional information.
Below is an excerpt of the assembly code that defines the first 32 ISRs. Unfortunately there is no way to know which gate was used to invoke the handler so we need one handler for each gate. We have to define the labels as
global so that we can reference them from our C code later.
global isr0 global isr1 ; ... global isr31 ; 0: Divide By Zero Exception isr0: push byte 0 push byte 0 jmp isr_common_stub ; 1: Debug Exception isr1: push byte 0 push byte 1 jmp isr_common_stub ; ... ; 12: Stack Fault Exception isr12: ; error info pushed by CPU push byte 12 jmp isr_common_stub ; ... ; 31: Reserved isr31: push byte 0 push byte 31 jmp isr_common_stub
Each procedure makes sure that
int_no and
err_code are on the stack before handing over to the common ISR procedure, which we will look at in a moment. The first push (
err_code), if present, represents error information that is specific to certain exceptions like stack faults. If such an exception occurs, the CPU will push this error information to the stack for us. To have a consistent stack for all ISRs, we are pushing a
0 byte in the cases where no error information is available. The second push corresponds to the interrupt number.
Now let's look at the common ISR procedure. It will fill the stack with all information required for
registers_t, prepare the segment pointers to invoke our kernel ISR handler
isr_handler, push the stack pointer (which is a pointer to
registers_t actually) to the stack, call
isr_handler, and clean up afterwards so that the CPU can resume where it was interrupted.
isr_handler has to be marked as
extern, because it will be defined in C.
[extern isr_handler] isr_common_stub: ; push general purpose registers pusha ; push data segment selector mov ax, ds push eax ; use kernel data segment mov ax, 0x10 mov ds, ax mov es, ax mov fs, ax mov gs, ax ; hand over stack to C function push esp ; and call it call isr_handler ; pop stack pointer again pop eax ; restore original segment pointers segment pop eax mov ds, ax mov es, ax mov fs, ax mov gs, ax ; restore registers popa ; remove int_no and err_code from stack add esp, 8 ; pops cs, eip, eflags, ss, and esp ; iret
Last but not least, we can register the first 32 ISRs in our IDT using the
set_idt_gate function from before. We are wrapping all the invocations inside
isr_install.
void isr_install() { set_idt_gate(0, (uint32_t) isr0); set_idt_gate(1, (uint32_t) isr1); // ... set_idt_gate(31, (uint32_t) isr31); }
Now that we have the CPU internal interrupt handlers in place, we can move to remapping the PIC and setting up the IRQ handlers.
Remapping the PIC
In our x86 system, the 8259 PIC is responsible for managing hardware interrupts. Note that an updated standard, the advanced programmable interrupt controller (APIC), exists for modern computers but this is beyond the scope of this post. We will utilize a cascade of two PICs, whereas each of them can handle 8 different IRQs. The secondary chip is connected to the primary chip through an IRQ, effectively giving us 15 different IRQs to handle.
The BIOS programs the PIC with reasonable default values for the 16 bit real mode, where the first 8 IRQs are mapped to the first 8 gates in the IDT. In protected mode however, these conflict with the first 32 gates that are reserved for CPU internal interrupts. Thus, we need to reprogram (remap) the PIC to avoid conflicts.
Programming the PIC can be done by accessing the respective I/O ports. The primary PIC uses ports
0x20 (command) and
0x21 (data). The secondary PIC uses ports
0xA0 (command) and
0xA1 (data). The programming happens by sending four initialization command words (ICWs). If the following paragraphs are confusing, I recommend reading this comprehensive documentation.
First, we have to send the initialize command ICW1 (
0x11) to both PICs. They will then wait for the following three inputs on the data ports:
- ICW2 (IDT offset). Will be set to
0x20(32) for the primary and
0x28(40) for the secondary PIC.
- ICW3 (wiring between PICs). We will tell the primary PIC to accept IRQs from the secondary PIC on IRQ 2 (
0x04, which is
0b00000100). The secondary PIC will be marked as secondary by setting
0x02=
0b00000010.
- ICW4 (mode). We set
0x01=
0b00000001in order to enable 8086 mode.
We finally send the first operational command word (OCW1)
0x00 =
0b00000000 to enable all IRQs (no masking). Equipped with the
port_byte_out function from the previous post we can extend
isr_install to perform the PIC remapping as follows.
void isr_install() { // internal ISRs // ... // ICW1 port_byte_out(0x20, 0x11); port_byte_out(0xA0, 0x11); // ICW2 port_byte_out(0x21, 0x20); port_byte_out(0xA1, 0x28); // ICW3 port_byte_out(0x21, 0x04); port_byte_out(0xA1, 0x02); // ICW4 port_byte_out(0x21, 0x01); port_byte_out(0xA1, 0x01); // OCW1 port_byte_out(0x21, 0x0); port_byte_out(0xA1, 0x0); }
Now that we successfully remapped the PIC to send IRQs to the interrupt gates 32-47 we can register the respective ISRs.
Setting Up IRQ Handlers
Adding the ISRs to handle IRQs is very similar to the first 32 CPU internal ISRs we created. First, we extend the IDT by adding gates for our IRQs 0-15.
void isr_install() { // internal ISRs // ... // PIC remapping // ... // IRQ ISRs (primary PIC) set_idt_gate(32, (uint32_t)irq0); // ... set_idt_gate(39, (uint32_t)irq7); // IRQ ISRs (secondary PIC) set_idt_gate(40, (uint32_t)irq8); // ... set_idt_gate(47, (uint32_t)irq15); }
Then, we add the IRQ procedure labels to our assembler code. We are pushing the IRQ number as well as the interrupt number to the stack before calling the
irq_common_stub.
global irq0 ; ... global irq15 irq0: push byte 0 push byte 32 jmp irq_common_stub ; ... irq15: push byte 15 push byte 47 jmp irq_common_stub
irq_common_stub is defined analogous to the
isr_common_stub and it will call a C the function
irq_handler. The IRQ handler will be defined a bit more modular though, as we want to be able to add individual handlers dynamically when loading the kernel, such as our keyboard handler. To do that we initialize an array of interrupt handlers
isr_t which are functions that take the previously defined
registers_t.
typedef void (*isr_t)(registers_t *); isr_t interrupt_handlers[256];
Based on that we can write our general purpose
irq_handler. It will retrieve the respective handler from the array based on the interrupt number and invoke it with the given
registers_t. Note that due to the PIC protocol we must send an end of interrupt (EOI) command to the involved PICs (only primary for IRQ 0-7, both for IRQ 8-15). This is required for the PIC to know that the interrupt is handled and it can send further interrupts. Here goes the code:
void irq_handler(registers_t *r) { if (interrupt_handlers[r->int_no] != 0) { isr_t handler = interrupt_handlers[r->int_no]; handler(r); } port_byte_out(0x20, 0x20); // primary EOI if (r->int_no < 40) { port_byte_out(0xA0, 0x20); // secondary EOI } }
Now we are almost done. The IDT is defined and we only need to tell the CPU to load it.
The IDT can be loaded using the
lidt instruction. To be precise,
lidt does not load the IDT but instead an IDT descriptor. The IDT descriptor contains the size (limit in bytes) and the base address of the IDT. We can model the descriptor as a struct like so:
typedef struct { uint16_t limit; uint32_t base; } __attribute__((packed)) idt_register_t;
We can then call
lidt inside a new function called
load_idt. It sets the base by obtaining the pointer to the
idt gate array and computes the memory limit by multiplying the number of IDT gates (256) with the size of each gate. As usual, the limit is the size - 1.
idt_register_t idt_reg; void load_idt() { idt_reg.base = (uint32_t) &idt; idt_reg.limit = IDT_ENTRIES * sizeof(idt_gate_t) - 1; asm volatile("lidt (%0)" : : "r" (&idt_reg)); }
And here goes the final modification of our
isr_install function, loading the IDT after we installed all ISRs.
void isr_install() { // internal ISRs // ... // PIC remapping // ... // IRQ ISRs // ... load_idt(); }
This concludes the IDT section of this post and we can finally move to keyboard specific code. It is supposed to be a blog post about a keyboard driver after all, am I right?
Keyboard Handler
When a key is pressed, we need a way to identify which key it was. This can be done by reading the scan code of the respective keys. Note that the scan codes distinguish between a key being pressed (down) or being released (up). The scan code for releasing a key can be calculated by adding
0x80 to the respective key down code.
A
switch statement contains all key down scan codes we want to handle right now. If a scan code does not match any of those cases, this can have 3 reasons. Either it is an unknown key down, or a released key. If the released key is within our expected range, we simply subtract
0x80 from the code. We can put this logic into a
print_letter function:
void print_letter(uint8_t scancode) { switch (scancode) { case 0x0: print_string("ERROR"); break; case 0x1: print_string("ESC"); break; case 0x2: print_string("1"); break; case 0x3: print_string("2"); break; // ... case 0x39: print_string("Space"); break; default: if (scancode <= 0x7f) { print_string("Unknown key down"); } else if (scancode <= 0x39 + 0x80) { print_string("key up "); print_letter(scancode - 0x80); } else { print_string("Unknown key up"); } break; } }
Note that scan codes are keyboard specific. The ones above are valid for IBM PC compatible PS/2 keyboards, for example. USB keyboards use different scan codes. Next, we have to implement and register an interrupt handler function for key presses. The PIC saves the scan code in port
0x60 after IRQ 1 is sent. So let's implement
keyboard_callback and register it at IRQ 1, which is mapped to interrupt number 33.
static void keyboard_callback(registers_t *regs) { uint8_t scancode = port_byte_in(0x60); print_letter(scancode); print_nl(); }
#define IRQ1 33 void init_keyboard() { register_interrupt_handler(IRQ1, keyboard_callback); }
We are almost done! The only thing left to do is to modify the main kernel function.
New Kernel
The new kernel function needs to put all the pieces together. It has to install the ISRs, effectively loading our IDT. Then it will enable external interrupts by setting the interrupt flag using
sti. Finally, we can call the
init_keyboard function that registers the keyboard interrupt handler.
void main() { clear_screen(); print_string("Installing interrupt service routines (ISRs).\n"); isr_install(); print_string("Enabling external interrupts.\n"); asm volatile("sti"); print_string("Initializing keyboard (IRQ 1).\n"); init_keyboard(); }
Now let's boot and type something...
Amazing! Having a VGA driver and a keyboard driver in place, we can work on a simple shell in the next post :)
Cover image by John Karlo Mendoza on Unsplash
Discussion (8)
Writing a keyboard driver using the keyboard 😁
Keyboardception. Not as impressive as writing the C compiler in C, though :D
Oh, you mean Compilerception 😂
typedef void (*isr_t)(registers_t *);
wht do this line mean
it means that if i say
isr_t huh;
i mean
void (*huh)(registers_t *);
no able to understand irq_handler code
if (r->int_no < 40) {
port_byte_out(0xA0, 0x20); // secondary EOI
}
maybe be >=40
|
https://dev.to/frosnerd/writing-my-own-keyboard-driver-16kh
|
CC-MAIN-2022-33
|
refinedweb
| 2,870
| 62.68
|
Trapping "white document window"K.Daube Feb 13, 2017 8:22 AM
Dear fiends,
You know, the last 10% are the most cumbersome ones...
With my script I get a "white document window" after opening of document files. I can not reproduce the behaviour reliably neither within FM (with menu) nor with ESTK (invoking only one function without menu). Even if the white screen appears, ESTK does not show a halt or error.
Painstaikenly repeating the actions (after a double FM-restart - see later why double) the effect may happen or not:
------------------------------------------------------------------------ ESTK, different sequence of files Open FM Open Simple Text Start Script for work with Dialog C Refresh ... script works correctly Open Markers and tables => white screen Working on the markers possible (but I don't see what) CTRL-l does not do anything Running SetDisplay from ESTK does not change the situation Where are we stuck? Closing panel Closing FM is time consuming ------------------------------------------------------------------------ ESTK, different sequence of files Open FM Open Markers and Tables Start Script for work with Dialog C Refresh ... script works correctly Open Simple Text Marke contents is default Check syntax operates on marker of prev. document! (known problem) Open Developer log Refresh ... script works correctly Switching documents etc all works Open From-scratch-CS-markers => White screen There seems to be one C marker in there Closing panel Closing FM is time consuming
How to catch the reason for these white screens?
I can work on the document, but don't see the results...
Closing FM after appearance of "white document window":
Method one:
For each open document:
- Click on X to close document, wait (15 sec) until dialog "save yes/no") appears
- Document is visible
- Click either Yes or No and wait again (about 5 sec)
- Document is closed, nex one is white
Close FM with X
Nothing happens for at least 20 sec, so I click into the window which becomes white.
Click on X again => "Adobe FrameMaker is not responding"
OK => Cancel => FM disappears.
Method two:
Close FM with X and wait until the dialog "Select the files to save before closing" appears (30 sec)
OK => wait at least 10 sec, then the dialog closes
FM is still open und hence i click on X
=> "Adobe FrameMaker is not responding"OK => Cancel => FM disappears.
Why restart FM a second time before next test?
If I use the script just after a restart of FM (after the white screen happening), I get "Window can not be created" errors). Hence I need a second restart of FM. Then the script can be started again.
1. Re: Trapping "white document window"Klaus Göbel Feb 13, 2017 10:34 AM (in response to K.Daube)
Hi Klaus,
my first and quick guess is:
there's a registered script in the background that catches the "close"-event. (reason for the slow ending)
In that script there's "display = 0" (the reason for white screen)
2. Re: Trapping "white document window"K.Daube Feb 13, 2017 12:40 PM (in response to Klaus Göbel)
Hi Klaus,
My script does not catch a close event - only these:
Notification (Constants.FA_Note_PostActiveDocChange, true);
Notification (Constants.FA_Note_PostOpenDoc, true);
Notification (Constants.FA_Note_PostBookComponentOpen, true);
I just started FM-13
- Then I open one of the files I'm testing with
- There are two scripts registered already :MathmLUpdate.jsx and NumberUtility.jsx
- Start the script (it registers)
- Open a panel by shortcut
- Everything works as expected
- Open another document
- Zack- white document window
The Script library displays the same scripts as registered as before + of course my script.
For a next test I will outcomment all calls to SetDisplay. It is called to stop the flicker on certain actions on the document. There may be a wrong pairing (off- on) which leaves an off dangling.
I had numerous tests without registering my script (oucommenting call to SetUpNotifications). During these 1.5h playing around I never had the White Document Window effect.
Hence I primarily must look into the chain called from the Notify function - whether there is dangling a Display Off.
But why the heck does CTRL+l nor executing a SetDisplay from within ESTK nothing to the display? These actions work in other cases.
And why can the exactly repeated sequence of actions create random results - even if between tests I start FM twice to avoid "can not create Window" at the start of the script.
3. Re: Trapping "white document window"Wiedenmaier Feb 13, 2017 3:30 PM (in response to K.Daube)
Hi Klaus D,
it's hard to follow and to understand what happens here exactly. If a you have a white document my guess is anyone sets display property to false. If it's set to false and document is saved, this setting is saved within the document. So if you open it again next time, document is white again.
Could you check display property of this document?
If you want me to have a deeper look into that, just send me your script by mail. And perhaps I can find out what happens here exactly.
Markus
4. Re: Trapping "white document window"K.Daube Feb 14, 2017 9:15 AM (in response to Wiedenmaier)
Thanks, Markus for the idea.
At the time the white window appeared, I was able to save the document as MIF. The only occurrence of "display" is in these lines:
<DShowAllConditions Yes> <DDisplayOverrides Yes> <DPageScrolling Variable> <DViewOnly No> <DViewOnlyXRef GotoBehavior> <DViewOnlySelect Yes> <DViewOnlyWinBorders Yes> <DViewOnlyWinMenubar Yes> <DViewOnlyWinPopup Yes> <DViewOnlyWinPalette No> <DFluid No>
I have also checked the calling sequnces for SetDisplay - At the time of the white screen the display setting is requested to be 1, but remains 0 despite two calls for app.Displaying to become 1:
... ........CollectVariables(true) ..........PutRefPageCategory("Ref-Variables",[Array:#DOCname,#T1,#T2,#T3,#T4,#T5,#VAT]) ............SaveCurrentLocation([Doc:[object Doc]]) ............GetRefPagePara([Doc:[object Doc]],"Ref-Variables") ............GetParagraphs([Pgf:[object Pgf]],"Ref-Variables") ............RestoreLocation([Doc:[object Doc]],[Object:[object Object]]) ........FillUserVars([ListBox:[object ListBox]]) ........CollectMarkers([Array:[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker]],"#calc") ..........SetDisplay(false) SetDisplay - current: 0 => wanted: false ..........SaveCurrentLocation([Doc:[object Doc]]) ..........GetFindParameters(3,"#calc") ..........RestoreLocation([Doc:[object Doc]],[Object:[object Object]]) ..........SetDisplay(true) SetDisplay - current: 0 => wanted: true ........GetIndexNearestMarker([Array:[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker],[object Marker]],"#calc") ..........GetFindParameters(3,"#calc") ........RestoreLocation([Doc:[object Doc]],[Object:[object Object]]) ........SetDisplay(true) SetDisplay - current: 0 => wanted: true ......DisplayMarker([Doc:[object Doc]],[Marker:[object Marker]]) ......ActivateButtonsC() ......HideInsUpdButtonsC() UpdateDialogues wPalC.active => White screen Notify triggered iNote= 26 sParm= null iParm= 0 object.Name= undefined object.ID= 0 ..RemoveMyNotifications()
At the time the white screen appeared I looked at consfile.txt (not disturbing the FM session). The last line at this time is 25. Then the closing of the FM session required the earier mentioned procedure and added a few lines to consfile.txt
Hence we have (most likely) trapped the cause of the white screen: app.Displaying is not set to 1 - but why?
And there is still the question why this situation can not be repaired by CTL+l, or ESC w r, or a script in ESTK (#target framemaker) with just this: app.Displaying = 1;
Function SetDisplay is quite simple:
function SetDisplay (bWanted) { //=== Set display to on or off ==================================== // Arguments bWanted: true => set display ON; false => display OFF // Reference Rick Quattro if (bWanted) { if (app.Displaying === 0) { app.Displaying = 1; } } else { if (app.Displaying === 1) {app.Displaying = 0; } } } //--- end SetDisplay
From the trace (the complete log file is about 300 lines) you can see that the script is quite elaborous - If You still offer to look at it, please let me know.
It just comes to my mind: next test will be with bypassed SetDisplay (which is there only to avoid flicker during various operations).
5. Re: Trapping "white document window"frameexpert Feb 14, 2017 9:36 AM (in response to Wiedenmaier)
Displaying is a Session (app) property and is not saved with the document.
6. Re: Trapping "white document window"K.Daube Feb 14, 2017 9:46 AM (in response to frameexpert)
frameexpert wrote
Displaying is a Session (app) property and is not saved with the document.
Yes, I had this in mind, but needed to verify - my mind is not that reliable any more...
It just comes to my mind: next test will be with bypassed SetDisplay (which is there only to avoid flicker during various operations).
Since in function, it was easy to let it do nothing - and lo and behold: there is only flicker, but everything works as intended! so this app.Displaying is not reliable as my trace demonstrates.
7. Re: Trapping "white document window"Klaus Göbel Feb 14, 2017 9:58 AM (in response to K.Daube)
Hi Klaus,
the danger using notifications is, that you only get error messages in console somtimes. And sometimes NOT.
And it mostly ignores breakpoints when you are debugging.
So if a script runs into an error, it may skip the rest of the code / function without any alert.
And so it could happen, that your function SetDisplay hasn't been executed and app.Displaying = 0 stayed alive.
So it may depend on where you called "SetDisplay".
I'm just struggling with similar problems and the only way to trace the code is to use alerts and keep the console in mind.
8. Re: Trapping "white document window"frameexpert Feb 14, 2017 10:52 AM (in response to K.Daube)
I haven't followed this thread or your post closely, but let me explain something important about the Displaying property. In earlier versions of FrameMaker, this property just acted like a switch; if it was already 0, it didn't hurt to set it to 0 again. So code like this wouldn't cause any harm:
app.Displaying = 0;
...
app.Displaying = 0;
...
app.Displaying = 1;
...
app.Displaying = 1;
Somewhere along the line, Adobe made the property "stack-based" so that if you set it to 0 more than once, you have to set it to 1 an equal number of times. Not only that, but setting it to the same value multiple times seems to cause FrameMaker to hang. That is why I switched all my code to test the value before setting it.
if (app.Displaying === 1) {
app.Displaying = 0;
}
if (app.Displaying === 0) {
app.Displaying = 1;
}
I can't remember when the switch was made, but I think it was with FrameMaker 11. I remember going through a period after the update where I had to update a bunch of old scripts (both FrameScript and ExtendScript) and plugins because of this new behavior.
9. Re: Trapping "white document window"frameexpert Feb 14, 2017 10:57 AM (in response to frameexpert)
Here is an old post from another list by Russ Ward that shows that this is an FDK problem. Since ExtendScript and FrameScript are "wrappers" for the FDK, the problem shows up in them as well:
Hi,
(compiling with FDK10 and running on FM11, Win XP, VS2008)
A warning here about a problem that took me more than an hour to figure out, because it was in such an unlikely place and the debugger gave no clues. In my setup, if I issue this:
F_ApiSetInt(0, FV_SessionId, FP_Displaying, True);
...and the property is already True, FM11 will hang up for about 30 seconds. This didn't happen in earlier versions of FM. If I issue this, no hang:
F_ApiSetInt(0, FV_SessionId, FP_Displaying, False);
F_ApiSetInt(0, FV_SessionId, FP_Displaying, True);
...but this does hang:
F_ApiSetInt(0, FV_SessionId, FP_Displaying, False);
F_ApiSetInt(0, FV_SessionId, FP_Displaying, True);
F_ApiSetInt(0, FV_SessionId, FP_Displaying, True);
So anyway, the gist is that you should test the current value before setting it to True. I was sticking this at the end of certain routines as a failsafe to ensure display restoration afterwards. On my machine, FM11 doesn't like it if display is already on. Complicating the problem is that the hang occurs when the code exits your function, not when you issue the SetInt() call, hence why the debugger was of marginal help.
If this is just an anomaly on my machine, then please disregard.
Russ
10. Re: Trapping "white document window"frameexpert Feb 14, 2017 10:57 AM (in response to frameexpert)
BTW, this behavior was confirmed by someone on the FrameMaker team at Adobe, but I can't find the email right now.
11. Re: Trapping "white document window"Wiedenmaier Feb 14, 2017 1:41 PM (in response to frameexpert)
Hi Rick,
thanks for bringing this background Information to FP_Displaying. I also ran into this trap several times, but I didn't know that this is put to a stack...
And you are right, this is a Session property and it is not stored within the document. I mixed something up.
But I remember a bug in some of mine code a long time ago.
I set any property to the document (I don't remember which one it was, yet). A few lines later I crashed FM with another bug in my code. (document was saved before).
After that I restarted FM and opened this document with "File > Open" by hand. And this document was always white. Other documents worked well.
So there must be any setting or combination of document settings which brings up this effect.
Markus
12. Re: Trapping "white document window"Wiedenmaier Feb 14, 2017 1:47 PM (in response to K.Daube)
Klaus,
If you want me to give you a hand, feel free to send your code, with a short step by step description on how to reproduce this behavior by mail.
Markus
13. Re: Trapping "white document window"Wiedenmaier Feb 14, 2017 2:10 PM (in response to Klaus Göbel)
Hi Klaus G. schrieb
the danger using notifications is, that you only get error messages in console somtimes. And sometimes NOT.
And it mostly ignores breakpoints when you are debugging.
I'm just struggling with similar problems and the only way to trace the code is to use alerts and keep the console in mind.
First I have to say: This Editor In This Forum Is A PAIN :-) GRRR
Sorry, just saying. and now to the topic.
I never got this to work debugging notification or command events. This is also terrible. But I found out some best practice for me to work around this. Perhaps this is the time to share it :-)
I always create a main script file. Here I create menus and register for notifications and here I implement Command and Notify callback, with a switch case.
#include "dosomething.jsxinc"; function Notify(notification, doc, sparm, iparm) { switch(notification) { case somenotification: DoSomething(doc, sparm, iparm); break; } }
Within a case I only call a function which is implemented in further *.jsxinc files (extension doesn't matter, gives only a better overview in Explorer). These jsxinc files are included with "include" statement.
These certain function take "doc, sparm, iparm" in function declaration of Notify-callback handlers, like:
function DoSomething(doc, sparm, iparm) { //code here... }
Within development process, I have a dev.jsx file, which calls these functions and sets certain Parameters, for testing and depending on the notifaction it should handle
If only document is relevant, I call:
DoSomething(app.ActiveDoc, "", 0);
If a filename is relevant like (PreOpen Event) I call:
DoSomething(app.ActiveDoc, "C:\foo.xml", 0);
and so on.
I made good experiences with that, and never hat big troubles when I do my integration tests. Of Course you need to know which parameter values are provided by certain notification. Here FDK reference could help and if not the old good message box handling works. But good luck with notifications which are fired very often like "BackToUser" and others.
Hope this helps anyone.
Markus
14. Re: Trapping "white document window"K.Daube Feb 15, 2017 2:12 AM (in response to Wiedenmaier)
@Rick
The SetDisplay as I have it should fulfill the stated requirements:
function SetDisplay (bWanted) { // Arguments bWanted: true => set display ON; false => display OFF // Reference Rick Quattro if (bWanted) { if (app.Displaying === 0) { app.Displaying = 1; } } else { if (app.Displaying === 1) {app.Displaying = 0; } } } //--- end SetDisplay
Hence I have no clue why at a certain stage it stops working - that is, does not switch anymore.
Having inserted a return before line 4 to bypass this function cures the White Screen problem, but of course leaves the user with a flickering screen.
@Markus
At least part of method to debug is present in my script - I will put it together with test files in a ZIP and send it offline to You. Maybe You find a reason for the coupling of Console output with the panels (if closing the console any panel will also be closed) - but again, not in all cases.
@All of you
It's somewhat a relief to hear that also seasoned experts have problems with ExtendScript and FDK - in particular with the lack of (some) documentation.
15. Re: Trapping "white document window"Wiedenmaier Feb 15, 2017 2:28 PM (in response to K.Daube)
> It's somewhat a relief to hear that also seasoned experts have problems with ExtendScript and FDK - in particular with the lack of (some) documentation.
You're right. Documentation especially for ExtendScript could get much better, as - let's say it clear - there is not really one. But there is a reasonable documentation available for programming with the FDK and it is not hard to follow even if you have no C-experiences yet.
In most cases follow these rules:
1. Functions in C has all a prefix F_Api. In ExtendScript this is a method of the object, without this prefix. The object type where this method is definied is (mostly) the last F_ObjHandleT Parameter of each C function declaration.
Examples:
C: F_ApiSimpleSave(F_ObjHandleT docId, StringT saveAsName, IntT interactive)
ES: doc.SimpleSave(saveAsName, interactice)
C: F_ApiGetText(F_ObjHandleT docId, F_ObjHandleT objId, IntT flags);
ES: obj.GetText(flags)
(where obj is an FO_* listed a the beginning of function descriptions, i.e. FO_Cell, FO_Flow)
2. Properties of objects in C has an Prefix FP_. In ExtendScript just skip this prefix.
3. Constants in C (i.e. starting with FV_) are defined 1:1 within the ES Constants class.
4. If you are reading this documentation especially sample code, skip all this memory allocation stuff like (F_Alloc; F_ApiDeallocate*, F_New, a.s.o). This is C specific and doesn't matter with ES.
But to be honest. We are talking about programming. Most of the issues discussed in this Forum, can't be covered by documentation. I'm sure this is not possible to get this stuff done by any developer or writer. So you need forums, like this, blogs and a good developer support.
All stuff can always be better than it is.
This is not an FrameMaker/FDK/ES only problem. I develop against many APIs (Word, Trados, and several Web-APIs and more). Always the same if you come to implement your own specific use cases. My daily work is to find workarounds. All these applications/APIs are that complex today that not anything can be covered by documentation. It needs a lot of experience!!!
And the good stuff on this is: With any of these problems you are getting better and better :-)
So don't worry
Markus
16. Re: Trapping "white document window"Wiedenmaier Feb 16, 2017 2:05 PM (in response to K.Daube)
Dear Klaus D.,
First thank you for providing your code. I think I've got the reason:
At some certain point FM is not able to reactivate app.Displaying again. At this point you can set
app.Displaying = 1
as often you want. app.Displaying is still 0.
Your code is well so far. You are de-/activating app.Displaying correctly*). But I found out, that this happens, when your function UpdateDialogues() is called on PostOpenDoc event. But this same function works well, if it is called when PostActiveDocChanged is fired. Switching documents always works very well as often you are doing this.
But after calling UpdateDialogues() in PostOpenDoc-event-handler, this function is called again after that in your PostActiveDocChanged-event-handler.
For some reason FM doesn't like this. It comes to a state, where changing app.Displaying is not possible anymore.
So I've found two solutions for you:
Solution 1: setting object as current document after it is opened (line 6). You have a handler for checking current document to that in your globals variable, in PostActiveDocChange event
case Constants.FA_Note_PostOpenDoc: // 2 another doc has been opened if (object.Name === "") { // new document PaletteDocSettings(); // set up ref page etc. } UpdateDialogues (object); goVal.oCurrentDoc = object ; break;
Solution 2: Think about if you really need the PostOpenDoc event handler, as PostActiveDocChanged is called afterwards. If not put the if clause to PostActiveDocChanged event handler, and this also works.
*)
SetDisplay function is a little bit smarter and better readable if you implement it like this:
function SetDisplay (bWanted) if (settings.bDebug) { .... } if (app.Displaying != bWanted) { app.Displaying = bWanted; } } //--- end SetDisplay
(but of course this is up to you)
Hope this helps. Let me know if Problem is solved in your environment, too.
Markus
17. Re: Trapping "white document window"K.Daube Feb 17, 2017 1:48 AM (in response to Wiedenmaier)
Markus, this is really a great answer.
Both your recommendations work fine - i stick tot he second one: have only one handler, namely that for and test there for 'new document': PostActiveDocChanged.
I already have left out the handler for Revert to Saved (), since the action triggers 3 events: PostOpenDoc (2), PostActiveDocChanged (105 and PostRevertDoc (29). I had expected that the action Revert to Saved woud trigger only the last event.
Thank you, Markus, again for this great solution!
|
https://forums.adobe.com/thread/2276988
|
CC-MAIN-2017-39
|
refinedweb
| 3,652
| 64.91
|
Hello
I want to develop a recursive
Either type as a Swift enum (at least a partially working version ;)), and so have been playing around with generics (trying to work with the type system).
Here is what I have so far:
enum NumericEitherEnum<Left, Right> { case left(Left) case right(Right) var left: Left? { switch self { case .left(let leftie) where leftie is NumericEitherEnum<Int, Float>: return (leftie as? NumericEitherEnum<Int, Float>)?.left // This won't work (obviously) case .left(let left): return left case .right(_): return nil } } var right: Right? { switch self { case .left(_): return nil case .right(let right) where right is NumericEitherEnum: return (right as? NumericEitherEnum)?.right // This assumes the generic parameters of Left, Right in the current enum so won't work. case .right(let right): return right } } }
I get cryptic diagnostic error messages in Xcode, which I haven't been able to get around:
- 'Replace
(leftie as? NumericEitherEnum<Int, Float>)?with
NumericEitherEnum<Int, Float>'
- 'Enum case 'left' cannot be used as an instance member'
What I am trying to achieve:
print(NumericEitherEnum<NumericEitherEnum<Int, Float>, NumericEitherEnum<Int, Float>>.left(.left(3)).left ?? "failed :(") // Parses the innermost value 3
The fix-it doesn't fix the error or advise how to actually address the underlying cause. I think this is probably an edge case for the compiler to parse (maybe even bug) ;). I also realise that in fact it doesn't make sense logically to return an
Int for a
Left? type but is there any way I can express this within the type system (I tried associated types but I still don't know how to make this dynamic).
I am not sure if this is actually possible so please explain in simple terms (if possible) how I might resolve this issue in a better way (preferably using an enum, but using a different struct could be good if enums are impossible or impractical in this instance).
Thanks for the help!
|
https://forums.swift.org/t/recursive-swift-enum-with-associated-values/45325
|
CC-MAIN-2021-31
|
refinedweb
| 328
| 64.1
|
- Join Date
- Mar 2007
- Location
- Frederick MD, NYC, DC
- 16,232
- Vote Rating
- 50
MVC app listing all views, stores and models is unmanageable
MVC app listing all views, stores and models is unmanageable
When reading source code for pre PR4 controller extensions, it was easy to determine what views, models, and stores a particular controller is to manage. That pattern worked well in the direction of the "Self documenting code" practice.
Moving views, models and stores to the application really goes against self documenting code as controllers often are specific to a certain view and/or model. I initially liked the idea of centralized configuration, but am now against it. Application definitions will become bloated and hard to manage/maintain for larger apps.
While thinking about MVC for ST2, please keep in mind that this code will most likely be used for Ext JS5, where tens of views, stores and models can pollute the application definition.
Just look @ the app.js for the kitchen sink demo. Imagine if there were an equal amount of models and stores listed there.
Code:
views: [ 'NestedList', 'List', 'SourceOverlay', 'Buttons', 'Forms', 'Icons', 'BottomTabs', 'Themes', 'Map', 'Overlays', 'Tabs', 'Toolbars', 'JSONP', 'YQL', 'Ajax', 'Video', 'Audio', 'NestedLoading', 'Carousel', 'TouchEvents', 'SlideLeft', 'SlideRight', 'SlideUp', 'SlideDown', 'CoverLeft', 'CoverRight', 'CoverUp', 'CoverDown', 'RevealLeft', 'RevealRight', 'RevealUp', 'RevealDown', 'Pop', 'Fade', 'Flip', 'Cube' ],
In this new model, I have to remember: What controller requires what models, stores and views? Did i get ALL of them in the app.js? This leads to potential pollution in production apps.
I'm sure the team has a really good reason for making this change. I just can't see it.
I would love to hear what the community thinks.
Since Ext.app.Application extends Ext.app.Controller, I would think it would be trivial to move these kinds of configs to the Controller and still have the Application use it. I'm not sure why the behavior was moved off of Controller, possibly a performance decision but I will open a ticket for this.
I'm not sure about the SenchaCon app but TouchForums has quite a few views and if I were to define them in the Application that array would be quite long also. However, most of the time I don't put views in the application, I use the requires property in the different views that require thatay - totally agree with you and didn't like having to move all my views, models, and stores into the application. What if you have a controller that is used in 3 different applications? Now when you add a view to that controller, instead of adding it in one place (the controller) you have to add it to three applications. What if developer A is working on application A and didn't realize he just broke applications B and C?
The thing I like to do is keep my application dumb. I prefer to define controllers and a launch() function in the application and that's about it. I define a launch() method in a controller that I want to initially control the app.
I was surprised that in beta1 they moved it to a central place, but on the other side, the new routes config moved to the controller (as opposed to a central place as in ST1).
I don't have an opinion on both yet, though. I'll see with time how it feels/maintains.
Usually you have your views structured into namespaces, therefore a "views" array of a normal application would look a bit more organized than the kitchensink code example.
What I don't like in >= beta1 though is that if you use namespaces in views, you have to specify the complete namespace, e.g. "SomeApp.view.nested.View" instead of just "nested.View".
Also, I'm often on the fence if I specify a view in the app config or in the "requires" config option of the main views as Mitchell points out.Owner of 360releases Ltd. - Sencha Touch & Ext JS consulting
twitter.com/steffenhiller
extjswithrails.com, senchatouchbits.com
estesbubba,
could you give me an example of where you'd use the same controller in 3 different applications?
Just curious.Owner of 360releases Ltd. - Sencha Touch & Ext JS consulting
twitter.com/steffenhiller
extjswithrails.com, senchatouchbits.
+1 for this.
To me, having controllers define views, stores, & models bodes well for reusable modules. Also, as stated earlier, it makes our controllers more humanly readable.
Device Order App (workflow used by end user and CSR)
Device Activation App (workflow used by end user and CSR)
Account Maintenance App (used by end user and can also do Device Order and Device Activation workflows)
The workflows have controllers, views, stores, and models that are shared by all 3 applications. Each workflow has a "master" controller (DeviceOrderController and DeviceActivationController) and they communicate with the workflow controllers via events.
In addition to the 3 applications in the above product we also have other products which use these workflow controllers, views, etc. So this "workflow library" is used by several products and each product can have multiple applications within it.
- Join Date
- Jan 2009
- Location
- Palo Alto, California
- 1,939
- Vote Rating
- 7
I've moved this into Discussion as it's obviously not a bug. The imminent B3 release has a new guide on dependency philosophy that I'd like you to take a look at as it lays out the reasoning behind this change. Happy to hear other viewpoints of course.
Last edited by edspencer; 14 Feb 2012 at 1:28 PM. Reason: yes I meant viewpoints not viewports ;)Ext JS Senior Software Architect
Personal Blog:
Twitter:
Github:
|
http://www.sencha.com/forum/showthread.php?180802-MVC-app-listing-all-views-stores-and-models-is-unmanageable
|
CC-MAIN-2013-48
|
refinedweb
| 940
| 61.67
|
Bulat Ziganshin wrote: > Hello]: I see that "n" is not in an IORef, and for n=1 your loop leaves sum holding 0, which is just the kind of off-by-1 fencepost but that c excels in generating: > > c code: int sum(int n) { int i = 1; int result = 0 for (; i<=n ; ++i) { result += i; } return result; } haskell: You really want this to be strict, so replace modifyIORef with modifyIORef' > modifyIORef' r f = do new <- liftM f (readIORef r) > writeIORef r $! new > return new > s1 n = do > sum <- newIORef 0 > forM_ [1..n] $ \i -> modifyIORef' sum (+i) > readIORef sum As you mentioned, there is easy syntactic sugar definable in Haskell itself: > a .+=. b = do new <- liftM2 (+) (readIORef a) (readIORef b) > writeIORef a $! new > > a .<=. b = liftM2 (<=) (readIORef a) (readIORef b) > > succ_ i = modifyIORef' i succ > > for init test inc block = do > init > let loop = do proceed <- test > when proceed (block >> inc >> loop) > loop With that sugar it becomes easy to look very much like the c-code: > s2 n = do > sum <- newIORef 0 > i <- newIORef 1 > for (return ()) (i .<=. n) (succ_ i) > (sum .+=. i) > readIORef sum And we do have "postfix" operators with the latest GHC: > (.++) a = do old <- readIORef a > writeIORef a $! succ old > return old
|
http://www.haskell.org/pipermail/haskell-cafe/2006-December/020641.html
|
CC-MAIN-2014-49
|
refinedweb
| 209
| 74.12
|
.
You can run the esxcli command directly in ESXi BusyBox Shell. For that you will need to have either direct access to the ESXi console, or SSH to the ESXi (you need to turn on the SSH Shell access). Should you have multiple ESXi servers to run the commands simultaneously, try the free DoubleCloud ICE I developed.
Alternatively, you can install vCLI on Windows or Linux from where you want to remotely manage ESXi servers. If you don’t want to install the package by yourself, you can download the vMA virtual appliance which has everything pre-installed and pre-configured. When you run the command this way, there is additional parameters for remote ESXi server address and credential. Other than that, the command syntax should be the same as native esxcli command.
There is actually another choice which is not documented but I digged it out anyway – You can run esxcli command in a browser. If you are interested, you can check out this post. Note that this is not supported by VMware.
This tutorial will guide you through all functionalities with samples and tips/tricks assuming we are using the native esxcli command. Given the complexity of the command, I cannot run all the combinations of parameters, please feel free to use the help and try by yourself when you cannot find exact sample. Should you find something worth sharing, please feel free to post them in the comments.
Where Is It Installed?
The esxcli command utility comes with the ESXi installation. If you type in the following commands you will find where it’s installed. Even more is that you will uncover the a little secret of esxcli – it’s essentially a Python script. If you are interested in what is in the script, you can simply check it out with vi command. We’ll not dig deeper there, but focus on the usage of the command as a user.
What You Can Do With It?
Unlike the vim-cmd command which mainly focuses on the virtual machine related management, the esxcli focuses on the infrastructure like hardware, storage, networking, esxi software, etc.
Typing the esxcli command without any argument will displays the command usage. With the options, you can control the format of the output to be xml, csv, key/value pair, or json.
The esxcli command is a very complex command that achieve a lot given it’s a single command. To help user to use the command without getting confused, the namespaces are used to group the commands. The namespaces can be further divided into sub-namespaces depending the complexity.
The following command shows the top level namespaces, each of which can be nicely mapped to a group of functionality. Just reading description of these commands should give you an idea on what esxcli can do for you. We’ll dig deeper into each of them in the following sections.
A bit more on the format. In the interactive mode, the default format of output is perfect. If you use the esxcli command for automation, other formats may be preferred. For example, the CSV can be easily imported into Excel or other spreadsheet for reporting and analytics. The XML is very good for data exchange. The key and value pairs are good shell script to consume. There are actually undocumented formats as I blogged about a while back.
High Level Conventions
In some way, the esxcli namespaces are like Java packages. At certain points down the namespace hierarchy, you can find available commands (think of them as methods on a class). One big difference is that there can be commands on a non-leaf namespace. Simply entering the full esxcli and namespace path will show both available namespaces and available commands.
The commands are mostly verbs as follows:
* list – retrieve a list of the objects that are represented by the namespace
* get – get information like property
* set – set a value
* load/unload – load/unload configuration
Note that they are not necessarily available in all the namespaces. When in double, always checkout the command line.
Depending on the command, there may be additional options specific to the command. These options are different from the general options which are always available for all commands.
Without further due, let’s jump to the sub-commands one by one.
Listing All esxcli Namespaces and Commands
Interestingly, the esxcli can also be a sub command to the esxcli command itself. What it does is very simple — list all the available namespaces and their commands. Because there are so many lines in the output, I will just show you the first few lines. You can easily find out in your SSH to ESXi.
Now, let’s take a look how to interpret the output. For each line, there is a corresponding esxcli command. Let’s pick up the second line “fcoe.adapter.” The related command is like the following:
The rule of thumb is to replace the dot with space and combine string together with top esxcli command and last command. For some commands, there are additional parameters, you may need to add there. For the list command, it’s mostly fine without additional parameters except the format as we discussed earlier.
Managing Fiber Channel Over Ethernet (FCOE)
We will not cover FCOE here as there are many good introduction already. Check out Cormac’s blog.
The following command shows it has two name spaces: adapter and nic.
To list adapters, you can use the following command:
I don’t have a FCOE adapter in my home lab, but got a sample out from VMware KB article here for each adapter:
For the NIC namespace, there are more commands available:
Here are the sample commands: (Again, the output sample from above KB article)
Managing Hardware
All the hardware related commands fit in the hardware namespace. As you can see the following output, you can retrieve information or manage various aspects of the hardware including cpu, ipmi, boot device, clock, memory, pci, platform (a little vague term, but will elaborate more soon), trusted boot.
Because hardware is hard, you cannot do much about it but retrieving the information about these components or aspects. So the list command is the most commonly used in this category.
The following command lists the CPU related information. There are 8 cores, but I just show 2 core inforation here – the rest 6 is pretty much the same.
IPMI stands for Intelligent Platform Management Interface (). It allows remotely managing the server over IP network. From the esxcli commmand, you can further manage the Field Replaceable Unit, Sensor Data Repository, and System event log.
My server in use does not have the IPMI support, so the following commands return nothing or empty values. If you have enabled servers, you will see more with the same commands.
Listing the boot devices is supported with the bootdevice namespace as follows. Interestingly, the output lists nothing – the server did boot successfully.
Every computer has a clock. With esxcli command, you can get the time on the clock, and change the time on the clock. The parameters to set up new time is a little tricky, but using the help should be very easy. You can set individual component of the time, say year, month, etc.
Retrieving the physical memory of ESXi server is very simple with the following command. It also shows the NUMA node count.
PCI information can be retrieved with the pci name space as follows. The output is pretty long, so I just include the first device. With the long output, you can pipeline it to grep command for exact information you are interested in.
Now it’s time for the vague platform namespace. Let’s start with the command itself. With that, I don’t need to explain what the platform is.
Last one in the hardware is the trusted boot. Again, my server does not have the feature. For more details on the technology, check out this wiki page:
ESXi Kernel Scheduling
With the sched namespace, we can manage VMKernel system properties and configure scheduling related functionality like swapping.
The changing of properties is through the set command. You can change one or more properties at a time with the switches as listed below.
Managing VIB Software
The design of ESXi is to keep the hypervisor as small as possible. Being small has many benefits, for example, less exposure to security attacks. At the same time, we need some flexibility to install new drivers or other software agents on the ESXi. This allows VMware partners to customize the system and extend the system with additional functionalities.
For that purpose, VMware created VIB format based on a Linux package system. It has related SDK for others to build the VIB. The commands in this section is about how to manage the VIBs with command line.
You can use the sources namespace to “browse” the VIB packages in a VIB depot. Before running the command, you want to modify firewall to allow HTTP client.
In this sample, I used the v-front.de which has a rich collection of VIBs. In your company, you may have your own VIB depot.
If you use the get command, you will get a lot more details than the list. The following shows one part of the long output.
This blog post has excellent introduction and more sample commands.
You can list the image profiles as follows. I intentionally used ESXi-6.0 for grep, or will get a lot more lines in output. Again, it connects to external site and you want to open firewall before this.
To find out the exact content in an image profile:
Supposedly you can download a zip and point the depot to it as follows. Somehow it does not work even though I had the full path to the zip file as recommended by a few bloggers.
The error message is not true because the zip file seems a valid zip file (not all output lines are listed)
ESXi has different level of acceptance for installing new VIBs. Changing acceptance levels enables installing VIBs from other vendors possible.
The level must be one of the values: VMwareCertified, VMwareAccepted, PartnerSupported, CommunitySupported. The acceptance level decides if some packages can be installed or not. From VMwareCertified to CommunitySupported, the criteria loosens up.
Different VIBs combined together forms a big collection called image profile. To manage image profile, the following commands can be used:
It’s quite easy to list all the VIBs installed on the system. The following shows the command and part of output.
To get more details of a specific VIB, you can use the get command as follows with the VIB name.
To install a VIB, you should install command with VIB locations. For the VIB not signed, you want to turn off the signature checking with –no-sig-check option. WARNING: If your installation requires a reboot, you need to disable HA first.
iSCSI Management
iSCSI allows ESXi to use storages on remote iSCSC servers. The esxcli command can help to manage this feature on different layers in the stack. Again, I don’t have the set up with iSCSI support. Instead of real commands, the following commands shows mostly the help so that you can see what are theree.
Network Management
ESXi has a rich set of features in networking. All the network related commands are grouped in the network namespace. To take a look at what are available there, simply type in:
As you can find there are more sub-namespaces, each of which is still a big topic of itself.
Firewall Management
To find out the current firewall status, get command is the way to go:
Firewall module can be unloaded or loaded using the unload and load command as follows:
When firewall working, you can enable and disable the firewall as follows. You want to keep the firewall enabled all the time.
You can also set the default action of firewall to let pass everything or block everything. When true is used, the firewall lets go everything unless specified otherwise; when false is used, it blocks everything by default.
After you change firewall configuration, the ruleset may be out of sync with the active. To keep in sync, you can simply run the refresh command.
Above is the overall control of firewall. You can fine tune each individual rule set within the ruleset namespace.
You can change individual ruleset to be enabled or disabled, and change the behavior to all all IP addresses or only those specified.
Each ruleset consists of a collection of rules. You can list them using rule namespace. If you don’t provide ruleset-id as follows, you will get a long list of rules from all the rulesets.
Note that even with the powerful esxcli command, you can not modify much of the firewall configurations. For all the configurations, you want to go directly edit the configuration file then refresh the firewall:
Managing Fencing Switches
For this feature, you must distributed virtual switch configured; or you will see the same output as I saw here.
To get all fence network bridge table entries information, you can use the following command.
To get all fence port info on the fence network, you can use the following command:
Managing IP Addresses and Configurations
To get the IPv6 related support, simply type the following.
To turn off or turn on IPv6 support, you can use the set command. Note: you have to restart the ESXi for the configuration to take effect.
To manage vmKernel network interfaces, you can use the interface namespace as follows:
To change the IP address for ESXi on an existing interface is easy too, but be careful with this operation because your SSH session may be terminated immediately.
Managing DNS server
The ESXi depends on the DNS setting to resolve server names. The following commands help manage the DNS.
You also change the default search domain for the DNS settings.
Network Security
There are two aspects you can manage the security: security association, and security policy. There are quite a few options you can tune. Combined together, they can cover a lot of cases.
Managing Gateways
You can manage both IPv4 and IPv6 networks. I first show the IPv4 here because the IPv6 is very similar.
To change the gateway, try the following command. Again, you session may be terminated with invalid parameter.
To remove a route, you can use remove command with same parameters as the add command. Again, be careful as your session may be terminated right away.
For the IPv6 listing of routes, you can see something similar as follows:
List Live Network Connections
At any given time, you can find out what live connections are there.
The type of connection can be filtered as follows. I intentionally used udp as it’s a lot less than the tcp connections.
Finding Neighbour on Network
You can use the esxcli command to list the network neighbors on the same network.
Managing Network Interface Card (NIC)
To turn on NIC VLAN stats, we can use set command as follows, and then we can check the VLAN stats.
For each NIC, you can get its stats with the stats namespace.
To get the current configuration of a network interface, you can use the get command with the name of the interface.
You can set the NIC with different parameters like speed, duplex mode. For easy life, you can simply use the –auto option which let the ESXi automatically negoatiate these with other system. When you have –auto option, you must not specify the speed and duplex mode. NOTE: if you use SSH to your ESXi server, be careful not to mess up the NIC underlying.
For a particular NIC adapter, you can also turn it on and off. Be careful not to turn off the NIC underlying your SSH session, or you have to have physical access or IPMI.
Virtual Machine Related Networking
To list all the virtual machines and their ports and networks they connect to, use the list command as follows.
Further down the port namespace, we can get more details of ports used by a specific virtual machine which is identified by the world id. Please note that you can also find the uplink port ID, which can used as normal VM port ID for its stats and filters.
Getting Port Related Stats and Filters
For each port, you can get the stats based its port number. The following command shows what are included in the stats.
To get port filter related stats, run the following command. Somehow I don’t have filter therefore nothing is shown in output.
Managing SR-IOV
SR-IOV stands for Single Root I/O Virtualization. It allow one PCI device appears as multiple NIC cards to the hypervisor. Scott Lowe has a nice blog post on this topic.
To list the NICs that support SR-IOV, and list the virtual functions (VF) on a nic, run the following commands.
There is no SRIOV Nic with name vmnic0
Managing Virtual Switches
The standard and distributed virtual switch are in two parallel namespaces. They allow lots of control over virtual switches.
To list all the virtual switches, use the list command as follows:
To create a new virtual switch, use the add command with port number and name.
The newly created virtual switch takes default for mtu, and cdp, but you can change them using the set command with the options below.
You can delete a virtual switch by the remove command
There are many policies you can change with esxcli command, namely failover, security, shaping. You can set these policies using the set command under the corresponding namespace. The name for the virtual switch is case sensitive.
To add a new uplink to a virtual switch, you can run the following command. The uplink name must be a valid pnic name.
To remove an uplink, just use the remove commmand
Managing Port Groups
Port group is a “virtual” concept. It defines a common behavior for a group of ports.
To add a new port group, use the add command
To remove a port group, use the remove command:
You can change the VLAN ID with set command. Note that this may affect the network connectivity.
There are similar policies that are associated with port groups as with the virtual switch. The following shows 3 commands and you can see what are included in the policy.
Distributed Virtual Switch
Distributed virtual switch is similar to standard virtual switch but the control is centralized in vCenter server. The esxcli command allows control of the vmware virtual switch. For the Cisco Nexus 1000v, you can use their own command line that I introduced before.
~ # esxcli network vswitch dvs vmware
Usage: esxcli network vswitch dvs vmware {cmd} [cmd options]
Available Namespaces:
lacp A set of commands for LACP related operations
vxlan A set of commands for VXLAN related operations
Available Commands:
list List the VMware vSphere Distributed Switch currently configured on the ESXi host.
Diagnosing Network Connection with Ping
The ping command is very useful for testing network connection. The esxcli command comes with a handy one as well with additional controls. I found it’s extremely helpful when I tested the jumbo frame configuration for my ESXi to a NAS server.
There are more options as shown in the following.
Managing Storage
The storage is another heavy aspect of ESXi management. It includes 6 different sub namespaces, each of which is a big topic by itself.
Managing NFS
To list all the NFS volumes that are already mounted on the host, just run the list command.
To add a new NFS volume, you want to use the add command:
To remove an existing volume, then the remove command is handy.
Managing File System
To list all the mount points, you can run the following command. You can check out the volume names, types, size, free space.
With changes on the file system, you can also run the following command to rescan and automatically mount those unmounted.
To unmount a volume, use the unmount command with label or UUID.
Managing VMFS System
There are also snapshot feature that can be managed by a few commands.
Managing SAN Storage
As I don’t have SAN storage in my lab, I won’t go deeper on this, but show the help of the command. You can drill down and give it try by yourself.
Managing Native Multi-Path
We can also list the devices involved in Native Multipath:
Multipath policy can also be configured using different plugins, which are listed as follows:
To list the configuration of a particular policy, we can use the following command (The device value is a little bit long but you can copy and paste it from the list command)
To list all the storage array plugin (SATP), the following command is handy.
To change the SATP, the following options are needed.
Core Storage
The following command lists all the storage adapters on the host,
To make sure the adapters are found, run the rescan all command.
IO statistics are also available with the following command. More lines are actually there, but skipped here to save space.
To list storage adapters, the following command works.
Get device statistics
To get a list of the worlds that are currently using devices on the ESX host, the following command is used:
Optionally, we can list the partitions with their GUID as follows:
To list all devices that were detached manually by changing their state on the system, run the following command. This is related to the ESXi feature of pluggable storage architectures (PSA).
For the VAAI feature, we can get their status. In my case, it’s not used at all therefore no much to show.
To list all the SCSI paths on the system, use the following command:
For each path, it can be set active, or off using the set command.
For path level stats, the following command can be used:
To list plugins in the system, the following command is used:
To allow automatic claiming process of PSA, the autoclaim can be used. By default, it’s enabled and should not be turned off.
New rules can also be added into the rule set. The command expects a few parameters, but the help is probably the best – it comes with a few examples.
Managing System Wide Settings
This section involves global setting for the ESXi management.
Get ESXi Boot Device
Managing Core Dump
The ESXi core can be dumped to a network server if you configure it as follows:
Core can aso be dumped into local partition and that involves another sub namespace – partition.
To get the configuration, use the get command.
To set the configuration, the set command is handy.
You can also change the configuration with the set command.
Module Management
To list the modules in ESXi server, you can use the module sub namespace with list command. There are many lines of output not listed here.
To get details about a module, you can use the get command
To load a module, run the following command:
You can also list parameters of a module as follows. There are actually more lines but omitted. It’s also highly possible that there is no line at all because there is no parameter to change for that module.
Userworld Process
To list these processes, you can use the following command. Again, it’s not fully list due to space limit.
To find how many userworld processes running, try the following command:
To get the system workload, run the following command and get the load in 1, 5, and 15 minute period. You will get more from esxtop command anyway.
Security Policy
As usual, you can list all the security policies using the list command. With each policy, you can see its enforcement level.
To change the level of enforcement, use the set command. Other than the enforcing level, I haven’t seen other level and I even tried none and a few others with no luck. The help doesn’t help neither – something for VMware to improve.
Kernel Settings
There are many parameters with which you can tune the ESXi. For a complete list of these parameters, you can use the list command as follows. As you expect, there are so many of them, I just show first two. The name of the setting is self explanatory with the description field.
ESXi Advanced Settings
There are many parameters you can fine tune the ESXi. The following shows the commands you can list them, change them.
Setting Keyboard Configurations
ESXi is like an operating system which can interactive with users. One way of interaction is via keyboard. The esxcli command allows changing the keyboard configuration.
To change the keyboard layout, the following command can be used. It’s not persisted across reboot with the no-persist option.
Getting Uptime of the ESXi server
The first command is not that readable because the unit is microseconds. You can try the second one for days of up time.
Syslog management
You can mark the syslog by adding a unique message in the log. Why is it needed? You can use it to mark start of new period for testing something, so that you can later easily locate the start point.
You can reload the log daemon to apply any new configuration options as follows:
To retrieve syslog configuration, get command can be used:
If you want to export the syslog to a remote syslog server, you can use the set command as follows. You want to make sure the FQDN is resolvable, which may involve the configuration of DNS as described earlier.
To list all the loggers, run the following command. There are many other loggers not listed due to limit of space.
To change a specific logger configuration like the rotation size and how many rotations to keep, you can run the following command. The id must be one in the above list output. The unit for the size is KiB.
To reset a specific value for a logger, run the following command:
Hypervisor File System
The following command shows a quick summary of the file system. You can also drill down to the ramdisk and tardisk with the next two commands.
Retrieving and Setting Hostname and Domains
You can change the default hostname for esxi from the default localhost to more meaningful domain and host name.
When you set the hostname, you can use fqdn option or domain plus host. They are mutually exclusive. I find fqdn is easy and straightforward.
Managing Maintenance Mode
You can place the ESXi into maintenance mode assuming you have evacuated all the virutal machines.
The default timeout for the set command is 60 seconds so the timeout can be omitted in above command.
Power Management
You can either power off or reboot ESXi from the esxcli command. But wait, why isn’t there a power on command? You will need a IPMI interface for that.
Both reboot and power off operation requires the same parameters.
Configuring SNMP
There are a few parameters you can configure on ESXi. The following help shows these parameters with some descriptions.
Retrieving UUID
The following command retrieves the UUID for the host.
~ # esxcli system uuid get
50cdca40-8c57-2ee2-af75-8c89a5d2b40f
Reading and Setting System Time
ESXi keeps its own system clock. To read the time and set the time, you can use the following commands:
Getting ESXi Version and Build Number
The following simple command shows the version and build number of the ESXi product.
Change the ESXi welcome message
The following command changes the welcome message users see upon login. It’s not necessary to change it, but if your IT has important policy to information users upon login it’s a good way to do it.
Managing Virtual Machines
Most virtual machine related operations can be done with vim-cmd command. The esxcli command touches lower part of the virtual machine. For the hypervisor, each running virtual machine acts like a process.
You can use the following command to list all the running virtual machine. Instead of process id, each VM is identified by its world ID.
You can kill a virtual machine by its world ID as follows:
There are other options as listed below, for example, soft type, hard type, and the ultimate force type. With the force option, you can almost stop any virtual machine.
I couldn’t refrain from commenting. Perfectly written!
A worth to read post. Thanks Steve. Plan to buy a book you authored.
Thanks a lot for your support Lawrence!
-Steve
Very nice initiative. Bookmarked!
Thank you
Thanks for your comment. Glad you like it.
Steve
We have two esxi hosts with V6.0.0 and 5 VMs are hosted on each ESXi hosts. Due to Business require we reboot all VMs every night. Adapter type these VMs have is E1000 type. Every day when VMs are rebooted couple of VMs will lose network connectivity. When we Select NIC and uncheck Device status and check back will resolve the issue. Decision made not to switch over to Vxnnet 3. We had history had lots of network issues when we did switch over VXMnet3. Is there is option what is the esxcli command syntax to uncheck the device NIC status and recheck it back if the Ping is failed.
Thank you for your help
Hi Shivaram,
You can use the vim-cmd command to find out the device status easily. Check out the other blogs:
There doesn’t seem to be a way to modify the NIC as you wanted. You can probably hack it by disconnect and connect the device with device.connection command there. Good luck!
Steve
Thanks for this tutorial full of useful commands.
Is there an esxcli command that provides information if an ESXi OS was booted in UEFI mode or in BIOS/Legacy model ?
Thanks Steve, haven’t looked at the UEFI before. If you find the answer, please feel to share here.
-Steve
|
http://www.doublecloud.org/2015/05/vmware-esxi-esxcli-command-a-quick-tutorial/
|
CC-MAIN-2018-09
|
refinedweb
| 5,034
| 64.41
|
This HTML version of is provided for convenience, but it
is not the best format for the book. In particular, some of the
symbols are not rendered correctly.
You might prefer to read
the PDF version, or
you can buy a hardcopy from
Amazon.
One of the best ways to describe a variable is to report the values
that appear in the dataset and how many times each value appears.
This description is called the distribution of the variable.
The most common representation of a distribution is a histogram,
which is a graph that shows the frequency of each value. In
this context, “frequency” means the number of times the value
appears.
In Python, an efficient way to compute frequencies is with a
dictionary. Given a sequence of values, t:
hist = {}
for x in t:
hist[x] = hist.get(x, 0) + 1
The result is a dictionary that maps from values to frequencies.
Alternatively, you could use the Counter class defined in the
collections module:
from collections import Counter
counter = Counter(t)
The result is a Counter object, which is a subclass of
dictionary.
Another option is to use the pandas method value_counts, which
we saw in the previous chapter. But for this book I created a class,
Hist, that represents histograms and provides the methods
that operate on them.
value_counts
The Hist constructor can take a sequence, dictionary, pandas
Series, or another Hist. You can instantiate a Hist object like this:
>>> import thinkstats2
>>> hist = thinkstats2.Hist([1, 2, 2, 3, 5])
>>> hist
Hist({1: 1, 2: 2, 3: 1, 5: 1})
Hist objects provide Freq, which takes a value and
returns its frequency:
>>> hist.Freq(2)
2
The bracket operator does the same thing:
>>> hist[2]
2
If you look up a value that has never appeared, the frequency is 0.
>>> hist.Freq(4)
0
Values returns an unsorted list of the values in the Hist:
>>> hist.Values()
[1, 5, 3, 2]
To loop through the values in order, you can use the built-in function
sorted:
for val in sorted(hist.Values()):
print(val, hist.Freq(val))
Or you can use Items to iterate through
value-frequency pairs:
for val, freq in hist.Items():
print(val, freq)
Figure 2.1: Histogram of the pound part of birth weight.
For this book I wrote a module called thinkplot.py that provides
functions for plotting Hists and other objects defined in thinkstats2.py. It is based on pyplot, which is part of the
matplotlib package. See Section 0.2 for information
about installing matplotlib.
To plot hist with thinkplot, try this:
>>> import thinkplot
>>> thinkplot.Hist(hist)
>>> thinkplot.Show(xlabel='value', ylabel='frequency')
You can read the documentation for thinkplot at.
Figure 2.2: Histogram of the ounce part of birth weight.
Now let’s get back to the data from the NSFG. The code in this
chapter is in first.py.
For information about downloading and
working with this code, see Section 0.2.
When you start working with a new dataset, I suggest you explore
the variables you are planning to use one at a time, and a good
way to start is by looking at histograms.
In Section 1.6 we transformed agepreg
from centiyears to years, and combined birthwgt_lb and
birthwgt_oz into a single quantity, totalwgt_lb.
In this section I use these variables to demonstrate some
features of histograms.
birthwgt_lb
birthwgt_oz
totalwgt_lb
Figure 2.3: Histogram of mother’s age at end of pregnancy.
I’ll start by reading the data and selecting records for live
births:
preg = nsfg.ReadFemPreg()
live = preg[preg.outcome == 1]
The expression in brackets is a boolean Series that
selects rows from the DataFrame and returns a new DataFrame.
Next I generate and plot the histogram of
birthwgt_lb for live births.
hist = thinkstats2.Hist(live.birthwgt_lb, label='birthwgt_lb')
thinkplot.Hist(hist)
thinkplot.Show(xlabel='pounds', ylabel='frequency')
When the argument passed to Hist is a pandas Series, any
nan values are dropped. label is a string that appears
in the legend when the Hist is plotted.
Figure 2.4: Histogram of pregnancy length in weeks.
Figure 2.1 shows the result. The most common
value, called the mode, is 7 pounds. The distribution is
approximately bell-shaped, which is the shape of the normal
distribution, also called a Gaussian distribution. But unlike a
true normal distribution, this distribution is asymmetric; it has
a tail that extends farther to the left than to the right.
Figure 2.2 shows the histogram of
birthwgt_oz, which is the ounces part of birth weight. In
theory we expect this distribution to be uniform; that is, all
values should have the same frequency. In fact, 0 is more common than
the other values, and 1 and 15 are less common, probably because
respondents round off birth weights that are close to an integer
value.
Figure 2.3 shows the histogram of agepreg,
the mother’s age at the end of pregnancy. The mode is 21 years. The
distribution is very roughly bell-shaped, but in this case the tail
extends farther to the right than left; most mothers are in
their 20s, fewer in their 30s.
agepreg
Figure 2.4 shows the histogram of
prglngth, the length of the pregnancy in weeks. By far the
most common value is 39 weeks. The left tail is longer than the
right; early babies are common, but pregnancies seldom go past 43
weeks, and doctors often intervene if they do.
prglngth
Looking at histograms, it is easy to identify the most common
values and the shape of the distribution, but rare values are
not always visible.
Before going on, it is a good idea to check for outliers, which are extreme values that might be errors in
measurement and recording, or might be accurate reports of rare
events.
Hist provides methods Largest and Smallest, which take
an integer n and return the n largest or smallest
values from the histogram:
for weeks, freq in hist.Smallest(10):
print(weeks, freq)
In the list of pregnancy lengths for live births, the 10 lowest values
are [0, 4, 9, 13, 17, 18, 19, 20, 21, 22]. Values below 10 weeks
are certainly errors; the most likely explanation is that the outcome
was not coded correctly. Values higher than 30 weeks are probably
legitimate. Between 10 and 30 weeks, it is hard to be sure; some
values are probably errors, but some represent premature babies.
On the other end of the range, the highest values are:
weeks count
43 148
44 46
45 10
46 1
47 1
48 7
50 2
Most doctors recommend induced labor if a pregnancy exceeds 42 weeks,
so some of the longer values are surprising. In particular, 50 weeks
seems medically unlikely.
The best way to handle outliers depends on “domain knowledge”;
that is, information about where the data come from and what they
mean. And it depends on what analysis you are planning to perform.
In this example, the motivating question is whether first babies
tend to be early (or late). When people ask this question, they are
usually interested in full-term pregnancies, so for this analysis
I will focus on pregnancies longer than 27 weeks.
Now we can compare the distribution of pregnancy lengths for first
babies and others. I divided the DataFrame of live births using
birthord, and computed their histograms:
firsts = live[live.birthord == 1]
others = live[live.birthord != 1]
first_hist = thinkstats2.Hist(firsts.prglngth)
other_hist = thinkstats2.Hist(others.prglngth)
Then I plotted their histograms on the same axis:
width = 0.45
thinkplot.PrePlot(2)
thinkplot.Hist(first_hist, align='right', width=width)
thinkplot.Hist(other_hist, align='left', width=width)
thinkplot.Show(xlabel='weeks', ylabel='frequency',
xlim=[27, 46])
thinkplot.PrePlot takes the number of histograms
we are planning to plot; it uses this information to choose
an appropriate collection of colors.
Figure 2.5: Histogram of pregnancy lengths.
thinkplot.Hist normally uses align=’center’ so that
each bar is centered over its value. For this figure, I use
align=’right’ and align=’left’ to place
corresponding bars on either side of the value.
With width=0.45, the total width of the two bars is 0.9,
leaving some space between each pair.
Finally, I adjust the axis to show only data between 27 and 46 weeks.
Figure 2.5 shows the result.
Histograms are useful because they make the most frequent values
immediately apparent. But they are not the best choice for comparing
two distributions. In this example, there are fewer “first babies”
than “others,” so some of the apparent differences in the histograms
are due to sample sizes. In the next chapter we address this problem
using probability mass functions.
A histogram is a complete description of the distribution of a sample;
that is, given a histogram, we could reconstruct the values in the
sample (although not their order).
If the details of the distribution are important, it might be
necessary to present a histogram. But often we want to
summarize the distribution with a few descriptive statistics.
Some of the characteristics we might want to report are:
Statistics designed to answer these questions are called summary
statistics. By far the most common summary statistic is the mean, which is meant to describe the central tendency of the
distribution.
If you have a sample of n values, xi, the mean, x, is
the sum of the values divided by the number of values; in other words
The words “mean” and “average” are sometimes used interchangeably,
but I make this distinction:
Sometimes the mean is a good description of a set of values. For
example, apples are all pretty much the same size (at least the ones
sold in supermarkets). So if I buy 6 apples and the total weight is 3
pounds, it would be a reasonable summary to say they are about a half
pound each.
But pumpkins are more diverse. Suppose I grow several varieties in my
garden, and one day I harvest three decorative pumpkins that are 1
pound each, two pie pumpkins that are 3 pounds each, and one Atlantic
Giant® pumpkin that weighs 591 pounds. The mean of this
sample is 100 pounds, but if I told you “The average pumpkin in my
garden is 100 pounds,” that would be misleading. In this example,
there is no meaningful average because there is no typical pumpkin.
If there is no single number that summarizes pumpkin weights,
we can do a little better with two numbers: mean and variance.
Variance is a summary statistic intended to describe the variability
or spread of a distribution. The variance of a set of values is
The term xi − x is called the “deviation from the mean,” so
variance is the mean squared deviation. The square root of variance,
S, is the standard deviation.
If you have prior experience, you might have seen a formula for
variance with n−1 in the denominator, rather than n. This
statistic is used to estimate the variance in a population using a
sample. We will come back to this in Chapter 8.
Pandas data structures provides methods to compute mean, variance and
standard deviation:
mean = live.prglngth.mean()
var = live.prglngth.var()
std = live.prglngth.std()
For all live births, the mean pregnancy length is 38.6 weeks, the
standard deviation is 2.7 weeks, which means we should expect
deviations of 2-3 weeks to be common.
Variance of pregnancy length is 7.3, which is hard to interpret,
especially since the units are weeks2, or “square weeks.”
Variance is useful in some calculations, but it is not
a good summary statistic.
An effect size is a summary statistic intended to describe (wait
for it) the size of an effect. For example, to describe the
difference between two groups, one obvious choice is the difference in
the means.
Mean pregnancy length for first babies is 38.601; for
other babies it is 38.523. The difference is 0.078 weeks, which works
out to 13 hours. As a fraction of the typical pregnancy length, this
difference is about 0.2%.
If we assume this estimate is accurate, such a difference
would have no practical consequences. In fact, without
observing a large number of pregnancies, it is unlikely that anyone
would notice this difference at all.
Another way to convey the size of the effect is to compare the
difference between groups to the variability within groups.
Cohen’s d is a statistic intended to do that; it is defined
where x_1 and x_2 are the means of the groups and
s is the “pooled standard deviation”. Here’s the Python
code that computes Cohen’s d:
def CohenEffectSize(group1, group2):
diff = group1.mean() - group2.mean()
var1 = group1.var()
var2 = group2.var()
n1, n2 = len(group1), len(group2)
pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2)
d = diff / math.sqrt(pooled_var)
return d
In this example, the difference in means is 0.029 standard deviations,
which is small. To put that in perspective, the difference in
height between men and women is about 1.7 standard deviations (see).
We have seen several ways to describe the difference in pregnancy
length (if there is one) between first babies and others. How should
we report these results?
The answer depends on who is asking the question. A scientist might
be interested in any (real) effect, no matter how small. A doctor
might only care about effects that are clinically significant;
that is, differences that affect treatment decisions. A pregnant
woman might be interested in results that are relevant to her, like
the probability of delivering early or late.
How you report results also depends on your goals. If you are trying
to demonstrate the importance of an effect, you might choose summary
statistics that emphasize differences. If you are trying to reassure
a patient, you might choose statistics that put the differences in
context.
Of course your decisions should also be guided by professional ethics.
It’s ok to be persuasive; you should design statistical reports
and visualizations that tell a story clearly. But you should also do
your best to make your reports honest, and to acknowledge uncertainty
and limitations.
Which summary statistics would you use if you wanted to get a story
on the evening news? Which ones would you use if you wanted to
reassure an anxious patient?
Finally, imagine that you are Cecil Adams, author of The Straight
Dope (), and your job is to answer the
question, “Do first babies arrive late?” Write a paragraph that
uses the results in this chapter to answer the question clearly,
precisely, and honestly.
chap02ex.ipynb
A solution to this exercise is in chap02soln.ipynb
chap02soln.ipynb
In the repository you downloaded, you should find a file named
chap02ex.py; you can use this file as a starting place
for the following exercises.
My solution is in chap02soln.py.
chap02ex.py
chap02soln.py
As a more challenging exercise, write a function called AllModes
that returns a list of value-frequency pairs in descending order of
frequency.
Think Bayes
Think Python
Think Stats
Think Complexity
|
http://greenteapress.com/thinkstats2/html/thinkstats2003.html
|
CC-MAIN-2017-47
|
refinedweb
| 2,517
| 65.32
|
Top iPhone 3G Downloads Sites Tips and Guide
Top iPhone 3G Downloads Sites Tips and Guide
The iPhone 3G is a cool smartphone... iPhone softwares and apps- sites that allow downloading of copyrighted iPhone
Submitting Web site to search engine
Web Sites
Once your web site is running, the next job for you... to the search
engines, the search engine crawls will visit your site and will index your
pages to the search engine index. Once your web site appears
index
Top 10 Emerging Social Networking Sites
networking sites, but to your amazement this rather regional site which is China's big... networking site that does not believe in shouting out loud like other sites. The most...Top 10 Emerging Social Networking Sites
It is no longer a literary expression
Free Web Site Hosting Services
and personal web sites including CGI and FrontPage Support.
We offer free space and tools for you to build your own web site. You get:150 MB... Search Engines To Promote Your Site E-Mail (Coming Soon) And much more...
http
Other Important Travel Sites of Agra
Other Important Travel sites in Agra:
From Mughal monuments to ancient... for the Taj Mahal and other sites such as magnificent Agra Fort and near by Fatehpur... not just as a religious site but also in terms of history. It is dedicated
Web Site promotion services at roseindia.net
Web site services
will help you get listed in major search engines and directory of the
world. Our own site traffic comes from the major search engines and
directory. We hand submits the web sites url manually
Designing your web sites
registering the domain your
next task is to design good web site for you. To
design your web site you should have some knowledge of HTML and designing tools
like.... You can design good web sites using Front Page.
Designing a good
How to Market Your Ecommerce Site
: There are a lot of sites these days who allow you to place your ad on their site at free...How to Market Your Ecommerce Site
So, did you just set up your e-commerce site? Great! The next step to get it all rolling smoothly is to market your e
How to Upload Site Online
.
Uploading site can be done in many ways, but the most popular is FTP. After hosting... sites (e.g. user Server) using the FTP (File Transfer Protocol) system
Adobe Flex Component Index
a rich look in the web site as well as with the help of various validators we can put validations on different field so easily and effectively.
Index of Flex
What is Index?
What is Index? What is Index
Submit your site to 100 top search engines
where you can
submit your site. Top search engines are Yahoo, Google, MSN, AOL, Dmoz, etc.,
but there are also many more high quality sites to list your
index of javaprogram
index of javaprogram what is the step of learning java. i am not asking syllabus am i am asking the step of program to teach a pesonal student.
To learn java, please visit the following link:
Java Tutorial
Choosing the Right Sites for Social Media Marketing
Choosing the Right Sites for Social Media Marketing
Right at the mention...
of content is permitted on the site and what type works. For example, blog
hosting sites permit many types of content but it might not be beneficial to a
person who
WEB SITE
WEB SITE can any one plzz give me some suggestions that i can implement in my site..(Some latest technology)
like theme selection in orkut
like forgot password feature..
or any more features
Sorry but its
Random Redirector
to select a site randomly from the list of sites you
have entered. Note that the selection of the site will be randomly.
To make such a servlet firstly... the sites
which you want to select randomly and the other class Random which
Search index
Welcome to Free search engine secrets: webmaster's guide to search engine
upon this examination search engines
index and rank the site. Although some...
Welcome To Webmaster's Guide
This site is dedicated
to Web related services. Here you can find tools and suggestions to promote your sites
Shared Web Hosting
web
sites are hosted on same physical server. It is the cheapest and easiest way to
get a web site up and running. All the sites shares the server
resources..., but it is not sufficient for Web sites getting tremendous traffic. If
your web
alter table create index mysql
alter table create index mysql Hi,
What is the query for altering table and adding index on a table field?
Thanks
Hi,
Query is:
ALTER TABLE account ADD INDEX (accounttype);
Thanks
index - Java Beginners
Explain about Cross site scripting?
Explain about Cross site scripting? Explain about Cross site scripting
Web Site Goals - Goal of Web Designing
Web Site Goals - Goal of Web Designing
What are the prime features necessary... and the client.
What is Custom Web Design?
Custom web site is little bit... in building Custom web sites.
What steps goes on in the process of web
Java arraylist index() Function
Java arrayList has index for each added element. This index starts from 0.
arrayList values can be retrieved by the get(index) method.
Example of Java Arraylist Index() Function
import
file uploads to my web site
file uploads to my web site How can I allow file uploads to my web site
Free Web Hosting - Why Its not good Idea
Web Hosting is
not good Idea for hosting your web sites, specially when you are looking for
getting high traffic on your web site. Also its very important to decide when
you are looking for big popularization of your web site in near
Mysql Date Index
Mysql Date Index
Mysql Date Index is used to create a index on specified table. Indexes...
combination of columns in a database table. An Index is a database structure
Hibernate Tools
Hibernate Tools:
Hibernate Tool is yet another cool...
Update Site
In this section we will show you how to download and install
Hibernate tools from Hibernate Tools Update Site.
including index in java regular expression
including index in java regular expression Hi,
I am using java regular expression to merge using underscore consecutive capatalized words e.g., "New York" (after merging "New_York") or words that has accented characters
Shopping Cart Index Page
Dynamic Website Designing
Dynamic Website Designing
The Dynamic sites differ from the static in terms of content and design. In dynamic sites, the content live in the database... registration, Site Search, Online Chat etc.
Contact to our designer to know about
Blocking a web site using java program
Blocking a web site using java program How to block a url typed in browser using java program
Web Hosting
Web Hosting Index
Web Hosting is a type of web service in which the host... sites of their clients. Web Hosting is the fundamental requirements for uploading and continuous running the site on the internet.
What we are accessing
Foreach loop with negative index in velocity
Foreach loop with negative index
in velocity
... with negative index in velocity.
The method used in this example... have
used foreach loop with negative index..
Hibernate Tools Update Site
Hibernate Tools Update Site
Hibernate Tools Update Site
In this section we... Site. The anytime you can user Hibernate
Tools Update Manager from your eclipse
Pointing last index of the Matcher
Pointing last index of the Matcher
... and also indicate the last index of the matcher using expression.For this we... will arrive.":- Declaring text as String in which
last index of word Tim
Index Out of Bound Exception
Index Out of Bound Exception
Index Out of Bound Exception are the Unchecked Exception... the
compilation of a program. Index Out of Bound Exception Occurs when
JavaScript array index of
JavaScript array index of
... to easy to understand
JavaScript array index of. We are using JavaScript...)index of( ) - This return the position of the value that is hold
Information Website Template
Information Websites
We provide high quality Information site development... and the layout of our information site websites are
designed in such a way... representation of the contents of the website.
Information Sites
Information
Spring Constructor arg index
Constructor Arguments Index
In this example you will see how inject the arguments into your bean
according to the constructor argument index...;
<constructor-arg index="0" value
Front Page Web Hosting
space to host these sites.
FrontPage is a cool tool which makes creating web sites... for the development of web site using HTML and DHTML. Front Page is used..., which are needed to publish a site with FrontPage.
Write a byte into byte buffer at given index.
Write a byte into byte buffer at given index.
In this tutorial, we...; index.
ByteBuffer API:
The java.nio.ByteBuffer class extends... ByteBuffer
putChar(int index, byte b)
The putChar(..) method write
Corporate Web Design Services
, portal, or sites.
The corporate sites differ from the general informative site... corporate site that ensures the site owner to enhance the huge traffic
PHP PDO Index
sqlite2
This is the index page of PDO, following pages will illustrate
Best iPhone Accessories and Attachments
' iPhone sites before. So what's new here? Well for starters, here you will find only... for a dual iPhone dock that accommodates your iPhone and iPod as well.
Cool iPhone... iPhone accessories its well worth to note that the iPhone is itself one cool
Open Source Bloggers Software written in Java
PHP Web Hosting
for the development of dynamic web sites. Its available for almost all... for
hosting any dynamic web site developed in PHP.
Free PHP Web Hosting are simple... companies places
some kind of adds on the web site.
Professional Web Design Services For You Web Site
Professional Web Design Services For You Web Site
Seeking the services of a professional... design of the web site
PHP Basics Tutorial Index
Write a long value at given index into long buffer.
Write a long value at given index into long buffer.
In this tutorial, we will see how to write a long value at given index
into long buffer....
abstract LongBuffer
put(int index, long value)
The put(..) method
OGNL Index
, this first character
at 0 index is extracted from the resulting array
What Security Functions Do You Need for Ecommerce?
Sites
SSL stands for severe sockets layer. This gives the site protection over... for an e-commerce site to be as secure as possible not only for the security... to trust the ecommerce site in that their information is not going to be stolen
How to get specific index value from short buffer.
How to get specific index value from short buffer.
In this tutorial, we will discuss how to get specific index value from
short buffer.
ShortBuffer...;
abstract short
get( int index)
The get() method reads is short
|
http://www.roseindia.net/tutorialhelp/comment/81342
|
CC-MAIN-2014-41
|
refinedweb
| 1,820
| 64.3
|
I know how to make actions happen based on if the mouse is being clicked or released and if the mouse is in motion or being clicked and in motion (all using freeglut).
But google has me very stressed with options on which way I should use to determine what object is being clicked.
Can someone please show me the simplest way you can think of to determine what object is being clicked so I can move that object independently using the glut functions?
As we are working with 2D objects, an object is pointed at if the position of the mouse is inside the object. This notion of being inside differs for different geometric shapes.
For a rectangle width upper left corner
c and
width,
height the the function could look like:
bool isInsideRectangle(double x, double y) { // The mouse is inside if the coordinates are 'inside' all walls return (x > c.x && y > c.y && x < c.x + width && y < c.y + height); }
For a circle with center
c and radius
r, it could look like this:
bool isInsideCircle(double x, double y) { // The mouse is inside if the distance to the center of the circle // is less than the radius return std::sqrt((x - c.x)*(x - c.x) + (y - c.y)*(y - c.y)) < r; }
For another shape you would have to figure out another function for how to calculate if a mouse position is inside or not, however in many cases you can simplify it to a bounding rectangle or sphere.
Regardless of whether you're working with 2D or 3D by far the simplest solution is to assign each pickable object a unique colour, which isn't normally used at all. Then for every click event you render (to the back buffer) the same scene with the unique colour applied to each object. By disabling lighting etc. the problem then becomes one of looking at the pixel color under the mouse and using a lookup table to see which object was clicked.
Even in 16 bit colour depth that still gets you 2^16 unique pickable objects and in reality that's rare in modern application to have less than 2^24.
|
http://www.dlxedu.com/askdetail/3/8c9e69a25477a7ec8a98b785ea6b32eb.html
|
CC-MAIN-2018-22
|
refinedweb
| 368
| 67.59
|
In school, we about
virtual functions in C++, and just how they're resolved (or found, or matched up, I'm not sure exactly what the terminology is -- we are not studying in British) at execution time rather than compile time. The teacher also told us that compile-time resolution is a lot faster than execution-time (also it will make sense for this to become so). However, a fast experiment indicate otherwise. I have built this small program:
#include <iostream> #include <limits.h> using namespace std; class A { public: void f() { // do nothing } }; class B: public A { public: void f() { // do nothing } }; int main() { unsigned int i; A *a = new B; for (i=0; i < UINT_MAX; i++) a->f(); return 0; }
I put together this program above and referred to it as
normal. Then, I modified
A to appear such as this:
class A { public: virtual void f() { // do nothing } };
Put together and referred to it as
virtual. Listed here are my results:
[felix@the-machine C]$ time ./normal real 0m25.834s user 0m25.742s sys 0m0.000s [felix@the-machine C]$ time ./virtual real 0m24.630s user 0m24.472s sys 0m0.003s [felix@the-machine C]$ time ./normal real 0m25.860s user 0m25.735s sys 0m0.007s [felix@the-machine C]$ time ./virtual real 0m24.514s user 0m24.475s sys 0m0.000s [felix@the-machine C]$ time ./normal real 0m26.022s user 0m25.795s sys 0m0.013s [felix@the-machine C]$ time ./virtual real 0m24.503s user 0m24.468s sys 0m0.000s
There appears to become a steady ~1 second difference in support of the virtual version. Why?
Relevant or otherwise: dual-core pentium @ 2.80Ghz, no extra programs running between two tests. Archlinux with gcc 4.5.. Producing normally, like:
$ g++ test.cpp -o normal
Also,
-Wall does not goes any alerts, either.
Edit: I've separated my program into
A.cpp,
B.cpp and
main.cpp. Also, I made the
f() (both
A::f() and
B::f()) function really do something (
x = 0 - x where
x is really a
public
int person in
A, initialized with one in
A::A()). Put together this into six versions, listed here are my benefits:
[felix@the-machine poo]$ time ./normal-unoptimized real 0m31.172s user 0m30.621s sys 0m0.033s [felix@the-machine poo]$ time ./normal-O2 real 0m2.417s user 0m2.363s sys 0m0.007s [felix@the-machine poo]$ time ./normal-O3 real 0m2.495s user 0m2.447s sys 0m0.000s [felix@the-machine poo]$ time ./virtual-unoptimized real 0m32.386s user 0m32.111s sys 0m0.010s [felix@the-machine poo]$ time ./virtual-O2 real 0m26.875s user 0m26.668s sys 0m0.003s [felix@the-machine poo]$ time ./virtual-O3 real 0m26.905s user 0m26.645s sys 0m0.017s
Unoptimized continues to be 1 second faster when virtual, that we find a little peculiar. But it was a pleasant experiment and want to thank everyone for the solutions!
When the vtable is incorporated in the cache, the performance distinction between virtual and non-virtual functions that really make a move is extremely small. It's definitely not something you need to normally be worried about when developing software using C++. So that as others have stated, benchmarking unoptimised code in C++ is pointless.
Profiling unoptimised code is virtually meaningless. Use
-O2 to make a significant result. Using
-O3 may lead to even faster code, but it might not produce a realistic outcome unless of course you compile
A::f and
B::f individually to
main (i.e., in separate compilation models).
In line with the feedback, possibly even
-O2 is simply too aggressive. The Two ms outcome is since the compiler optimized the loop away entirely. Direct calls aren't that fast actually, it must be tough to observe any significant difference. Slowly move the implementations of
f right into a separate compilation unit to come on amounts. Define the classes inside a .h, but define
A::f and
B::f in their own individual .cc file.
|
http://codeblow.com/questions/exactly-why-is-execution-time-method-resolution-faster-than-compile-time-resolution/
|
CC-MAIN-2017-43
|
refinedweb
| 669
| 63.96
|
Introduction
Welcome to Ariadne!
This guide will introduce you to the basic concepts behind creating GraphQL APIs, and show how Ariadne helps you to implement them with just a little Python code.
At the end of this page you will have your own simple GraphQL API accessible through the browser, implementing a single field that returns a "Hello" message along with a client's user agent.
Make sure that you've installed Ariadne using
pip install ariadne, and that you have your favorite code editor open and ready.
Defining schemaDefining schema
First, we will describe what data can be obtained from our API.
In Ariadne this is achieved by defining Python strings with content written in Schema Definition Language (SDL), a special language for declaring GraphQL schemas.
We will start by defining the special type
Query that GraphQL services use as an entry point for all reading operations. Next, we will specify a single field, named
hello, and define that it will return a value of type
String, and that it will never return
null.
Using the SDL, our
Query type definition will look like this:
type_defs = """ type Query { hello: String! } """
The
type Query { } block declares the type,
hello is the field definition,
String is the return value type, and the exclamation mark following it means that the returned value will never be
null.
Validating schemaValidating schema
Ariadne provides the
gql utility function to validate schema. It that takes a single argument, a GraphQL string, like the following example:
from ariadne import gql type_defs = gql(""" type Query { hello String! } """)
gql validates the schema and raises a descriptive
GraphQLSyntaxError, if there is an issue, or returns the original unmodified string if it is correct.
If we try to run the above code now, we will get an error pointing to incorrect syntax within our
type_defs declaration:
graphql.error.syntax_error.GraphQLSyntaxError: Syntax Error: Expected :, found Name GraphQL request (3:19) type Query { hello String! ^ }
Using
gql is optional; however, without it, the above error would occur during your server's initialization and point to somewhere inside Ariadne's GraphQL initialization logic, making tracking down the error tricky if your API is large and spread across many modules.
First resolverFirst resolver
The resolvers are functions mediating between API consumers and the application's business logic. In Ariadne every GraphQL type has fields, and every field has a resolver function that takes care of returning the value that the client has requested.
We want our API to greet clients with a "Hello (user agent)!" string. This means that the
hello field has to have a resolver that somehow finds the client's user agent, and returns a greeting message from it.
At its simplest, a resolver is a function that returns a value:
def resolve_hello(*_): return "Hello..." # What's next?
The above code is perfectly valid, with a minimal resolver meeting the requirements of our schema. It takes any arguments, does nothing with them and returns a blank greeting string.
Real-world resolvers are rarely that simple: they usually read data from some source such as a database, process inputs, or resolve value in the context of a parent object. How should our basic resolver look to resolve a client's user agent?
In Ariadne every field resolver is called with at least two arguments: the query's parent object, and the query's execution
info that usually contains a
context attribute. The
context is GraphQL's way of passing additional information from the application to its query resolvers.
In the above example, note the
*_argument in the resolver's method signature. The underscore is a convention used in many languages (including Python) to indicate a variable that will not be used. The asterisk prefix is Python syntax that informs the method it should expect a variable-length argument list. In effect, the above example is throwing away any arguments passed to the resolver. We've used that here, to simplify the example so that you can focus on its purpose.
The default GraphQL server implementation provided by Ariadne defines
info.context as a Python
dict containing a single key named
request
containing a request object. We can use this in our resolver:
def resolve_hello(_, info): request = info.context["request"] user_agent = request.headers.get("user-agent", "guest") return "Hello, %s!" % user_agent
Notice that we are discarding the first argument in our resolver. This is because
resolve_hello is a special type of resolver: it belongs to a field defined on a root type (
Query), and such fields, by default, have no parent that could be passed to their resolvers. This type of resolver is called a root resolver.
Now we need to set our resolver on the
hello field of type
Query. To do this, we will use the
QueryType class that sets resolver functions to the
Query type in the schema. First, we will update our imports:
from ariadne import QueryType, gql
Next, we will instantiate the
QueryType and set our function as resolver for
hello field using it's field decorator:
# Create QueryType instance for Query type defined in our schema... query = QueryType() # ...and assign our resolver function to its "hello" field. def resolve_hello(_, info): request = info.context["request"] user_agent = request.headers.get("user-agent", "guest") return "Hello, %s!" % user_agent
Making executable schemaMaking executable schema
Before we can run our server, we need to combine our textual representation of the API's shape with the resolvers we've defined above into what is called an "executable schema". Ariadne provides a function that does this for you:
from ariadne import make_executable_schema
You pass it your type definitions and resolvers that you want to use:
schema = make_executable_schema(type_defs, query)
In Ariadne the process of adding the Python logic to GraphQL schema is called binding to schema, and special types that can be passed to
make_executable_schema's second argument are called bindables.
QueryType (introduced earlier) is one of many bindables provided by Ariadne that developers will use when creating their GraphQL APIs.
In our first API we passed only a single bindable to the
make_executable_schema, but most of your future APIs will likely pass a list of bindables instead, for example:
make_executable_schema(type_defs, [query, user, mutations, fallback_resolvers])
It's possible to call
make_executable_schemawithout bindables, but doing so will result in your API handling very limited number of use cases: browsing schema types and, if you've defined root resolver, accessing root type's fields.
Testing the APITesting the API
Now we have everything we need to finish our API, with the only missing piece being the HTTP server that would receive the HTTP requests, execute GraphQL queries and return responses.
Use an ASGI server like uvicorn, daphne, or hypercorn to serve your application:
pip install uvicorn
Create a
ariadne.asgi.GraphQL instance for your schema:
from ariadne.asgi import GraphQL app = GraphQL(schema, debug=True)
Run your script with
uvicorn myscript:app (remember to replace
myscript.py with the name of your file!). If all is well, you will see a message telling you that the simple GraphQL server is running at. Open this link in your web browser.
You will see the GraphQL Playground, the open source API explorer for GraphQL APIs. You can enter a
{ hello } query on the left, press the big, bright "run" button, and see the result on the right:
Your first GraphQL API build with Ariadne is now complete. Congratulations!
Completed codeCompleted code
For reference here is complete code of the API from this guide:
from ariadne import QueryType, gql, make_executable_schema from ariadne.asgi import GraphQL type_defs = gql(""" type Query { hello: String! } """) # Create type instance for Query type defined in our schema... query = QueryType() # ...and assign our resolver function to its "hello" field. def resolve_hello(_, info): request = info.context["request"] user_agent = request.headers.get("user-agent", "guest") return "Hello, %s!" % user_agent schema = make_executable_schema(type_defs, query) app = GraphQL(schema, debug=True)
|
https://ariadnegraphql.org/docs/0.12.0/intro.html
|
CC-MAIN-2021-17
|
refinedweb
| 1,314
| 61.26
|
Giant Steps is a John Coltrane song infamous for being difficult to improvise over, because it has massive key changes (hence “giant steps”) that are hard for musicians to keep track of.
It didn’t seem to give Coltrane too much trouble though:
The “circle of fifths” is the sort of landscape in which these steps (giant or otherwise) can be taken. Say we start with the note C. Within the key of C major, if we move up five notes we get to a G (C, D, E, F, G). This G is the fifth of C. Likewise, if we move up five notes from G we get to D (G, A, B, C, D). Continuing this we eventually walk around all 12 notes in the scale by fifths (because \[ 5n \: \mathrm{mod} \: 12 \] cycles through all possibilities).
Here’s what happens if you do a step-by-step walk around the circle of fifths. (The chords sound like they’re alternating between low and high pitch because I moved around the chords to fit within a smaller range of pitches.) Every one of these samples is going to repeat once, so you’ll be able to hear it repeat at the midway point.
If you take three of these fifth-sized steps at a time, you end up using only four chords out of the twelve:
Here’s four steps around, which of course means three chords. It has a different rhythmic feel because it’s based on counting to three instead of four, but the chord changes are still similar. This is also the set of chord changes most similar to what’s in Coltrane’s song.
Here’s what happens if you walk at five steps around: you end up with chords right next to each other on the scale.
Because 12 is divisible by 1, 2, 3, 4, and 6, and because 5 is just 6-1 (so the same as going 1 step in the other direction after jumping half the circle), any integer value of jumps around the circle leads to a repetitive pattern. Any linear recurrence mod 12 gives us a human-recognizable pattern of chords.
We could try to fix this by jumping into the world of the pseudorandom. Instead of just adding \[ n \] at every step, let’s use an LFSR or a Mersenne Twister to generate more-random (but still not totally random) sequences. They should sound more strange to the human ear, providing a bizarre musical experience while still being grounded in recognizable patterns.
Would this work? Well…not exactly. We can generate a random sequence of chord changes using something like the code below. Because the cycle here is so long (Python’s
random module has a period of \[ 2^{19937-1} \]), if we’re going to hear any sequence as “random”, this should be it.
import random def note(n): """Converts position on circle of fifths to a note name""" notes = ['C', 'G', 'D', 'A', 'E', 'B', 'Gb', 'Db', 'Ab', 'Eb', 'Bb', 'F'] return notes[n - 1] for i in range(12): print(note(random.randint(1, 12)))
Here’s a sample “song” made using the above code.
Do you hear this as a random sequence? My guess is no. Human brains are very good at detecting patterns even in truly random data, and the scope of what’s allowed here (only 12 options, all major chords, repeats once) just doesn’t allow for something that sounds all that “random”. We may have giant steps, but it’s still hard to go for a random walk.
|
https://vitez.me/giant-steps
|
CC-MAIN-2020-16
|
refinedweb
| 600
| 76.25
|
In Part 1 of this mini-series we created the layout for a calculator. In this part, we’ll take a look at the event handlers required to make the buttons works.
When the user clicks a button an event is raised. You can register a method to “handle” that event – that is you can set up your program so that when the user clicks your button a specific method is invoked.
There are a number of ways to register a method to an event. One
of the easiest ways to do this is to click on the Button in the Designer and then to click on the event you’re interested in in the Properties window. To see the events, you need to click the events button in the upper right hand corner, as shown in the figure.
The events window lists all the events that might be associated with your Button. Click on the Clear button and then double-click in the Click event handler box. Blend creates a new Event for you named by appending the event (Click) to the Buttton’s name with an underbar (Clear_Click). Blend also creates the stub for the event handler code, and moves you to the code file (MainPage.xaml.cs).
Switch back to MainPage.xaml and click on Button01. . This time rather than double clicking in the event handler for the click button, type in the name “NumberButton_Click” Do this for all ten number buttons; they will all share the same event handler.
Use the default name for all the other buttons.
Click the menu choice File -> SaveAll. Right click on the solution file and choose Edit In Visual Studio
Before we go on to examine writing the code associated with this application, let’s open MainPage.xaml. Visual Studio defaults to a split view, with the design view on the left and the Xaml view on the right. Notice that the design is identical to what you saw in Expression Blend.
Let’s focus on the Xaml for a moment. Every property that you set interactively in Blend is now shown in the Xaml. For example, notice that the first entry in the StackPanel is a Border that contains a TextBlock, which is just what we hoped,
<StackPanel x: <Border Margin="15,0,30,0" Background="White"> <TextBlock TextWrapping="Wrap" Text="0" FontSize="48" Foreground="Black" HorizontalAlignment="Right" Margin="0"/> </Border>
Take a look at the WrapPanel and double check that all the Buttons have the right names and correct Click event handlers,
<toolkit:WrapPanel <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: <Button x: </toolkit:WrapPanel>
Event Handlers
With the layout and UI design complete, it is time to write the logic of the calculator. Turn to MainPage.xaml.cs and notice that there are event handlers that were created and “stubbed-out” by Blend, for example,
private void Clear_Click( object sender, System.Windows.RoutedEventArgs e) { // TODO: Add event handler implementation here. }
Your job, no surprise, is to fill in the event handler implementations. Before we dive into the specific event handlers, we need a few class members. We’ll begin by defining an enumeration named OperatorTypes,
public enum OperatorTypes { None, Addition, Subtraction, Multiplication, Division }
We’ll create a private member variable of type OperatorTypes and initialize its value to None
OperatorTypes operatorType = OperatorTypes.None;
We also need a flag to tell us if we’re dealing with a new value or we’re just adding numerals to an existing value.
Binding and Dependency Properites
We want to bind the number we display to a property and for that we have to register a dependency property. Here’s the syntax, see the linked to article for more on Dependency Properties.
public double DisplayNumber { get { return (double)GetValue(DisplayNumberProperty); } set { SetValue(DisplayNumberProperty, value); } } public static readonly DependencyProperty DisplayNumberProperty = DependencyProperty.Register( "DisplayNumber", typeof(double), typeof(MainPage), null);
We’re ready to return to the Xaml and add the binding to the TextBlock,
<TextBlock TextWrapping="Wrap" Text="0" FontSize="48" Foreground="Black" HorizontalAlignment="Right" Margin="0"/> Replace Text=”0” with the following,
Notice that we say in the Text property that the Binding is to the DisplayNumber. What is the DisplayNumber? It is a property but of what object? This is answered by setting the DataContext back in the code behind,
protected override void OnNavigatedTo( System.Windows.Navigation.NavigationEventArgs e ) { DataContext = this; DisplayNumber = 0; }
You can now press F5 to test the databinding. Next up, Handling Number Click events.
|
http://jesseliberty.com/2011/08/19/building-a-windows-phone-app-from-scratchpart-2/
|
CC-MAIN-2021-10
|
refinedweb
| 770
| 52.29
|
Patent application title: WORKSPACE SYSTEM AND METHOD FOR MONITORING INFORMATION EVENTS
Inventors:
Michael Appelbaum (Washington, DC, US)
Jeffrey Garvett (Washington, DC, US)
Christopher Bradley (Sterling, VA, US)
Karl Ginter (Beltsville, MD, US)
Michael Bartman (Potomac, MD, US)
IPC8 Class: AG06F944FI
USPC Class:
719318
Class name: Electrical computers and digital processing systems: interprogram communication or interprocess communication (ipc) event handling or event notification
Publication date: 2011-07-07
Patent application number: 20110167433
Abstract:
A system and method for monitoring information events partitions sets of
information and processing steps into one or more workspaces. The
workspaces include sharable portable specifications for implementing
event monitoring by a plurality of users or computer systems. Workspaces
may be bindable computing resources to establish controls between the
computing resources and the workspaces.
Claims:
1. A method for monitoring information events comprising: partitioning
sets of information and processing steps into one or more workspaces;
wherein said workspaces comprise sharable specifications for one or more
objects used to implement event processing flows.
2. The method of claim 1 wherein said workspaces comprise workspace items including shareable and portable specifications for one or more of PPSs, rule specifications, event queues, event objects, rulebooks, templates, wizards, publish/subscribe relationships, authorization credentials and computing resources.
3. The method of claim 1 wherein said workspaces items include entities used to define, implement control and monitor event processing.
4. The method of claim 1, further comprising provisioning each of said workspace items to one or more computer resources.
5. The method of claim 1 further comprising binding instances of said one or more workspaces to one or more computing resources to establish controls between said resources and said workspaces.
6. The method of claim 2, further comprising binding instances of said one or more workspaces to one or more of said workspace items to establish controls between said workspace items and said workspaces.
7. The method of claim 1 comprising partitioning said sets of information into said workspaces in accordance with access rights assigned to said workspaces.
8. The method of claim 1 further comprising: sharing one or more of said workspaces between one or more users.
9. The method of claim 1 further comprising: sharing one or more of said workspaces between one or more roles.
10. The method of claim 1 further comprising: sharing one or more of said workspace items between one or more of said workspaces.
11. The method of claim 1 further comprising associating one or more of said workspaces with one or more rule specifications.
12. The method of claim 1 further comprising associating one or more of said workspaces with one or more rulebooks, wherein said associating makes the contents of said one or more rulebooks available to an associated workspace.
13. A system for controlling information events comprising: one or more workspaces including sharable specifications for one or more workspace items used to implement event processing flows.
14. The system of claim 13 wherein said workspace items include shareable and portable specifications for one or more of PPSs, rule specifications, event queues, event objects, rulebooks, templates, wizards, publish/subscribe relationships, authorization credentials and computing resources.
15. The system of claim 13 wherein said workspaces items include entities used to define, implement control and monitor event processing.
16. The system of claim 13 wherein each of said workspaces defines a corresponding information and event processing configuration.
17. The system of claim 16 wherein said corresponding information and event processing configuration includes identifications of binding between a plurality of said workspaces.
18. The system of claim 16 wherein said corresponding information and event processing configuration includes identification of bindings between workspace items and distributed computer resources.
19. A system for monitoring information events comprising one or more workspaces including sharable specifications for one or more workspace items used to implement event processing flows; and means for partitioning sets of information and processing steps into one or more of said workspaces.
20. The system of claim 19 further comprising: means for binding one or more of said workspaces with entities selected from the group consisting of users, roles, workspace items and computer resources.
21. The system of claim 19 further comprising: means for separating the operations the processing steps occurring within a first workspace and the processing occurring with a second workspace such that processing steps occurring in the first workspace do not effect the processing steps occurring in the second workspace.
22. The system of claim 19 further comprising: means for enforcing the separation between the processing occurring within a first workspace and the processing occurring with a second workspace.
Description:
CROSS REFERENCE TO RELATED U.S. PATENT APPLICATION
[0001] The present application claims priority under 55 U.S.C. §119(e) to provisional U.S. Patent Application Ser. No. 60/924,801 (Docket No. 54041-005001) filed May 31, 2007, which is incorporated herein by reference in its entirety and for all purposes.
, Agent Logic, Inc.
BACKGROUND
[0003] This invention relates to systems and techniques for monitoring information events from various data sources, and further relates to systems and techniques for specifying shared event sources, constructing distributed event processing systems, and techniques and systems for managing event processing rules and specifications.
[0004] Business and government analysts are experiencing an information onslaught. The volume of information is increasing in internal systems, in publicly accessible information sources, and across the Internet. While this information flow is valuable, it is becoming increasingly difficult to sort and filter, to determine patterns and trends in the information flow, and to present the resulting materials in a form usable by one or more end users. Operational imperatives such as situational awareness, cost containment, risk mitigation, and growth require timely detection of, and response to, key business events. Organizations must be able to effectively respond to opportunities and threats represented by the information continually occurring across disparate sources of information that relate to their missions.
[0005] Information flows can be considered as a sequence of individual events, each of which must be collected, processed, evaluated, as part of an information processing system. Individual events, such as a new order, a 911 call, a customer service request, a geographic position update, or an updated investigative report represent the foundation of new and changing data throughout an organization that must be continually monitored to identify opportunities and threats. Previous systems have employed news feeds, databases, and search engines to receive, process, and index data as it becomes available. However, cataloging information into databases and search engines takes time and computing resources. Meanwhile, the user must periodically query the data system for new results that match their search criteria. One manager estimated that his analysts spend the first 1-2 hours of each workday checking existing databases and search engines for new information and manually further processing the information into actionable events. Complex events, that include related individual events, often go undetected due to information overload or improper filtering and assessment. Automated systems that automatically correlate events, particularly events that are separated by a time interval of days or weeks, often fall back on storing information in a database, manually or automatically querying the database for known event patterns, and then re-analyzing the information retrieved. These processes are highly inefficient and are not scalable.
[0006] Raw information becomes actionable events through a defined series of information processes and/or processing steps. Existing systems provide for static processing systems using IT-defined, process-driven workflows that often add time to the processing. Mechanisms for access to raw and processed information, the processing steps and workflow definitions, and resulting assessment and actions have historically been neglected. Extant information monitoring systems often rely on monolithic architectures over continuously connected networks in order to process information. These systems suffer from significant drawbacks. First, these systems are often statically configured, requiring users with appropriate permissions to pre-compute the amount of processing power and processing resources that must be made available for each step of system's processing. Thus, these types of systems do not scale well as information loads, resources, staffing, or processing requirements change. Changing of information and data sources, information flow rates, available processing power, the number and locations of staffing seats (including workstation configurations, access, and provisioning with data sources, processing recipes and the like) are all aspects of scaling. Some information resources exhibit "bursty" volume characteristics, in which the information volume often increases by orders of magnitude during times of interest. Similarly, staffing and resources applied to management of events often dramatically increase during times of interest. Often, time is not available to make IT-centric workflow, system provisioning, and/or changes, much less to provide for the testing and rollout of new IT-based workflows and processing recipes. Thus, the management of the information, resources, and staff during times of substantive change is a significant challenge in today's environment. Additionally, the organization and provisioning of resources is often statically performed by external (e.g. IT) staff, and requires significant effort to shift resources and services to use alternate processing resources, workflows, and processing recipes. For mission critical applications, disaster and outage management paradigms further require that large monolithic systems be replicated at great cost.
[0007] Furthermore, present system architectures lack effective ways to share and control data about information sources, data management processes and recipes, and information filtering techniques/processing recipes. For example, Microsoft Windows products provide an interface for ODBC drivers in which an information database connection can be loaded onto a user's machine, but which provides no other controls than the connection string. Furthermore, ODBC technologies support only local and network connected databases, and are not useful for newer distribution mechanisms such as web-based information sources and RSS feeds. For example, RSS feed readers store URLs and authorization information to access data feeds, but do not provide continued processing capabilities. Other products, such as web search engines or bookmark collections, provide stored URLs to web-based information services, but do not provide an easy mechanism to manage authorization credentials associated with each URL so that several users can access the information without extensive or repetitive configuration efforts, nor do they permit definition of additional process steps required to obtain and pre-process content referenced by the URLs. Other types of information sources have similar issues, and do not provide a robust, sharable solution for handling these aspects of information processing.
[0008] Additionally, extant systems and methods do not provide mechanisms for successful information processing and filtering recipes and techniques to be captured in a transportable manner and subsequently used within a distributed environment. Raw information is obtained, pre-processed, and assessed as part of a process that transforms the information into an actionable event. The mechanisms for obtaining the information, pre-processing it, and assessing the information are traditionally hard coded into information processing systems, and are thus not easily distributable or sharable between users, sites in a distributed system, or different systems or instances of a system. Current systems generally rely on individuals to obtain, process, and assess information feeds independently. This results in significant duplication of processing efforts at system, machine and personnel levels.
[0009] Specifically, the workflows, rules, and processing recipes for processing information are generally hard coded into present day information system, or are configured by specialized IT staff. The information systems often impose restrictions on how, where, and by whom the rules can be changed, and are not structured to support reuse of rules and processing recipes, nor the sharing of user developed rules, recipes, and workflows.
[0010] Finally, current information processing systems do not provide for isolation of multiple instances of workflows, rules, and recipes from each other. Extant systems provide large, monolithic processing mechanisms that focus on processing speed and not information separation. Information separation is important in some businesses. Furthermore, systems that do not provide robust information separation can exhibit unexpected information processing behaviors because of interactions between two or more processing rules. The information "side effects" cause system instability, unreliable processing, and sometimes work stoppage.
[0011] What is needed is a system that permits for the management of user-defined resources, processing recipes, and subsequent event management workflows within a scalable, distributed framework for connecting to and receiving information from a plurality of resources, processing this information, and producing actionable events which are effective to provide real-time event detection, analysis, and response in highly complex and secure environments.
SUMMARY
[0012] The present invention provides a robust solution for event correlation and monitoring applicable in a variety of fields. In particular, the present invention provides a variety of user-configurable methods for interfacing with data sources, recognizing and selecting events, and providing actions based upon those events.
[0013] The details of one or more embodiments of the invention are set forth in the accompanying drawings and the description below. Other features and advantages of the invention will be apparent from the description and drawings, and from the claims.
DESCRIPTION OF DRAWINGS
[0014] FIG. 1 shows a logical representation of the components involved in an input stage of the present invention.
[0015] FIG. 2 shows a process flow diagram illustrating event processing steps in accordance with an illustrative embodiment of the present invention.
[0016] FIG. 3 shows a schematic representation of a Portable Producer Specification (PPS) in accordance with one embodiment of the present invention.
[0017] FIG. 4 shows an exemplary Rule Specification (RS) object within the scope of the present invention.
[0018] FIG. 5 illustrates a logical representation of a publish/subscribe action between workspaces.
[0019] FIG. 6 shows a logical representation of the architecture in accordance with one embodiment of the present invention.
[0020] FIG. 7 shows a schematic representation of the architecture in accordance with one embodiment of the present invention.
[0021] FIG. 8 shows a schematic representation of the architecture in a distributed configuration in accordance with one embodiment of the present invention.
[0022] FIG. 9 is a process flowchart depicting a first exemplary use of an enterprise-wide event management system.
[0023] Like reference symbols in the various drawings indicate like items.
DETAILED DESCRIPTION
1 Overview
[0024] A distributed information and processing system and architecture ("the system") is described that processes information across disparate information sources, such as data streams, sensors, communications systems, legacy systems, databases, and flat files, produces and processes events based upon information from these information sources, and initiates specified actions as a result of this event processing. The system creates "event objects" as information flows through one or more information systems, either by polling underlying data systems or by receiving specific notifications. Event objects are describe at least one aspect of a detected event and optionally describe meta-data associated with the event, such as the time at which it was detected, the source of the information used, the version of the software used to process the detection, etc.
[0025] When the system detects an event, or a combination of events, that match conditions specified in a rule, it executes one or more corresponding responses (actions). Events that do not match any rule do not result in responses being executed. This mechanism removes unwanted, insignificant, or not yet significant events from further immediate processing, permitting available computing resources to be focused on those events that are of interest, and the execution of responses to them. Events, or information derived from them, can be retained by the system when one or more rules specify this, and be used in the future evaluation of rules, thus providing the system with a "memory" and the ability to detect combinations of events over time. Events which are not significant when first detected later can be found significant in combination with other events that occur at a later time. For example, one failed attempt at providing a valid password for access to a user account on a computer is not significant, but a large number of failed attempts over a short time span might be.
[0026] Many types of event responses can be initiated using a variety of mechanisms well understood by those skilled in the art, such as email instant message alerts, Web Service and business process activation, event enrichment responses to collect additional information about the event, and browser alerts through such mechanisms as Agent Logic's (Herndon, Va.) Real-Time Browser®, and instant GIS/Link Analysis tool updates. Responses, such as process initiation and alerts, can be either triggered in real time, or processed as a group at specific points in time.
[0027] An aspect of some embodiments of the present invention is the ability to generate events based on information obtained from commonly defined information and data sources, the processing required to determine the relevance of piece of information and/or data to one or more specified event or set of events, and initiate responses. A further aspect is to make access to these information sources, the processing steps required, and the actions to take in response to the information and/or data processing available to many users of the system without involving IT personnel. In some embodiments both individual and complex events across many different systems are simultaneously detected and responded to. As shown in FIG. 1, a plurality of information sources (1100, 1110, 1120, & 1130) can be input through the use of a plurality of Connector/Protocol Adapters (1140, 1150, 1160, & 1170) that incorporate necessary protocol knowledge to deal with each type of information source as well as an ability to convert the information obtained from each information source into a format understood by the system's producer services. The said converted information is passed to a producer service (1180), that uses rules, pre-processing specifications and/or scripts obtained from a Portable Producer Specification (PPS) (1190) to evaluate the said converted information and to generate event objects from it as specified by the said rules, pre-processing specifications and/or scripts and place said event objects into appropriate event queues (1200, 1210 & 1220) as determined by rules, pre-processing specifications, scripts or other materials incorporated into the PPS. Event objects in event queues are further processed by other aspects of the system as described below. Multiple producer services, and other applications, that are part of the system, running within a single instance of embodiments of the present invention can be managed separately so that any number of systems and users can leverage event-processing capabilities for a variety of isolated applications, all of which are running concurrently.
[0028] One advantage of the enterprise-wide event management system and architecture described herein is that it provides for real-time event detection, analysis, and response in highly complex and secure environments. The flexible many-to-many event processing flow mechanisms support the partitioning of information and processing by security domain, workload, user, information source, event queue, priority, department, computing resources or other parameter or parameters. Partitioning is achieved through mechanisms such as "workspaces", providing access and usage controls on all system objects, and by restrictions on the use of computing resources. Computing resources comprise data processing hardware, such as CPUs, memory, communication means and data storage devices, and/or permission to make use of these, which are useful for execution of event processing flows. Each enterprise-wide event management system is configurable to enforce any desired level of information segregation, so both users and information can be logically and physically separated in order to ensure processing integrity. Unlike other systems of this type, the described architecture provides for rapid deployment and scaling of each component, distribution of processing while maintaining data and processing partitioning, and for the organic growth of rules and rules sets without required intervention by IT staff.
[0029] As shown in FIG. 2, the exemplary system provides for shared, and portable, complex, user-specified, rule-based calculations and formulas for the processing of information and events. A sequence of event processing steps (2001, 2002, & 2003), effective to produce a desired outcome from event processing, is known herein as an "event processing flow" (2000). Event processing steps (2001, 2002, & 2003) are a combination of rules, processes, event definitions and responses effective to receive information (2005, 2006, 2007, & 2008), process said information, and produce one or more event objects (2020, 2021, 2022, 2023, 2030, 2031, 2032 & 2055) and/or responses (actions) (2050, 2051, & 2052) as a result of said processing. The specific components of the event processing flow (2000) (e.g. Portable Producer Specifications (PPSs) (2015 & 2016), producer services (2010 & 2011), event queues (2025, 2026, & 2027), analytic services (2035 & 2036), rule specifications (RSs) (2040 & 2041), responder processes (2045 & 2046), etc.) effective to define (and subsequently process) a complete aspect of a distributed event processing flow (2000), such as the implementation of a specific instance of an event processing step (2001, 2002, or 2003), are known herein as "event processing nodes". Event processing nodes can be located on a single computing system, or distributed across any number of computing systems, consistent with computing resource restrictions configured into the system to maintain desired partitioning of information and processing. Computing system are typically computer systems of common manufacture, such as servers, desktops, mainframes, embedded systems, as well as mobile computing devices such as laptops and cell phones. Specifically, and without limitation, computing systems can include single and multi-processor computers, as well as multi-core processor equipped computers. Computing systems can similarly be equipped with any of the peripherals and communications technologies used in current-day computers.
[0030] The system provides for the definition, use, sharing and transporting of information source definitions, known as Portable Producer Specifications (PPSs). These comprise information such as procedures and specifications for procedures necessary to access and use various information sources, such as web pages, RSS feeds, and databases, as well as procedures for pre-processing the information obtained from said sources into event objects as used by the system, and placing said event objects into appropriate event queues. PPSs are described in more detail below.
[0031] Each defined PPS used in the system can be specified by rule specifications (RSs) created or used by each user. Furthermore, each user can create such additional PPSs as they require, using templates and wizards (for novice users), or by directly creating PPSs through command or other user interface mechanisms as will be understood by those having skill in the art.
[0032] Rules define the relationships between events (as represented by event objects) and responses. Each user can create such rules as they deem appropriate using templates and wizards (for novice users), by directly writing rules in a rules language, or by commands or other user interface mechanisms as will be apparent to those with skill in the art. Templates are partially defined rules within which the user is required to complete one or more aspects of the rule before use. A wizard is a software application that guides a user through coding a rule, or completing a template. Templates can also be used for more complex structures, such as defined processing flows.
[0033] The system provides for the definition, use, sharing and transporting of rule specifications (RSs). An RS is an object containing a definition for a single rule and all parameters associated with the rule. The parameters associated with the rule are implementation dependent, but can include such things as a rule ID, access restrictions for the rule, identification of the rule's author, etc.
[0034] A collection of PPSs, related event queue descriptions, and RSs that is sufficient to perform at least one event-processing step, when combined with appropriate services, such as producer or analytic services, is referred to as a "recipe". A recipe defines information sources, the event queues that event objects generated from these information sources are placed into, and the rules that operate on the said event objects to generate the responses specified by the rules.
1.1 Portable Producer Specifications
[0035] FIG. 3 shows an exemplary Portable Producer Specification (PPS) object within the scope of the present invention. A PPS is an object that can be provided as a data file, database entry, directory entry, or in another machine-readable format that can be used by a producer service to configure its interaction with a data source. PPSs can be shared between users, workspaces, or systems or exported and transported between users, workspaces, systems or instances of the invention and can optionally be included in RuleBooks to simplify sharing and transporting sets of PPSs. The PPS (3100) includes one or more elements, including data source information (3110), optional access credentials (3120), optional rights specifications (3130), and optional pre-processing rules (3140). These elements can be optionally cryptographically protected (3190) for integrity (e.g. hash/digital signature) and/or privacy (e.g. encryption). A PPS can be encoded using any representation-appropriate encoding scheme, such as rows in a database table, as ASCII tag-value text in a properties file, or as an XML document.
[0036] Data source information (3110) includes one or more information elements that describe or inform the user, or producer service, about the data source, including name and description, source data type, contact information for an assistance provider (e.g. a help desk or system manager), account numbers, owning user, group or system, and related materials. Data source information (3110) also can include elements that form an association between a producer service and the system, including a unique identifier or other ID of the producer service, authorization credentials required to use the information source, or other security and configuration indicia that can be used by the system to properly configure and authenticate the use of the information source, the producer service, and the system. The specification of the precise information elements included in this group of elements is implementation dependant.
[0037] Access credentials (3120) includes information elements that provide machine-readable information that can be used by a producer service to gain access to the information source. Elements within this section can include a database access string, a URI, and/or a predefined query to define the information source location and/or mechanisms required to access the information source. If not encoded within the database access string or URI, the access credentials (3120) can also include the method or protocol to be used to access the information service, such as specification of a connector/protocol adapter to use with the particular information source. Additionally, the access credentials (3120) can contain authentication and authorization materials, such as user id, user name, password, digital certificate, or other indicia of authority to receive information from the information source. Other components can be added to the access credential section on a producer service by producer service basis.
[0038] Rights components (3130) is an optional specification that can include specifications of rights or tags to attach to information received from the information source. Alternatively, rights components (3130) can include a rights specification, such as a rights specification defined using a rights specification language such as XrML.
[0039] Pre-processing rules (3140) are an optional set of components that provide rules for pre-processing information obtained from an information source, such as an RSS feed or email, for example, prior to passing the information to an analytics section, such as extracting and formatting information into the format required by an event specification, or the addition of meta-data, such as the time of collection, the source the information was collected from, the ID or software version of the producer service, or other information about the collected information or the mechanism used to collect it. In some embodiments, the pre-processing rules can include the actual rule specification itself, while in other embodiments, the pre-processing rules can comprise a reference to one or more rules specifications stored elsewhere. Pre-processing rules specifications can also comprise specification of the event queue, or event queues, that are available to receive events generated as a result of pre-processing the source information, and what criteria are used to assign events to particular event queues. Pre-processing rules specifications can optionally comprise script or procedure information that permits arbitrary processing as a part of event processing.
[0040] PPSs can optionally be encrypted for privacy or to enforce security partitioning, or as a form of digital signature to certify origin.
[0041] One aspect of the invention is that service definitions are both portable and sharable. Sharable service definitions support the sharing of service definitions for producer, analytics, and responders as RSs are shared. Portable service definitions permit service definitions to be moved between instances of the present invention, and for an appropriate service to be instantiated on the new instance using the original service definition. The term portable as used throughout the present specification generally means transportable, but may also be used to describe objects, systems, data structures or other entities that are shareable without necessarily being transportable. An advantage of using PPS's is that PPS's can be shared between users of an instance of a system of the present invention, can be shared between disparate instances of the present invention, and can even be made available on other systems, such as storefronts and within application provisioning systems.
[0042] Another advantage of using PPS's is that PPS's provide a business a means to control access to information sources, while at the same time, maintaining the confidentially of the information and data source authentication materials. Coupled with controls over access and use, the arrangement of using PPS's permits control over access to materials at the same time facilitating sharing of common resources and the management of common accesses.
[0043] One benefit of having sharable and portable PPSs is that they ease the burden of each individual user's being required to define their own information sources, provide and manage personal authentication to these information and data sources, and to define and manage the pre-processing of the information from these data sources to a form useful to the system. Furthermore, exported PPSs permit this information to be provided to several disconnected or intermittently connected systems that can function as providers in a distributed network of systems. In some exemplary embodiments, PPSs can be created and provided as a business service. Such services can be provided as a primary business activity, such as by consultants or as pre-packaged products, or as an incidental business activity, such as a news or other information service providing PPSs relating to the use of their news feeds.
1.2 Rule Specifications
[0044] FIG. 8 shows an exemplary Rule Specification (RS) object within the scope of the present invention. An RS is a data structure that can be provided as a data file, database entry, directory entry, or in another machine-readable format that can be used to describe a rule and associated information. RSs can be shared between users, workspaces, or systems or exported and transported between users, workspaces, systems or instances of the invention and can optionally be included in RuleBooks to simplify sharing and transporting RSs. The RS (4200) includes two or more elements, including rule description information (4210), a rule definition (4220), optional rights specifications (4230), and optional access credentials (4240). These elements can be optionally cryptographically protected (4290) for integrity (e.g. hash/digital signature) and/or privacy (e.g. encryption). An RS can be encoded using any representation-appropriate encoding scheme, such as rows in a database table, as ASCII tag-value text in a properties file, or as an XML document.
[0045] Rule description information (4210) comprises one or more information elements that describe or inform the user, or services, about the RS, including name and description, owning user, group or system, and related materials. Rule description information (4210) also can include elements that form an association between an RS and the system, including a unique identifier or other ID of the RS. The specification of the precise information elements included in this group of elements is implementation dependant.
[0046] The rule definition (4220) comprises the information describing the rule itself, as well as associated information, such as event source information (e.g. event queue names or IDs), response information and other items required for the actual evaluation of the rule and execution of any actions required by the evaluation of the rule.
[0047] Rights Specifications (4230) comprise information specifying_authorization credentials required of the rule to make use of the event queues, computing resources, etc., or other security and configuration indicia that can be used by the system to properly configure, authenticate and implement the use of the rule.
[0048] Access credentials (4240) comprise information elements that provide machine-readable information that can be used by the system to validate authentication and authorization materials, such as user ID, user name, password, digital certificate, or other indicia of authority to access, or make use of the RS. The specification of the precise information elements included in this group of elements is implementation dependant. Alternatively, rights credentials (4240) can include a rights specification, such as a rights specification defined using a rights specification language such as XrML.
[0049] One aspect of the invention is that the RSs are both transportable and sharable. Sharable RSs support the sharing of rule definitions for producer, analytics, and responders. Transportable RSs permit rule definitions to be moved between instances of the present invention.
[0050] One benefit of having sharable and transportable RSs is that they ease the burden of each individual user being required to define their own rules. Furthermore, transportable RSs permit rules to be provided to several disconnected or intermittently connected systems that can function as part of a distributed network of systems. In some exemplary embodiments, transportable RSs can be created and provided as a business service. Such services can be provided as a primary business activity, such as by consultants or as pre-packaged products, or as an incidental business activity, such as a news or other information services providing RSs relating to the use of their news feeds.
1.3 RuleBooks
[0051] One aspect of the present invention is that the various embodiments provide extensible analytics RuleBooks for user-based creation and sharing and/or transporting of event processing rules and recipes. The system supports any number of RuleBooks.
[0052] A RuleBook is a portable container object comprising zero or more rulebook items. The RuleBook is typically stored as a single object with a unique user-defined name. The benefit is that a user can share or export a set of objects as a single operation, and users of the objects can transport and import, or subscribe to, the set of objects as a set, rather than having to work with each rulebook item individually.
[0053] A RuleBook can be stored in an instance of a database, a local storage location, in a distributed directory service, such as LDAP, or by other means as determined to be useful by those having skill in the art.
[0054] RuleBooks are thus collections of objects used by the system, and are defined as portable objects comprising one or more RSs, PPSs, recipes, template specification, wizards, access control lists, watch lists, event specification, process definition, and/or other objects relevant to the processing of information and event flows. Objects contained within a RuleBook, or capable of being contained within a RuleBook, are referred to as "RuleBook items". A RuleBook can be stored as an external file that comprises at least one definition for a RuleBook item, stored in a database or directory system such as LDAP, or in any other form as determined to be effective by those having skill in the art. A Rulebook Item can be included as part of a Rulebook by direct inclusion (e.g. a copy within the Rulebook),55] Individual RuleBook items (e.g. PPSs, RSs, and recipes), as well as RuleBooks, can be exported and made transportable to other workspaces, systems or instances of the invention. In some exemplary implementations, the RuleBook items, or RuleBooks, can be transported without modification from a first system to a second system. In other exemplary implementations, the RuleBook items, or RuleBooks, are converted in format by exporting, for purposes of transport from a first system, and are converted again, by importing, for use on a second system. The format of the RuleBook items, or RuleBooks, on the second system can be the same as or different from the format used on the first system. The exported format used for transport can be any format recognized and useful by the first and second systems, such as XML, name-value pairs, or other formats well known to those with skill in the art. When transported in this manner, the transported RuleBook items, or RuleBooks, become separate instances of the RuleBook items, or RuleBooks. Such transported entities have their own access restrictions, users and other aspects, limitations and controls and are not affected by changes to the original RuleBook items, or RuleBooks, they were created from, nor do changes to the transported entities result in changes to the original entities they were transported from. Transporting of such entities can be useful for creation of redundant systems, for disaster recovery purposes, for creation of variant instances of a system or part of a system, for research or testing purposes, for creation and provision of RuleBook items, or RuleBooks, as a business service, or for other purposes as will be apparent to those having skill in the art.
[0056] RuleBooks can be made available for workspaces to import or subscribe to, and can thus be shared or transported between one or more workspaces. RuleBook sharing can be accomplished using different physical copies of a RuleBook (export/import), shared from a common location (such as a common file share similar to those provided by NFS or CFIS), or by loading the components contained within a RuleBook into external storage means such as a database, and then sharing the storage means between workspaces (publish/subscribe).
[0057] RuleBooks can be made transportable between users, systems or instances of the invention. When transported in this manner, the transported RuleBooks become separate instances of the original RuleBook. Such transported RuleBooks have their own access restrictions, users and other aspects, limitations and controls and are not affected by changes to the original RuleBooks they were exported from, nor do changes to the transported RuleBooks result in changes to the original RuleBooks they were exported from. Transporting of RuleBooks can be useful for creation of redundant systems for disaster recovery purposes, for creation of variant instances of the system or part of the system for research or testing purposes, for checkpoint or backup purposes, for creation and provision of RuleBooks as a business service, or for other purposes as will be apparent to those having skill in the art.
[0058] Rulebooks can have access controls associated with them, at both the Rulebook and at the Rulebook Item level. Thus, a first user can be granted access only to a first RuleBook, a second user can be granted access to a second RuleBook, and a third user can be granted access to both the first and second RuleBooks. Similarly, a specific item within a Rulebook can be access controlled, with similar outcomes. A default RuleBook is also provided with system-provided analytics features as described below.
[0059] A workspace binds to, shares or prepares a RuleBook for transport as described above, e.g. with the import and export, or publish and subscribe capabilities. Subscribing to a RuleBook, or importing a RuleBook, makes the RuleBook itself accessible to the workspace, but other functions are used to make RuleBook contents available to the workspace, without loading the RuleBook contents into the workspace as if they had been locally defined (i.e. with full access to and control over them). These functions include "mount" and "unmount". Mounting a RuleBook makes the RuleBook contents available to a workspace to the extent permitted by relevant access controls, which can be less than full access to the RuleBook and its contents. For example, a workspace might have access to make use of RSs contained in a RuleBook, but not have sufficient access rights to change the RSs in the RuleBook, or to make use of rule wizards in the RuleBook to create new RSs. Some users of the workspace can have rights that implicitly allow them to use any mounted RuleBook. Mounting a RuleBook to a distributed workspace can cause the RuleBook to be physically distributed to all servers that support the distributed workspace. Unmount removes the availability of a RuleBook from a workspace, without removing the binding of the RuleBook to the workspace. The unmount command will not succeed if aspects of the RuleBook are referenced from components within the workspace.
[0060] The "publish" function for a RuleBook makes a specific RuleBook available to a specific workspace, user or role. In other words, it adds the RuleBook to the workspace, user or role's access list. "Unpublish" removes the availability of the RuleBook from the specified workspace, user or role. In some exemplary implementations of the present invention the ability to publish to all users or roles, or to sets of users or roles, with a single publish operation is supported.
[0061] RuleBooks provide an effective means of sharing or transporting complete and partial RSs and/or recipes between workspaces, users, roles or instances of the system. Thus, if a first user develops a particularly useful recipe for event processing, that user can create a RuleBook that comprises PPSs, event definitions, RSs, namespaces, event queue specification, and any other components required to successfully process events using the recipe. The first user can then make this RuleBook available to a second user to facilitate the second user's processing of events. The election of whether to share the processing recipe using a RuleBook, or by using a workspace that publishes an end result such as a set of event queues or response action effects, is made based upon whether the processing rules should be exposed to the second user. In the instance where the workspace publishes end results, the processing rules are not exposed to the second user. In the shared RuleBook instance, the processing rules can be exposed to the second user, depending on the access rights of the second user with respect to the RuleBook.
1.4 Namespaces
[0062] PPSs, Event objects, RSs, recipes, workspaces, and other components of the system can be named. Each of these components is specified using at least one namespace. Specification of individual components within namespaces is well understood by those skilled in the art. An example of a namespace system that is well known in the art includes that defined for XML-based systems. An XML-based schema for specifying namespaces describes namespaces and is used as follows:
TABLE-US-00001 <root xmlns: <htext:table> <htext:tr> <htext:td>Apples</htext:td> <htext:td>Oranges</htext:td> </htext:tr> </htext:table> <obj:table> <obj:name>Plywood Sheet</obj:name> <obj:width>48</obj:width> <obj:length>96</obj:length> </obj:table> </root>
[0063] In the above example, references to a "table" item would be ambiguous without the use of namespaces to permit specification of which "table" item is being referred to . . . the HTML table or the physical object plywood table. In the system of the present invention, similar ambiguities can occur with respect to PPSs, RSs, event queues, workspaces, and other aspects of the system due to factors such as publish/subscribe relationships, and importation of exported objects, such as RuleBooks. For example, if a first workspace creates an event queue for events related to news items obtained from wire services, named, "current news", then publishes it, and a second workspace creates an event queue for internal company events, also named, "current news", then publishes it, it becomes problematic for a third workspace to subscribe to only one of these two event queues unless namespaces are used to qualify the event queue names. If the event queue published by the first workspace is associated with a namespace bound to the first workspace, and the event queue published by the second workspace is associated with a namespace bound to the second workspace, the third workspace can refer to either event queue in an unambiguous fashion.
[0064] Each workspace is associated with one or more namespaces. A workspace becomes associated with each namespace as the result of binding the workspace with a RuleBook that defines one or more namespaces, by a user action that associates a namespace with the workspace, a user profile that defines one or more namespaces, or from a globally defined profile that defines one or more namespaces. Namespaces are named using globally unique identifiers. Globally unique identifiers are well understood by those with skill in the art.
[0065] Namespaces are used by the system to unambiguously define names and references to the data and processing elements used by the system. When event queues, RuleBooks or other entities are created, they are each associated with a namespace. When these entities are bound to a workspace, such as by a publish/subscribe relationship, the namespace associated with each is retained and used to unambiguously refer to the entity or its attributes. Other entities in the workspace can have names or attributes that are the same as those of the first entity, but due to the different namespaces associated with each entity, there is no ambiguity as to which is being referenced. The system uses namespaces to specify the names and attributes of elements referenced by rules, event objects, and other components of the system.
1.5 Workspaces
[0066] One challenge in developing and deploying user-specified rules, calculations, and formulas for the processing of information events is the logical separation of sets of information and processing based upon function and usage. In some business environments, this is called the compartmentalization of information, and is known herein as "partitioning". Partitioning is supported in the present invention through mechanisms such as "workspaces" and access limitations on objects such as PPSs, RSs, event queues, and RuleBooks.
[0067] One method employed by the present invention for partitioning information is the processing of information and events within a series of "workspaces". A workspace is a sharable and portable specification for one or more PPSs, RSs, event queues, event objects, RuleBooks, templates, wizards, publish/subscribe relationships, authorization credentials, computing resources and/or associated entities used to define, implement, control and monitor event processing flows, and its subsequent implementation through provisioning of each aspect of the workspace to one or more computing resources. Each item that is part of the workspace specification is called a "workspace item". A workspace item can be included as part of a workspace by direct inclusion (e.g. a copy within the workspace),68] Each workspace thus defines a specific information and event processing configuration and implementation comprising of workspace items bound to each other and to disparate computing resources. This permits a workspace to either specify specific resource requirements, or to specify types of resources and to be subsequently provisioned with available resources as necessary.
[0069] A process called "binding" establishes the association of a workspace with specific users or roles, workspace items, and computing resources. A workspace instance is said to be "bound" to one or more specific resource(s), workspace items, and/or computing resources. The binding of the workspace item with a particular resource establishes the controls between the resource and the workspace. An example of a user/action permission binding is generally described herein, however, generalized associative binding techniques are well understood by those skilled in the art. Similarly, provisioning of workspaces is performed using techniques that are well understood by those skilled in the art
[0070] Each workspace participates in specific information partitions based on the access rights assigned. A workspace may be shared between one or more users or roles, and a first workspace can share RuleBooks, PPSs, event queues and other objects with one or more second workspaces. Each association is formed in conjunction with an optional control mechanism that limits the actions or capability of the associated component. For example, a user (or role shared by one or more users) may be associated with a workspace using an access control list that describes the actions the user (or role) may take (and possibly those that they may not take). Authentication and authorization can be performed at the granularity of a workspace, a specific system or server, a cluster of systems or servers, or at the enterprise level. User authentication and authorization materials, including user IDs, role assignments, and the like, may be stored in one or more database(s), registry(ies), or directory(ies), such as an LDAP, flat file(s), or other storage mechanism(s) suitable for storing user authentication and authorization materials. User preference and profile materials can be stored with user authentication or authorization materials. Alternatively, user preference and profile materials may be stored in a different one or more database(s), registry(ies), or directory(ies), such as an LDAP system, flat file(s), or other storage mechanism(s) suitable for storing user preference and profile materials.
[0071] A workspace can be associated with one or more RSs and/or recipes. In some implementations, these RSs and recipes are provided in collected sets as RuleBooks. In other implementations, they are included within the workspace as individual elements. Each association of a first workspace with a specific RuleBook makes the contents of the RuleBook available to that workspace. RSs and recipes can also be provided within a first workspace, whether created by a user of the first workspace or published by a user of a second workspace and subscribed to by a user of the first workspace. Associations can also be made to individual named components within a RuleBook or workspace.
[0072] A workspace can be associated with one or more event and information sources, as specified by one or more PPSs and acquired through use of a producer service. Optionally, direct specification of event and information sources can be used in lieu of using a PPS to specify them. These information sources can be specified within a first workspace, can be published by a second workspace and subscribed to by a first workspace, specified within one or more RuleBooks, or can be provided by a mechanism external to the system. In a distributed system, these event and information sources, as well as the producer services associated with each, can be located on a plurality of computing resources.
[0073] Similarly, one or more bindings may be established between a workspace and a computing resource that indicates the amount, or identities, of computing resources that the workspace may use. For example, a binding may be established between a workspace and a computer that limits the amount of CPU and memory provided by the computer to the workspace. A workspace can be restricted to use of particular computing resources by permitting it to bind only with those computing resources, and allowing no CPU or other resource use on systems the workspace is not permitted to bind to. Such restrictions can be for various purposes, such as information partitioning and maintenance of security, for optimizing distribution of workspace tasks over available computing resources, or for optimizing distribution of workspace tasks and information access to limit communication means bandwidth use.
[0074] Each workspace can be logically isolated from all other workspaces. In other embodiments, one or more aspects of a workspace can be shared with other workspaces. This organization provides advantages when the event and information processing within a first workspace should be hidden from a second workspace. The first workspace can make specific aspects of its processing available to other workspaces without exposing the details of the event and information processing configuration. Publishing can be used to make aspects of a first workspace available to a second workspace. "Publishing" refers to making an object available to a plurality of entities. Objects can be published within an instance of the invention, or published across a plurality of instances of the invention using mechanisms external to the invention (such as LDAP, shared file systems or database servers). Published objects can be access controlled. A workspace makes use of a published object by "subscribing" to it. Subscribing consists of making at least one aspect of a published object available to an entity other than the publishing entity. Both publish and subscribe actions are controlled actions within their respective workspaces. Users must possess special permissions in order to establish publish/subscribe relationships. Publish/subscribe relationships are especially advantageous when implementing event and information processing systems that use common information processing mechanisms or processes.
[0075] A workspace definition, including component bindings, controls such as access control lists, publish/subscribe relationships, rules, and information processing state(s) are typically defined within the components of the system. In some cases, these items are defined within a workspace. In other alternative implementations, one or more of these aspects may be defined and stored external to a workspace (e.g. globally) and be shared between one or more workspaces. A machine-readable workspace definition can be exported from a workspace into a transportable format by using the export capability associated with the workspace. Exporting comprises making at least one object ready for transportation. The complementary operation is referred to as "importing". Importing comprises making at least one transported object ready for use in at least one aspect of at least one instance of the invention. An import capability can be used to read the transportable format and create a workspace that is comprised of the component bindings, controls, publish/subscribe relationships, rules, and information processing states of the original workspace. Import and export are useful for backup and restore purposes, to create duplicate workspaces for workers performing similar duties, and to define a transportable event detection and management system arrangement.
[0076] The import and export actions are controlled actions (e.g. subject to access and configuration controls). One example transportable format is an XML representation of the workspace definition. A limited example, for illustration purposes only, of an XML workspace representation might be:
TABLE-US-00002 <WORKSPACE> <ID>Bob Smith's Workspace</ID> <PPS> <PPS_REF>PPS_Newsfeed</PPS_REF> <PPS_REF>PPS_BlogerSpot</PPS_REF> </PPS> <RULE> <RULE_REF>RULE_Extract_Item_By_Name</RULE_REF> </RULE> <EVENT_QUEUES> <QUEUE>OurCompany</QUEUE> </EVENT_QUEUES> <AUTH>Analyst_Group</AUTH> <OWNER>Bob Smith</OWNER> <ACCESS> <RIGHT>Analyst_Group?ADMIN</RIGHT> <RIGHT>All?READ</RIGHT> </ACCESS> </WORKSPACE>
[0077] The exported workspace definition can be stored in a RuleBook, as described below.
[0078] FIG. 5 illustrates an example of a publish/subscribe model. In this model a first information processing mechanism embodied in a first workspace (5500) that provides a common pre-processing or filtering function on "raw" information. The first workspace publishes event objects to a published event queue (5600) that require additional analysis. One or more second workspaces subscribe to the said published event queue and process the said event objects according to the RSs they are bound or subscribed to. The information sources and processing techniques within the first workspace are thus hidden from subscribers to the published event queue, with only the published event queue and the event objects it contains, and their respective namespaces, being exposed to the subscribers. Two additional information processes can be implemented as a second and third workspace (5710 and 5720) respectively, each of which subscribes to the published event queue of the first workspace. The subscription to the published event queue and the controls over the subscription are shown by the subscribe arrows joining the workspaces and the event queue. Just as the second and third workspaces have no access to the information sources and processing activities of the first workspace, the first workspace has no access to the RSs and processing activities of the second and third workspaces. This is one example of how information, and processing of information, can be partitioned within the system.
1.6 Distribution of Processing
[0079] FIG. 6 shows a logical instance of an embodiment of a workspace 6000 of the present invention, which includes an input section 6010, an analytics section, 6020 and a responder section 6030. Information flows from information sources, both internal and external to the input section 6010, where it is processed, expanded and passed on to the analytics section 6020. The input section's 6010 role is to gather input from a plurality of data sources, generate additional information (e.g. the information source ID, time of collection, version of the collection software, etc.), and aggregate this information together as one or more completed event objects for further processing. Once information has been aggregated into an event object, it is passed to an analytics section 6020 for further processing by placing it into an event queue. The analytics section 6020 provides a framework in which one or more analytic rules may be applied to event objects obtained from event queues. Each event object is processed by one or more rules. The results of the rule processing can include creating additional event objects, taking specific actions, or simply saving the event for possible later use. Specific actions resulting from rules acting on event objects, including external notifications, system updates, generation of additional event objects, etc., are managed by one or more responder sections 6030. The responder section(s) 6030 provide the external interfaces and program logic required to effect each configured action.
[0080] Each of input, analytic, and responder sections may be deployed on a single computer, or may be distributed across a plurality of computers. Illustratively, each input section instance 6012, 6014, analytics section instance 6022, 6024 and responder section instance 6032, 6034 is in messaging communication with other sections. The configuration of the components within each section and the communication means used to communicate between sections are defined using configuration information for the system, each section, and each component (respectively). The distribution of particular services, workspaces, RuleBooks, event queues, and other aspects of the system can be restricted by system configuration such that specific instances of these, or those bearing particular access specifications or other characteristics, are placed only on a particular computer or computers. This partitioning of data and the processing of that data permits required levels of isolation to be maintained for security purposes, tracking purposes, or for other reasons, such as load balancing or system redundancy, while still permitting distribution of the system across a plurality of computing resources. Due in part to the implementation of the system as a set of cooperating services using shared resources to exchange information, the distribution of aspects of the system across available computing resources can change over time as computing resource availability changes so as to optimize use of available computing resources and/or maintain partitioning of data and processing.
[0081] FIG. 7 is a schematic view of a logical instance of one embodiment of the present invention, which includes an input section (7110), an analytics section (7120), and a responder section (7130) interfaced using communications means (7140; 7150). The input section (7110) further includes one or more producer services (7112a, 7112b, 7112c), which are operable to interface with at least one information source using communications means (not shown), and one or more portable producer specifications (PPSs) (7114a, 7114b, 7114c). These PPSs can be used to define the access and initial pre-processing/enrichment of one or more information sources. The input section (7110) further includes an optional input section log (7118) that records the actions of the producer services. One or more instances of input sections can be supported by various exemplary implementations of the present invention. Each input section (7110) is connected to one or more analytics sections (7120) in order to support further processing of the information.
[0082] The analytics section (7120) receives information from one or more input section instances in the form of "event objects." Thus, input and analytics sections are associated in a many-to-many relationship using one or more communications means. In some exemplary implementations the associations are made using a messaging mechanism such as a messaging technology such as MQ from IBM Corporation of Armonk, N.Y., or the Java Messaging System (JMS) from Sun Microsystems of Santa Clara, Calif. In other exemplary implementations, other technologies such as sockets, streams, and inter-process control messaging also can be used. In still other exemplary implementations, non-message-based mechanisms such as shared databases or common event queues can be used. Each analytics section (7120) further includes one or more analytics plug-ins (7122a, 7122b, 7122c) which can process event objects received from the input section over the communication means (7140), one or more analytic rule definitions (7124a, 7124b, 7124c) which are used to define the processing by an analytics plug-in, and an optional analytics section log (7128) which is used to record the actions of the analytics plug-ins. One or more instances of an analytics section can be supported by a specific exemplary implementation of the present invention. Each analytics section is logically connected to one or more responder sections using one or more instances of a communications means (7150) in order to support further processing of the information. The communications means (7140; 7150) can be similar technologies, but are not required to be identical or even compatible. Thus, each of the analytics and responder sections are also associated using a many-to-many relationship. In some embodiments (not shown), a communications means can be used to directly link input section components to responder components without the use of an analytics section.
[0083] A responder section (7130) receives notification requests (or "notifications") from an analytics section through the communications means (7150) and processes these requests. Each responder section further includes one or more responder services (7132a, 7132b, 7132c), which can convert notifications into responses for further processing, responder rules (7134a, 7134b, 7134c) that are used to configure the operation of the responder services, and an optional responder-processing log (7138), which is used to record the operation of the responder section. Analytics and responder services optionally can perform additional pre-processing/enrichment of events, and can insert events into any of the communication interfaces linking components of the system. Various embodiments of the present invention further include one or more instances of a rules engine (7160), one or more instances of an enterprise agent service (7170), and one or more instances of configuration information (7180) that defines configurations of aspects of an input section, an analytics section, a responder section, a communications means, and/or other components of the present invention. Rules engine (7160) can be provided as a common instance of a rules engine or can be distributed with instances of specific analytic and responder sections. Configuration materials (7180) can be stored as a local disk file, within a service on the local machine, in a local database (e.g. within an instance of optional database (7190)), on a shared disk, in a shared database, or within a networked service such as LDAP as dictated by implementation circumstances. In one example embodiment, the Configuration Materials (7180) describes the configuration of an input section, an analytic section, and a responder section, including the configuration of each of the services that are part of each respective section. The Configuration materials (7180) further defines the communications means used. The configuration materials (7180) define an input section, including the number and types of producer services (7112a, 7112b, 7112c)) that are started, and the computing resources that each can use. Each defined producer service is associated with at least one PPS (e.g. 7114a, 7114b, 7114c) that defines the information source and Connector/Protocol Adapters to use, the authentication credentials to use for access to the information source, any necessary pre-processing steps to perform, scripts to execute, and other information that may be required to access the information source, obtain the information and convert it into event objects as required and place the said event objects into event queues for processing by at least one analytic section. Similarly, the analytic sections configuration materials define the rules engines, RSs and RuleBooks to use in processing event objects obtained from event queues.
[0084] One feature in some embodiments of the present invention is that event queues can be published from a first workspace, which makes them available to one or more second workspaces. For example, one or more input section instances can generate event objects that are aggregated within a first event queue, the "commercial news sources" event queue. In this example, the "commercial news sources" event queue can include event objects corresponding to each article published in commercially available news sources. Producer processes of authorized users place events into the said event queue and the analytic processes of the same, or other authorized, user(s) can process the said event objects. Authorized users can create more finely grained event queues, such as an event queue for commercial news having to do with occurrences in a particular city, and appropriate producer processes can be configured to write events to these queues. In some exemplary embodiments, a responder service can generate one or more event objects and add them to specific event queues for processing. For example, an analytics section component can identify a specific news story that matches one of its rules. That rule might specify to match all news stories from the AP newswire service that have the word "NASA" in their title or text, and to create an event object related to that news item in the "NASA" event queue for all news items that match. In this example embodiment, an analytics plug-in matches keywords in the news story with the keyword "NASA," and if a match occurs, creates and sends an event object to the "NASA" event queue. The selection of response to take (e.g., create and send an event object), and where to send the resulting event object (e.g., to the event queue) are specified as part of one or more rules.
[0085] A system in accordance with an embodiment of the present invention can be developed using any of the technologies known to those skilled in the art of developing complex software systems. In an example embodiment, the software components can be developed in Java using a service-based framework such as the Spring Framework. Rules engines and related components can be provided using java-compatible technologies such as the Drools Rules Engine and the Antlr Parser tools. Other technologies, such as C# or C++ can also be used. The database (7190) can be any available database, such as Oracle, MySQL, Informix, DB2, HSQLDB, Cloudscape/Derby, or another database product. The database can be stored solely within a computer memory (e.g., RAM), within memory and on a persistent memory such as disk, or solely in a persistent memory. Similarly, a networked service can be any available networked service, for example, an LDAP accessible directory service, such as the Active Directory product provided by Microsoft Corporation of Redmond Wash. Other types of network services are described at various points herein. Each of these services can be implemented by those skilled in the art.
2 Example Use
[0086] An example system in accordance with one embodiment of the present invention is an enterprise-class system, meaning the system needs to support many different deployment configurations. Distribution of services, portable producer specifications, rule specifications, and event descriptions and objects allows embodiments of the system of the present invention to be deployed across a distributed network of computer systems. One exemplary deployment is shown in FIG. 8, which shows a sample distribution, in which a first computer system (A) includes the input processing section (8110), including source services (8112a-c), source definitions (8114a-c), optional log (8116), and a communications means (8118). The communications means operably connects the first computer system to a second computer system (B) using networking techniques well known to those skilled in the art. One such well-known technique is TCP/IP networking. In some embodiments, the networking techniques used may not require a reliable network layer upon which to function, and can provide message store-and-forward and queuing capabilities. These capabilities provide for a distributed, intermittently connected system that is effective to receive and process data, and then provide events of relevant information to other systems for further processing. The second computer system (B) includes an input section (8130) and an analytics section (8140), including components as described above for FIG. 7. The input and analytics sections are joined using a communications means (8138), such as TCP/IP, messaging queues, or other inter-process communication system, such as shared memory, in order to pass information between the input processing section of the second computer system (B) and at least one analytics section. The analytics section of the second computer system (B) is also connected with the input processing section of the first computer system (A) (8110) using the communication means (8118). The second computer system (B) is also connected to a third computer system (C) using communications means 8128, which can be any of the communications means herein described. The third computer system (C) includes a responder section (8120) and is connected to the second computer system (B) through the communications means (8128), and further includes responder services (8122a, 8122b), responder rules (8124a, 8124b), and optional log (8126). Present in this configuration, but omitted from the drawings for clarity, is configuration materials that describe the configuration of each of the sections.
[0087] Also present in the system, but omitted for clarity, are web servers and web services that provide a user interface. These components can be present on any computer system that hosts aspects of the described invention. Alternatively, a user interface can be constructed using other technologies, such as hard-coded C/C++ or Java applications. The determination of user interface specifics is implementation dependent and can be implemented by anyone skilled in the art. Web-based examples of user interfaces presented herein are exemplary in nature and are not intended to limit the implementation to a web-based interface.
[0088] FIG. 9 depicts a first exemplary use of an enterprise-wide event management system. The system is configured to monitor an RSS news feed for stories about airplanes (9110). The system is configured with several instances of an RSS producer service (9120); each instance of the service is configured using one or more PPSs that describe the RSS interfaces to external information source(s) (9130). The producer service contacts the information source using the PPS information and access credentials provided in the source definition (9140). In this example, the information source is an RSS feed. The PPS provides a URL for source of the RSS feed (9150), and the pre-processing step of fetching the full text story using the URL embedded in the RSS feed using a specified RSS connector/protocol adapter component (9160). This configuration establishes the information flow from the information source to the producer service. The producer service receives the information provided (9170), performs the specified pre-processing as specified by the PPS (9180), and produces an event object based upon the information provided (9190). In some cases, the event object contains some or all of the specific information provided to the producer service; in other cases, the event contains meta-information relevant to the event, such as the time at which the information was obtained, the version of the software used to obtain the information, or other information about the source information or how it was obtained, instead of, or in addition to source information provided to the producer service. In yet other cases, the event includes a reference to the source information rather than the information itself, and optionally including meta-information about the source information or a reference to such meta-information. In some cases, additional event objects can be created and placed in event queues so as to cause responses that collect additional information from the same or different information sources and aggregate said additional information with the original event object or its content in a new event object (9200). This, and similar, processes of refining "raw" information by obtaining additional information and aggregating the additional information with the first information is called event enrichment. The enriched event is forwarded to one or more analytics section(s) (9210) based upon the specified processing of the relevant rule specifications.
[0089] Continuing with the exemplary use, an event representing a newly received story is received by the defined analytics section (9220) where the event is processed by a rules engine and one or more analytics plug-ins (9230). The rules engine processes the event in response to one or more rules defined for use by the analytics section. These rules can be taken from a database, a directory, shared files, or other storage means known to those skilled in the art. In some embodiments, groups of rules can be used together. These rules also can be from collections of sharable and portable RSs and recipes, called "RuleBooks", can be associated as part of a larger rule, or can be individually provided. In addition, further analysis of events can be provided using plug-in analytic programs associated with at least one rule (9240). The rules engine and/or analytic programs can generate additional responder section notifications on the basis of the rules processing, or upon the basis of processing by an analytics plug-in program (9250). The responder section notifications are forwarded to one or more responder section(s) based upon the specifications of the relevant RSs (9260).
[0090] The responder section operates one or more responder services, which convert responder notifications received within the system (9270) into responses (e.g., external notifications, messaging, or other actions) (9280). For example, a responder service can convert responder notifications resulting from the processing of an event object (such as the one above representing a news story that passed the pattern matching for "airplane") into an e-mail message, using information contained within the event object to fill in one or more aspects of the email message, such as a "To:" address or "Subject:". Each responder service has one or more configuration components in the form of responder rules. These rules can be taken from a database, a directory, shared files, RuleBooks, or other storage means known to those skilled in the art.
[0091] The resulting response (e.g., external communication or other action) (9280) completes the exemplary processing of a responder notification by the system of the present invention.
2.1 Distributed Architecture
[0092] The architecture of the event management system is inherently distributed. Distribution of the system provides scalability, redundant processing, and other benefits. The distributed architecture is enabled by the communication interfaces and modular component design described above. There are two primary distribution strategies: the distribution of services and rules management and the distribution of event processing and load-balancing. The distribution of services and rules management permits the system to operate with a minimum of centralized IT support, and leverages the capability of the system to collect and share rules and information processing techniques between users and their workspaces. Distribution of event processing permits the construction of scalable, highly redundant systems that are resistant to single point failure and that can be quickly scaled in response to changes in data volumes, information workflow, and user communities. Different information management and distribution strategies can be employed to implement these features--the choice of specific information management mechanisms utilized is implementation dependant. It is advantageous for distributed instances of an enterprise-wide event management system to use a common time source, so event and analytic timing is consistent. The use of common distributed time sources is well understood in the art.
[0093] One approach to distributing an enterprise-wide event management system is to distribute PPSs, services, RSs, recipes, RuleBooks, and configuration information between one or more computer system instances and link these instances using one or more communication means. In a first embodiment, each instance of the system of the present invention runs a web interface and connects to the same back-end data storage service or database, but each server instance negotiates for and actively loads only a subset of the services and rules stored in the data storage service or database. A back-end database system or storage server is preferably highly available. In an alternative embodiment, the backend database is not used. Rather, the configuration materials, PPSs, RSs, services, and other aspects of the system are propagated to each system that requires them. The propagation can be performed manually, using automated tools, or using shared disks or services such as a mounted disk or by integrating the materials as part of a shared directory service. Other mechanisms for sharing information between system instances also can be used and are well understood by those with skill in the art.
2.1.1 Redundancy and Fault-Tolerance
[0094] An enterprise-wide event management system of the present invention provides for an implementation-dependant degree of redundancy and reliability. Distribution of services as described above provides redundancy and fault tolerance by distributing service instances across several computer systems. The distributed computing systems can be configured using one or more communications means in order to effect distribution and redundancy.
[0095] When a rules engine (within the analytics section) or producer service is configured to use instances of RSs stored within a shared storage system, service, or database, the rules engine enables a new style of distribution: event processing flow then can be load-balanced across multiple computer systems while sharing a common configuration and rules set. Each system instance connects to the same storage system, service, or database. Each service instance is able to evaluate and update any rule in the system, consistent with access controls, because the state of the rule network is entirely persistent within the database. However, each service instance only processes a fraction of the incoming event flow. This approach helps to eliminate the I/O bottlenecks that occur in systems that process large volumes of data, and provides redundancy and fault-tolerance to the architecture. Event queues and service in-core lists can be persisted to disk, storage service, or database in order to permit fault tolerant restarts without loss of information.
2.2 Controls on Use
[0096] An enterprise-wide event management system in accordance with various embodiments of the present invention provides for controls on the use and flow of information using access control lists on each security enabled system object and service. These access control lists are used to grant access rights to the object or service. Access controls can be used to restrict creation, storage, viewing, modification, use, export/import, publishing/sharing or deletion of PPSs, RSs and recipes, RuleBooks, event objects, event queues, workspaces, or other aspects of the system.
[0097] Each security-enabled system object and service contains a set of access control list entries. Each entry specifies: [0098] principal (string)--a user name or, if prefixed by "ROLE_", a role name [0099] permission (string)--READ, WRITE, or ADMIN [0100] granted (Boolean)--either true or false
[0101] The permission field is completely flexible. Any text can be entered as a permission, so the list of available permissions can grow as needed. When a new database retrieval or update operation is written, the operation specifies which permissions are acceptable to complete the operation.
2.2.1 Example Access Control List
[0102] Suppose there exists a rule "Correlate market activity" that is managed by John Smith (jsmith), edited by Mark Hancock (mhancock), and readable by any user (ROLE_USER). However, Mike Jones (mjones) should not be able to see it at all. An exemplary access control list would look like this:
TABLE-US-00003 Principal Permission Granted jsmith ADMIN true mhancock WRITE true mjones READ false ROLE_USER READ true
[0103] In this example, ADMIN permission implies READ and WRITE permission, and WRITE permission implies READ permission.
[0104] In the examples given later in this document, it is assumed that the user has the proper permissions (READ, WRITE, or ADMIN) to successfully perform the described action(s).
2.2.2 Security in the User Interface
[0105] Users see only the objects they have permission to see. User interfaces inform the user of their access rights by displaying or hiding links, form buttons, and other controls as appropriate. (For example, if a user has read access but not write access, they can view an object's detail page but the link to the Edit feature will be hidden.)
[0106] If a user attempts to access a restricted resource or method directly from the web service interface, they will receive an appropriate HTTP error (e.g., 403 Not Authorized or 404 Not Found).
2.3 Logging and Auditing
[0107] The system in accordance with various embodiments of the present invention provides for auditing and logging of configuration and configuration changes, event object generation, event queues, service operations, and rule evaluations. The system also provides for object access, export/import, and publish/subscribe logging.
2.4 Working with RuleBooks
[0108] Exemplary implementations of the present invention provide means to create new RuleBooks, edit existing RuleBooks, publish and un-publish RuleBooks, subscribe to published RuleBooks, export and import RuleBooks and destroy (delete) RuleBooks. These functions can be restricted or prohibited based on the access rights of the user or role attempting them.
[0109] For example, if a user wants to publish several rules used by their stock-watching event processing flow, so that other users can implement their own stock-watching event processing flows, the user can create a RuleBook containing their stock watching rules, and the PPSs used to collect the information to feed through the rules. Other users can subscribe to the RuleBook, subject to access controls, and use the rules to establish their own stock-watching event processing flows.
2.4.1 Creating a New Rulebook
[0110] In an illustrative embodiment, the following steps may be carried out to create a new RuleBook: [0111] Step 1. Select "New>RuleBook" in the navigation menu. The New RuleBook screen appears and prompts the user to enter information for the new RuleBook. [0112] Step 2. Enter a name and description for the new RuleBook, and also select one or more RuleBook items from the displayed list for inclusion in the new RuleBook. [0113] Step 3. The system calculates minimum access rights for the new RuleBook based on the access rights of the RuleBook items selected for incorporation into the new RuleBook and displays this information. The calculated access rights will be equal to the most restrictive access rights of any RuleBook item selected for inclusion into the new RuleBook. The access rights can be adjusted so as to make the access rights more restrictive if desired. Selecting less restrictive access rights requires specific rights. [0114] Step 4. Set the encrypt/no-encrypt checkbox appropriately. [0115] Step 5. Optionally select a key to use to digitally sign the RuleBook. [0116] Step 6. Select "Save". The new RuleBook is created and saved to the current Workspace. If "Cancel" is selected, rather than "Save", the operation is aborted and a new RuleBook is not created.
2.4.2 Editing a RuleBook
[0117] In an illustrative embodiment, the following steps may be carried out to edit an existing RuleBook so as to add or remove RuleBook items currently incorporated into the said RuleBook: [0118] Step 1. Select "Edit>RuleBook" in the navigation menu. The system responds by displaying a list of existing RuleBooks in the current workspace. This list includes both private RuleBooks and those that are subscribed to and bound to the workspace. [0119] Step 2. Select the RuleBook to edit. The system then displays a list of the RuleBook items currently included in the selected RuleBook. [0120] Step 3. To delete RuleBook items from the RuleBook, select one or more RuleBook items from the displayed list of currently included RuleBook items, and select "Delete" to mark the selected RuleBook items for deletion. The system indicates the pending delete status for these items by altering their appearance, such as by lowering contrast, changing color, or by other means as are well understood by those having skill in the art. [0121] Step 4. To add additional RuleBook items to the RuleBook, select "Add". A list of available RuleBook items from the user's workspace, both local and subscribed and bound items, that are not already incorporated into the RuleBook, is displayed. Select the RuleBook items to add from the displayed list, using means well understood by those with skill in the art, such as clicking, double-clicking, dragging, etc., and these are added to the list of RuleBook items in the RuleBook, but marked so as to indicate their pending status, such as by altering their appearance by using a different color, contrast, or other means as is well understood by those having skill in the art. [0122] Step 5. As RuleBook items are deleted from, or added to, the RuleBook, the system calculates minimum access rights for the RuleBook based on items currently in, or pending inclusion in, the RuleBook and displays this information. The access rights can be adjusted to be more restrictive if desired. Making the access rights less restrictive can require specific authorization credentials. [0123] Step 6. Set the encrypt/no-encrypt checkbox as desired. [0124] Step 7. Optionally select a key to use to digitally sign the RuleBook. [0125] Step 8. Select "Update" and the RuleBook changes, whether deletions, additions, changes to access rights, encryption state or digital signing, are made and the updated RuleBook is saved to the current Workspace, replacing the original RuleBook. In some exemplary implementations, the original RuleBook can be preserved as a backup or prior-version copy. If "Cancel" is selected, rather than "Update", the operation is aborted, any changes made are ignored, and the original RuleBook is not altered or replaced.
2.4.3 Publishing a RuleBook
[0126] In an illustrative embodiment, the following steps may be carried out to publish a RuleBook so as to make the said RuleBook available to other users, roles or workspaces: [0127] Step 1. Select "Publish>RuleBook>New" in the navigation menu. [0128] Step 2. Select the RuleBook to publish from the displayed list. [0129] Step 3. Enter or select the user, role, or wildcard specification to publish the RuleBook to. [0130] Step 4. Select "Publish", and the RuleBook is published to the specified user(s) and/or role(s) and/or workspace(s). Select "Cancel" to abort the operation without publishing the RuleBook.
2.4.4 UnPublishing a RuleBook
[0131] In an illustrative embodiment, the following steps may be carried out to unpublish a RuleBook, so as to remove it from availability for subscription by one or more other users, roles, or workspaces: [0132] Step 1. Select "Publish>RuleBook" in the navigation menu. [0133] Step 2. Select the RuleBook to unpublish from the displayed list of previously published RuleBooks. [0134] Step 3. In the displayed information for the selected RuleBook, select the users, roles, workspaces or wildcard specifications to remove from publication of the RuleBook or select "Clear All" to remove all users, roles, workspaces and wildcard specifications (this makes the RuleBook private). [0135] Step 4. Select "Publish" to commit the changes and the RuleBook is unpublished and removed from availability for the specified user(s) and/or role(s) and/or workspaces, or, if "Clear All" was selected, the RuleBook is made private and is no longer published. If "Cancel" is selected, the operation is aborted, and the publication status of the RuleBook is not altered. [0136] Step 5. Note that unpublishing a RuleBook does not alter current subscriptions and bindings for the RuleBook. Those users, roles or workspaces that are currently subscribed to the RuleBook will retain access to the RuleBook, even after the RuleBook is unpublished for them, until such time as they unsubscribe from the said RuleBook. This avoids disruption of event processing flows for a first user, who is subscribed to a published RuleBook and making use of the RuleBook items incorporated into the RuleBook, when a second user, who has published the RuleBook, accidentally or intentionally unpublishes said RuleBook.
2.4.5 Subscribing to a RuleBook
[0137] In an illustrative embodiment, the following steps may be carried out to subscribe to a published RuleBook, so as to permit binding it to a workspace for use: [0138] Step 1. Select "Subscribe>RuleBook" in the navigation menu. [0139] Step 2. Select the RuleBook to subscribe to from the displayed list of available published RuleBooks. [0140] Step 3. Select "Subscribe" and the RuleBook is added to the user, role, or workspace as a current subscription.
2.4.6 Exporting a RuleBook
[0141] In an illustrative embodiment, the following steps may be carried out to export a RuleBook from the current workspace, so that it can be imported into another workspace, or transported to another instance of the system: [0142] Step 1. Select "Export>RuleBook>from the navigation menu. [0143] Step 2. Select the RuleBook to export from the displayed list of RuleBooks in the current workspace. These can be private RuleBooks or RuleBooks that are subscribed to, providing that access rights are sufficient for export. [0144] Step 3. Select the transport format from the list of available transport formats. The format chosen should be compatible with the import capabilities of the intended destination. [0145] Step 4. Select "Export", and a copy of the selected RuleBook is converted to the transport format and saved in the user's Workspace. The saved transportable RuleBook can then transported to the destination. If "Cancel" is selected, the operation is aborted and the RuleBook is not exported.
2.4.7 Importing a RuleBook
[0146] In an illustrative embodiment, the following steps may be carried out to import a RuleBook into the current workspace, so that it can be used: [0147] Step 1. Acquire a transportable format RuleBook by means well known to those having skill in the art, such as copying a file within a file system, receiving a file as an e-mail attachment, or copying from a portable storage medium, such as a CD-ROM, USB "thumbdrive", or other similar means. [0148] Step 2. Incorporate the transportable format RuleBook into the current Workspace. [0149] Step 3. Select "Import>RuleBook" in the navigation menu. [0150] Step 4. Select the transportable format RuleBook to import from the displayed list. [0151] Step 5. Select "Import", and the RuleBook is converted from the transportable format into the internal format used for RuleBooks by the system, and saved in the current Workspace as a private RuleBook. If "Cancel" is selected, the operation is aborted and the RuleBook is not imported. The transportable format RuleBook is not altered, and remains in the current Workspace in transportable format.
2.4.8 Destroying a RuleBook
[0152] In an illustrative embodiment, the following steps may be carried out to destroy (delete) a RuleBook: [0153] Step 1. Select "Destroy>RuleBook" in the navigation menu. [0154] Step 2. Select the RuleBook to destroy from the displayed list of available RuleBooks in the workspace. [0155] Step 3. Select "Delete". The system requests confirmation of the deletion, and provides a "Yes" option to confirm deletion, and a "No" option to deny confirmation. If the deletion is not confirmed (i.e. "No" is selected), the procedure is aborted and the RuleBook is not destroyed. If the deletion is confirmed (i.e. "Yes" is selected), the system has three possible actions that will be taken. The selection of an action is based on the state of the RuleBook. [0156] 1) If the RuleBook is private, and has no subscriptions, the RuleBook is deleted. [0157] 2) If the RuleBook is private, and has subscriptions (i.e. the RuleBook was published in the past, and has been subscribed to at that time), the RuleBook is removed from the current workspace and marked "pending delete" by the system, but the RuleBook is not deleted immediately. [0158] 3) If the RuleBook is published by another user, role or workspace, and has been subscribed to for the current workspace, the subscription is cancelled. If the RuleBook is marked "pending delete" and this was the last subscription to the said RuleBook, the RuleBook is deleted.
2.5 Events
[0159] Events are related to real-life occurrences pulled in from the outside world by producer services. Events can be anything that a user has deemed of interest, such as 911 dispatches, breaking news headlines, network outages, and the like. Some other examples of events include: [0160] Stock prices [0161] Credit card transactions [0162] Company public announcements [0163] Wire transfers to bank accounts [0164] IP address detections [0165] Call center activities [0166] Network conditions [0167] Community crimes [0168] Radar detections [0169] Weather events [0170] Building control system reports [0171] E-mail reception
[0172] Producer processes automatically generate event objects as they gather and pre-process inputs from information source, such as web pages, RSS feeds, sensors, databases and others. Millions of event objects can be passed through the system every day. When an event object is generated, its parameters are identified and used to assign the event object to a specific event queue. As described above, producer services manufacture event objects based upon the data they extract from underlying systems and information feeds. A single real-world event, such as a stock price change, news article, or credit card transaction, can result in a plurality of event objects being generated within the system. These event objects can be placed in a plurality of event queues for processing by one or more analytic sections. Rules as applied to event objects can produce additional event objects and trigger responder services to take action as a result of events. Therefore, event objects are central to event processing flows and resulting actions by the system.
[0173] An event object has one or more properties associated with it. Each event object can include properties common to all event objects, some properties common to one or more groups of event objects, and some properties that are specific to a particular event object type. The properties associated with each type of event object are defined at the time the event object type is defined. Some common properties associated with event objects include: [0174] a timestamp property. The timestamp property is set to the current time when the event object is added to an event queue. Alternatively, a producer service can set the timestamp to the time the event object is created, or to the time at which the source information that triggered the creation of the event object was acquired. [0175] an optional topic property. The topic property is set by the pre-processing rules or scripts specified in the PPS that configures the operation of the producer service that creates the event object. In some exemplary implementations, the event topic property is set to the name of the event queue into which the event is first inserted. In other exemplary implementations, the event topic property is set to the name of the event queue the event object is currently associated with. In still other exemplary implementations the event topic property is set to one or more tags that describe the general nature of the information that triggered the creation of the event object, such as "news", "blog post", "aerospace", "medical techniques", or "stock price change". [0176] an optional source property. The source property identifies the source of the event object, e.g. the ID of the producer service that created the event, the PPS that controlled the producer service, or a descriptive name for the original source of the information collected by the producer service. [0177] An event type property. The event type uniquely identifies the type of event object. The type of the event object determines the structure of the event object, and defines the properties the event object can include.
[0178] Each event type, class, and property is named within one or more namespaces, making them usable within one or more rules or workspaces. Namespaces are described in more detail above and below.
[0179] In some implementations of the present invention, an event object encapsulates a Java object of any type. The properties of the event object are the properties of the enclosed Java object. Event objects are typically read-only once they are created. For read only event objects, modifications to event objects are not allowed, although an event object can be copied and the copy modified.
2.5.1 Transportable Event Definitions
[0180] Event definitions, including the specification of event type and event properties, can be exported in a sharable or transportable form. Sharable and transportable event definitions facilitate the use of sharable and transportable services, PPSs, RSs, and related entities to facilitate distributed processing and creation of additional instances of the system, such as for disaster recovery, research or testing purposes. They can also be used to enable sharing and porting of services, PPSs. RSs, RuleBooks and workspaces between users, roles and workspaces or between instances of the system for other purposes, such as provision of such entities as a business service.
2.5.2 Event Persistence
[0181] In normal use, an event object is "used up" (consumed) when the event object is processed by a rule or rule set, however, it is sometimes desirable to make event objects available beyond their initial processing. This is advantageous when more than one event object is required to identify a pattern of events, such as a particular sequence of events, a particular frequency of events, a triggering event count, or a particular set of events all occurring within a given period of time. This process of retaining event objects and making them available for further processing is called "persisting" an event object. An event object that has been persisted is said to be "persistent".
[0182] In some exemplary embodiments, an event object can be made persistent by adding the event object to a persistent event queue. The persistent event queue can be made persistent by safe-storing it to a non-volatile storage device (e.g. a hard disk, flash memory, or magnetic tape) or a database, and by the system not removing event objects from persistent event queues when they are processed. Event objects will remain in this event queue until they are explicitly removed, and can be processed a plurality of times while they remain in the persistent event queue. This type of event persistence is useful when a manual interaction is desired to acknowledge a particular event.
[0183] In other exemplary embodiments, persistent event objects can be stored in a memory list by one or more services in order to make the event persistent. This type of event persistence can be made to survive process crashes and shutdowns by safe-storing the events stored in memory to a non-volatile storage device (e.g. a hard disk, flash memory, or magnetic tape) or a database.
[0184] In still other exemplary embodiments, persistent event objects can possess an expiration parameter that specifies a time at which the event object should be destroyed, the number of times that an event object can be processed before it is automatically destroyed, or another rule that specifies the conditions under which the event object should cease to be persistent and should be destroyed. This capability is useful for implementing time-limited or other semi-persistent event processing. Such capabilities can be useful, for instance, when an event object has persistent utility, but only for a limited time span, such as a current building temperature reading in a building control system that acquires and broadcasts a new temperature reading every 15 minutes, or a system that calculates a moving average for closing stock prices over the prior 30 days.
[0185] In yet other exemplary embodiments, the system can automatically persist all event objects until they are manually deleted, or automatically deleted under control of one or more rules.
2.5.3 Event Enrichment
[0186] Events can be "enriched" during processing by the system. Enrichment is a process by which additional properties and/or data are associated with an event object as the event object is processed by the system. Enrichment of event objects is a rule-based process, in which event objects are first identified by one or more rules, the responses of which are specified to either make changes in the event object's structure (e.g. add/remove/change properties), or to collect additional information and add that additional information to the event object.
[0187] In a first exemplary embodiment, adding, removing, or changing a property of the event object can enrich an event. For example, a rule can identify an event object of a first type, and for all event objects of this type that it identifies, add a property to the event object that indicates that the event object was processed by a specific instance of a service or a rules engine, or at a particular time. This type of event enrichment is useful for marking event objects as processed (which is particularly useful for persistent event objects), for adding other relatively static properties that indicate an aspect of the event or event object, and the like.
[0188] In a second exemplary embodiment, an event can be enriched by employing a rule that specifies a response that collects additional information and adds it to the event. For example, an event object can correlate to a stock symbol and price, and the response might be to use an SQL statement parameterized by an event object's properties to look up the stock ticker symbol in a database and obtain additional information about the stock issue from the database, such as name or price/earning ratio. This event enrichment procedure can be repeated a plurality of times for any given event. For example, once the original event object containing a stock symbol and price has been enriched by the SQL database query with the company name and P/E ratio, another rule can result in a response that triggers the activation of a producer service that uses a PPS specifying collection of information about the company that issued the stock, and the activation of rules that send any information discovered to a stock analyst's e-mail address. In this manner a stock reaching a given price point, for instance, can automatically result in gathering information about the company and delivery of this information to an analyst for determination of whether the stock price is justified or not. Event enrichment information can be added to the original event as new or changed properties and values, or can be implemented by creation of a new event object that contains both the original event's information and parameters as well as the new information and parameters resulting from enrichment actions.
[0189] In a third example embodiment, an event object can be enriched by combining information from two or more event objects. For example, a first event object is generated for a news story that matches a keyword rule that results in it being put in the "NASA" event queue, and a second event object is generated for the same news story that matches a keyword rule for "airplane". The two event objects can be combined to produce an enriched event object that has properties that indicate that the news story matches the "airplane" keyword and is (or was) in the "NASA" event queue.
[0190] The event enrichment process can be repeated without limit, enabling the provisioning of research/information enrichment steps using rules and RuleBooks, resulting in the fully automated production of packages of enhanced information from a variety of information sources that are provided to or by end-users.
2.5.4 Event Bus and Event Queues
[0191] The system supports several technical communications means for communicating between and within system instances and services. Each of these technical communication means provides an interface abstracted as one or more sharable lists of events, individually called an "event queue". Event queues also can be implemented using techniques other than communications techniques described above, for example, using a table in a shared database, an in-memory list, or a shared messaging bus. Collectively, the operating set of communication mechanisms implemented for an implementation of an enterprise-wide event management system is called the "event bus."
[0192] Event queues can be published and shared within the system, or they can be left private and visible only within a single workspace. Private event queues are used internally to event processing flows, or are made available to specific services, users, roles or workspaces on the basis of specific access controls. The visibility of event queues, either private or published, can be controlled using one or more access controls, as described herein. Each event queue can be ordered as a queue (first in, first out), or can be priority ordered based upon one or more event object properties.
[0193] Each event queue can have zero or more associated event sources, such as producer services or response section services that generate event objects in response to processing of other event objects according to rules. Each event queue also can have zero or more associated event object consumers, such as analytic section services. These event object consumers obtain event objects from an event queue and process them. Obtaining an event object from an event queue deletes the event from the queue, unless the event queue is a persistent event queue, or the event object has a parameter specifying that it is persistent. The association of an event source and the right to place an event object into an event queue is controlled by one or more access control mechanisms, as described herein. In some exemplary implementations the access rights of an event source can be specified in a PPS. Similarly, the association of an event consumer, and the right to retrieve an event from an event queue, is controlled by one or more access control mechanisms. In some exemplary implementations the access rights of an event consumer can be specified in an RS.
[0194] Using any of these techniques, event objects can be propagated to one or more components of the system. Distribution of event objects can occur either by sharing event queues between distributed aspects of the system or by replication of event objects to distributed aspects of the system. Some or all of the event objects in the event queue can be propagated in this manner.
[0195] Event queues also provide for the configurable safe storing of event objects added to each event queue. The safe storing of event objects in event queues is a configuration option that can be turned on or off and is used to determine when to save event objects. By default, all event objects are saved to a database, or other non-volatile storage, immediately upon receipt (i.e. at the time they are removed from an event queue). Optionally, event objects can be processed first and only then saved if they are found to participate in a partial match with one or more rule(s).
[0196] If one or more systems or services shut down, lose power, crash, and so on, then upon restarting the one or more systems and services the working memory can be rebuilt by rereading all the safe-stored event objects into working memory. (No responses are executed at that time, since it is assumed that they would have already been executed previously; the operation simply returns the working memory to the state it was in previously.) This option is also configurable; if turned off, no attempt to reload events from the safe-store is made upon startup.
[0197] Event queues can have properties associated with them. These properties can be used to define mandatory and optional aspects of event objects associated with each event queue, to optionally define default values for these properties if alternative values are not assigned, or to define aspects of the event queue itself, such as a name or ID, access rights required to place event objects into the queue, or to remove event objects from the queue, or by producer services to determine appropriate event queues to place generated event objects into. Event queue properties are used in a variety of ways as described herein.
[0198] Event queues can be used to categorize event objects and their properties. When an event object is created, the event object's properties and values are identified and categorized using one more rules and/or event queue definitions. The event object is then added to each appropriate event queue. If there is more than one event queue that is appropriate for a given event object, the event object is duplicated and one copy placed into each appropriate event queue. Event objects in a published event queue are made available to any subscriber to the said published event queue. For example, if a news-related event object is added to the "World News" published event queue, any subscriber of the "World News" published event queue can process the said event object. If the published event queue is not a persistent event queue, and the event object is not parameterized to be persistent, the first subscriber that processes the event object will consume it and the event object will be removed from the event queue and not be available to other subscribers to the published event queue.
[0199] New event queue properties can be created automatically. If an event object that contains a new property (e.g., "author") is the first event object containing that property to be placed into that event queue, then the property is added to the event queue's list of properties. As new rules or services are created, this allows producer services and other event object sources to "learn" to automatically associate event objects with one or more event queues.
[0200] Examples of event queues, and some of the parameters that can be associated with each, include: [0201] Stock Quotes (price, symbol, date/time, financial index) [0202] World News (date/time, title, full story text, URL) [0203] Call Center (location, date/time, representative, activity) [0204] Business News (date/time, title, full story text, URL) [0205] Community News (date/time, location, title, full story text, URL) [0206] Security Gate (date/time, location, license plate number, license plate state) [0207] Weather News (date/time, location, title, full story text, URL) [0208] Network and Server (server name, network IP, date/time, location) [0209] Bank Transactions (bank name, date/time, activity) [0210] Credit Card Transactions (credit card type, balance, credit limit, date/time, limit)
2.5.5 Viewing Events
[0211] One aspect of the present invention is to allow a user to view event objects currently in the system. Using an exemplary web interface, a user can select one or more views of event objects using the following procedure: [0212] Step 4. Select "View>Events>All Events" in the navigation menu. All of the events in the system, that the user has access rights to view, are displayed. Each event is shown with a unique ID number. [0213] Step 5. Select sort preferences14] Step 6. Use "next" and "previous" controls, or other well understood means, to navigate between screens if the presented events are too numerous to fit on a single screen.
[0215] An example event object list provides the following information: [0216] ID--Displays the ID number for the event. [0217] Topic--Displays the associated topics for each event. [0218] Properties--Displays the properties that are defined in each event object. For example, a stock.quote event may contain properties for price, date, and symbol. [0219] When--Displays the date and time of the event object timestamp.
2.5.6 Viewing Events by Topic
[0220] Embodiments of the present invention can process millions of event objects per day and could produce many screens of seemingly random event objects. To reduce the event objects displayed to a usable subset, a capability for viewing event objects filtered by topic is provided. For example, if the user is only interested in seeing event objects related to stock prices, they can use the following procedure: [0221] Step 1. Select "View>Events>by Topic" in the navigation menu. All of the topics used by any events in the system, that the user has access rights to view, are displayed. [0222] Step 2. Select the topic, or topics, of interest (such as "Stock Quotes"), or specify the topic or topics of interest by entering them explicitly. The system displays all event objects that include the specified topic or topics, from among the events currently in the system that the user has access rights to view. [0223] Step 3. Sort preferences are selected24] Step 4. The user can use "next" and "previous" controls, or other well understood means to navigate between screens if the presented events are too numerous to fit on a single screen.
2.5.7 Viewing Event Queues
[0225] The exemplary implementation of the present invention includes the ability to view event queues that there are sufficient access rights to. Access rights are defined using access control lists, as described herein. Access rights required to view a given event queue are defined as part of the event queue definition. In an illustrative embodiment, the following steps may be carried out to view all event queues: [0226] Step 1. Select "View>Event Queues" in the navigation menu. All event queues that there are sufficient access rights for are displayed. [0227] Step 2. Sort preferences are selected by use of the "View>Event Queues>Sort" option in the navigation menu. By default, event queues are sorted alphabetically by name. The sort order can be altered to sort event queues displayed by other mechanisms, such as based on event queue parameters (topic specification, access rights required, producer services that supply event objects to the queue, etc.), by number of event objects in the queue, by owner of the event queue, or by other means. [0228] Step 3. The user can use "next" and "previous" controls, or other well-understood means to navigate between screens if the presented event queues are too numerous to fit on a single screen.
[0229] The Event Queues screen lists all of the event queues that are visible to the user, showing the following information for each event queue: [0230] Name--Displays the event queue name. [0231] Description--Displays a brief description of the event queue. [0232] Properties--Displays the list of properties defined for the event queue. [0233] Events/Day--Displays how many events are typically generated for the event queue each day. [0234] Last Modified--Displays the date and time the event queue was last modified. [0235] Persistent/non-Persistent--Displays whether the event queue holds persistent event objects or not. [0236] Status--Displays the current status of the event queue.
[0237] The properties section provides information that can be used in determining the relevance of the event queue property to the event objects in the event queue. For each property, a count, frequency, and percentage are displayed. [0238] Count--Displays the number of times the property has matched a rule since the event queue was created. This count can be reset (see "Resetting a Property Count" below). [0239] Frequency--Displays the number of rule matches per hour for the property. [0240] Percent--Displays how often the property has matched a rule in comparison with the event queue's total rule match count. For example, an event queue can have 100 rule matches and a specific property can match 80% of those rule matches.
[0241] The count, frequency, and percentage information can be used to aid in writing rules that have a greater chance of matching. For example, if use of a "title" property results in 80% of rule matches and a "headline" property only matches in 30% of rule matches, a user can use this information to determine that writing a rule using "title" rather than "headline" is more likely to result in a rule that matches event objects in the queue.
2.5.8 Creating Event Queues
[0242] Most often, new event queues are created through services and properties are created automatically as previously described. However, a user can use the "New>Topic" feature to create a new event queue manually. In an illustrative embodiment, the following steps may be carried out by a user to create a new event queue: [0243] Step 1. Select "New>Event Queue", which causes a New Event Queue screen to appear with fields to fill in to define the parameters and other aspects of the new event queue. [0244] Step 2. Enter the name and description of the event queue. [0245] Step 3. Specify initial properties for the event queue in the "Properties" section. If an incoming event object contains properties not already associated with the event queue, the properties are automatically added to the event queue in addition to those specified initially. [0246] Step 4. Select "Create" to create the event queue in the current workspace.
2.5.9 Disabling or Deleting an Event Queue
[0247] A user with the required access rights can disable or delete event queues. Disabling an event queue does not remove the event queue from the system; the event queue still appears in the event queue display and can be reactivated. A deleted event queue is removed from the system
[0248] In an illustrative embodiment, the following steps may be carried out to disable or delete an existing event queue: [0249] Step 1. Select "Delete>Event Queue", from the navigation menu. The Delete Event Queue screen will appear, displaying all event queues that the user has sufficient access rights to disable or delete. [0250] Step 2. Select the event queue, or queues, to disable or delete. [0251] Step 3. Select "disable" to disable the selected event queues, or "delete" to delete the selected event queues. [0252] Step 4. The system requests confirmation of the disablement or deletion, and provides a "Yes" option to confirm the operation, and a "No" option to deny confirmation. If the operation is not confirmed (i.e. "No" is selected), the procedure is aborted and the event queue is not disabled or deleted. If the operation is confirmed (i.e. "Yes" is selected), the system has three possible actions that will be taken. The selection of an action is based on the state of the event queue: [0253] 1) If the event queue is not published, and has no subscriptions, the event queue is disabled or deleted. [0254] 2) If the event queue is not published, but has subscriptions (i.e. the event queue was published in the past, and has been subscribed to at that time), an event queue disablement fails, the IDs of the subscribing workspaces are provided, and the operation is aborted, but an event queue deletion results in the event queue being removed from the current workspace and marked "pending delete" by the system. The event queue is not deleted immediately in this case. [0255] 3) If the event queue is published by another user, role or workspace, and has been subscribed to for the current workspace, and the operation was to delete the event queue, the subscription is cancelled, but the event queue is otherwise not affected, unless the event queue is marked "pending delete" and this was the last subscription to the said event queue, in which case the event queue is deleted. If the event queue has been subscribed to for the current workspace, and the operation is to disable the event queue, the event queue is marked as disabled for the current workspace and event processing flows the workspace is processing, but the event queue is not affected for other users. 2.5.10 Testing with User Entered Events
[0256] After a user creates a new RS, an event object may not be immediately available to test the rule. The user can manually create an event object and customize the event object to match the new rule's conditions. For example, if the new rule invokes a response when stock symbol "MSFT" exceeds $90, the user can create an event object manually and specify MSFT as the symbol and $100 as the price to ensure that the response occurs as intended.
[0257] Two methods are available for creating custom events. [0258] Create a new event from scratch [0259] Copy and save an existing event 2.5.10.1 Creating a New Event from Scratch
[0260] The "New Event" screen is used to customize an event that can be used to test a new rule: [0261] Step 1. In the navigation menu, select "New>Event", which causes the New Event screen to appear. [0262] Step 2. Enters the same event queue name as defined in the new RS for event source. [0263] Step 3. Specifies the expiration date of the event. If the event is only being used for test purposes, the user can specify that the event expires in 1 hour. [0264] Step 4. Enter the properties and values to match those in the new RS's rule definition. [0265] Step 5. Add additional properties as desired. [0266] Step 6. Select "Save" to create the event object and insert it into the specified queue.
2.5.10.2 Copying an Existing Event
[0267] The "Copy Event" screen is used to customize an existing event object that can be used to test a new rule. Perform the following steps to copy an existing event object: [0268] Step 1. In the navigation menu, select "View>Events>All Events". All of the event objects in the system, that the user has access rights to view, are displayed. [0269] Step 2. Select an event object to copy. [0270] Step 3. Select "Copy". The selected event will be displayed in a New Event screen, as above. [0271] Step 4. The user modifies the event object properties as necessary. It is possible to change any existing properties so that they match the new rule. If necessary, a property can be deleted. [0272] Step 5. When all changes are complete, the user clicks Save and the event object is created and inserted into the event queue specified.
2.5.11 Event Auditing
[0273] The system provides for auditing of event objects, event queues, and response actions, including access attempts, event object creation, event object insertion into event queues and other aspects of the operation of the system. The auditing mechanism creates logs of event actions that can be reviewed by appropriately authorized users.
2.6 Watch Lists
[0274] A watch list is a set of stored data items. The watch list is stored as a single object with a unique user-defined name. The name can be specified within a specified namespace, or sans namespace. If the watch list is not associated with a specific namespace, it will use the default namespace of the workspace it is bound to. The watch list name can be added to a rule and the rule will reference the data stored in the watch list object. The benefit is that a user can modify the data within the watch list at any time and the rule does not have to change. This is particularly useful when the rule is published and shared by a plurality of workspaces. If the rule does not specify a namespace for the watch list, each subscriber to the rule will be able to create their own watch list, and the shared rule will reference each subscriber's individual watch list to obtain the referenced watch list data.
[0275] For example, if a user wants to create several rules regarding their stock portfolio, they can create a watch list with all of their stocks. When a user creates a rule, they use the watch list rather than each individual stock symbol. Then, in the future, if the user's stock portfolio changes, they can modify the watch list and every rule will automatically use their updated portfolio. If the rule is published, and does not specify a namespace for the watch list, each subscriber to the rule can create their own watch list, and when the rule is evaluated, the watch list will take on the default namespace of the workspace the rule is subscribed from, and the user's local watch list will be referenced. The published rule will then be referencing different lists of stock symbols for each subscriber, and each subscriber can update their watch list of stock symbols at any time without requiring changes to the RS or having any effect on other users or workspaces.
[0276] A watch list can be stored in an instance of the database, a local storage location, a shared directory service, a RuleBook or by other means as determined to be proper by those having skill in the art.
2.6.1 Creating a New Watch List
[0277] In an illustrative embodiment, the following steps may be carried out to create a new watch list: [0278] Step 1. Select "New>Watch List" in the navigation menu. The "New Watch List" screen appears. [0279] Step 2. The user specifies the type of watch list to create. To create the watch list as a text string, "Text" is selected. To create the watch list as a list of items, "List" is selected. [0280] Step 3. The text or the list of items is entered. [0281] Step 4. The name and description of the watch list is entered. [0282] Step 5. The status as of the watch list is set to "active". [0283] Step 6. "Save" is selected, and the watch list is created and saved to non-volatile storage so that it will continue to exist after system reboots or otherwise resets.
2.7 Services and Service Interfaces
[0284] A service is a configurable object that can be identified within the system by a unique identifier, and started and stopped. Services are executable programs that run as part of the system. They include the service, a configuration, and an optional name.
[0285] The rules engine is dependent on external services to produce events and respond to them.
[0286] Services are sometimes used to interact with the computer systems or networks external to the system of the invention, collecting data and inputting that data into the system of the invention in the form of event objects. A user can create and configure different services for a variety of data types, such as network monitors, news feeds, financial transactions, and so on. After a service is created, the user can schedule the service to run at any time and interval (e.g., 1 time every 30 minutes, every other day, the first day of the month, etc.). This type of service is called a producer service. Specifically, a producer service is a service that is configured by a PPS and can be scheduled to run at specific times. An example of a producer service is a news reader that extracts events from an RSS or Atom news feed.
[0287] Services are sometimes used to produce actions in computer systems or networks external to the system of the invention, such as by generating email messages or changes in databases. A user can create and configure different services for a variety of interaction types, such as sending an email, writing data to a log file, activating an alarm or updating a database. After this type of service is created, the user can configure the service to respond to one or more events by specifying the service as the response defined for a rule. Specifically, a responder service is a service that carries out a response for an underlying service, such as an analytic service. An example of a responder is an email service that sends email messages to notify specific users of the occurrence of particular events. A response is a named service configuration. Responses are specified within rules to specify actions to take when rules match specific events.
[0288] Services are sometimes used to manipulate information within the system of the invention. These types of services can be used for event enhancement, to perform calculations, do research, or for other tasks. After this type of service is created, the user can configure the service for use by one or more rules. Specifically, an analytic service is a service that implements a data processing function. An example of an analytic service is a match function that analyzes a set of input elements and returns a true or false result if all elements do or do not match specified criteria.
[0289] Services can be producers, analytics or responders. A service can be both a producer and a responder. For example, when an event object requires enrichment by the addition of additional information, the responder for the rule that determines the need for further event enrichment can be a producer service that acquires the additional information. A service can be referenced as part of a PPS.
[0290] A user with the proper permissions can create, modify, configure, schedule, disable or delete services. Disabling a service does not remove the service from the system; the service still appears in the service list and can be reactivated.
2.7.1 Example Services
[0291] Event objects are generated through producer services that are configured and scheduled using embodiments of the present invention. A multitude of producer services can be configured to access outside information sources of many different types, such as RSS feeds, data monitors, databases, web pages, and computer systems.
[0292] Example producer services include those that interface to: [0293] Email services, including pop, imap, and SMTP-based services. [0294] SMS services, that take SMS messages and produce events. [0295] RSS producer services, that take an RSS feed and process it to produce events. [0296] IM services, that take IM messages and process them to produce events. [0297] HTTP services, that take information from a web page and processes it to produce events. [0298] Database services, that perform queries against a database and process the results to produce events. [0299] File monitor services that monitor file system events and file contents and process the results to produce events. [0300] Real Time Alert Manager (RTAM) services. [0301] EAS Agent Service.
2.7.1.1 EAS Agent Service
[0302] This service communicates with an Enterprise Agent Server (EAS) to offer the following capabilities: [0303] Respond by executing an EAS agent or source asynchronously. [0304] Execute an EAS source/object/agent and raise the response as an event object of the present invention.
[0305] The service configuration defines the properties needed to invoke an agent: [0306] name of the agent to run [0307] event parameters
[0308] The EAS Agent Service is configured on initialization with the URL of the EAS Execution Servlet. When its respond method is invoked, the EAS Agent Service reads the requested agent name from the Response object, along with any other properties defined by the response object. The service then does an HTTP POST to the EAS Execution Servlet URL, with parameter agentName equal to the specified name. The service encodes all available event properties as form parameters. The EAS Execution Servlet makes those HTTP form-post properties available to the agent as event parameters. For example, if the AgentService sets a price parameter equal to 10, EAS will set $event-param:price$ to 10.
2.7.1.2 RTAM Service
[0309] This service communicates with a Real-Time Alert Manager (RTAM) server instance to offer the following capabilities: [0310] Respond to a situation by submitting an alert to RTAM [0311] Produce event objects for any observed RTAM alerts
2.7.1.3 Email Service
[0312] This service provides SMTP, POP, and IMAP interfaces to the system. It permits the system to: [0313] Respond to a situation by sending an e-mail [0314] Produce event objects by checking an e-mail inbox
[0315] The service configuration defines the mail server, account/mailbox, and authentication information necessary to communicate with the mail system.
2.7.1.4 Instant Messaging Service
[0316] The instant messaging service maps Jabber/XMPP messages and presence events to and from the system. This service leverages the Jabber IM service to: [0317] Respond to a situation by sending a Jabber message [0318] Produce event objects by checking an e-mail inbox
[0319] The Jabber server can be configured to provide transports to other messaging services such as AOL Instant Messenger, MSN Messenger, IRC, etc. Jabber/XMPP is a product of the Jabber Software Foundation of Denver, Colo.
2.7.1.5 URL Service--http, ftp, file, etc.
[0320] A generic change listener built on the Apache Commons VFS product from the Apache Software Foundation of Forest Hill, Md., allows users to: [0321] Respond to a situation by executing a file write, http post, ftp put, etc. [0322] Produce an event object by reading a web page, ftp location, file, etc. and returning its result
[0323] The VFS API supports many common file systems (for example, local file, CIFS/Windows networking, FTP, HTTP, HTTPS, SFTP, temporary files, webdav, zip, jar, gzip, bzip2). It is a "dumb" retrieval/comparison algorithm, and submits the entire document when the document changes.
[0324] Alternatively, the URL Change Listener can delegate its services to lower-level change listeners that understand the most efficient ways to detect changes in their domain. The HTTP Change Listener is one example where greater efficiency can be attained by leveraging protocol-specific features.
2.7.1.6 HTTP Change Listener Service
[0325] An HTTP change listener leverages HTTP protocol-specific features to efficiently determine when a web page has changed. Examples are ETag/If-Match, and If-Modified-Since. Those headers lets the user ask the web server if the page has changed since the last time the user retrieved the page, and the headers are a much more intelligent way to determine web page changes than downloading and comparing locally.
2.7.1.7 Database Service--http, ftp, file, etc.
[0326] This service allows embodiments of the present invention to interact with a database through a JDBC driver. Each service instance is pre-configured with a JDBC driver, connection string, and so on and accepts the following tasks: [0327] Respond to a situation by running a database query (typically INSERT, UPDATE, etc.) [0328] Produce an event object by reading the result of a database query (typically SELECT)
[0329] Multiple databases can be handled with separate instances of the Database Service.
2.7.1.8 RSS Producer Service
[0330] An RSS producer service is an RSS listener that subscribes to one or more RSS feeds, and monitors each feed for RSS feed items (such as news stories). The RSS producer service uses configuration information, such as a PPS, to define one or more feeds and to make the RSS association for these feeds. The RSS producer service receives each feed and processes the feed, looking for items in the feed.
[0331] The RSS producer service can be optionally configured to generate an event object for each item found in the feed, to generate an event object for each new item found in the feed, or to generate an event object for each item in the feed that matches one or more defined pre-processing rules. For each feed item identified as requiring an event object, the RSS producer service generates one or more event objects. These event objects can be tagged with one or more topics, as defined by the PPS, or determined by pre-processing rules.
2.7.1.9 File Monitor Service
[0332] A windows file system listener watches a directory recursively for any changes within that directory tree; or the file system listener can watch a single file for changes. When changes occur, the file system listener POSTs the file metadata and content using the HTTP REST interface.
2.7.2 Service Properties
[0333] Services have properties associated with them. Some example properties include: [0334] Name--Displays the name and description of the service. [0335] Type--Displays the type of service. [0336] Owner--Displays the user who created the service. [0337] Status--Displays the current status of the service (e.g. enabled/disabled). [0338] Schedule--Displays the service schedule. The schedule includes a start time, end time, repeat count, and a repeat interval.
2.7.3 Portable Service Definitions
[0339] The system provides for the creation and use of portable service definitions. Portable service definitions include configuration and naming for producers, responders (e.g. responses), and analytics, and can be stored in a database instance, on a local disk, in configuration materials, in a RuleBook, or other locations as is convenient. In some embodiments, a portable service definition references or includes a specific instance of an executable program that provides a service. A portable service definition used to configure a producer service is known as a "Portable Producer Specification" (PPS).
2.7.4 Scheduling a Service
[0340] Producer and response services can be scheduled as to when they run. Schedules do not apply to analytic services. Scheduling a service causes the service to run on a periodic basis to collect information from information sources or to process any responses that have been queued for delayed execution.
[0341] In an illustrative embodiment, the following steps may be carried out by a user to schedule a specific service: [0342] Step 1. Select "Services>All Services", which causes the "Services" screen to appear. [0343] Step 2. Select the service to schedule. This causes the "Schedules" screen to appear. If no schedule currently exists, or if the service is newly created, the schedule section can be used to set a start time, end time, and an interval for the selected service. The format used for the "Start Time" and "End Time" fields is implementation dependent, but can be, for example, "yyyy/mm/dd hh:mm:ssAM (or PM)", such as "2006/07/31 10:04:03AM" [0344] Step 3. The "Repeat Count" field, is used to specify how many times the schedule is to be run. [0345] Step 4. The "Repeat Every" field is used to specify the time interval between each scheduled execution of the service. [0346] Step 5. Select "Save Schedule" to cause the schedule to be set as entered.
[0347] In an exemplary embodiment, a schedule starts on Dec. 11, 2006 at 12:32:42 AM and ends at 11:59:59 PM. The schedule will run once every hour.
[0348] After a service is scheduled, the service will run at the designated time and interval, producing or processing event objects.
2.7.5 Creating a Producer Service
[0349] A producer service is a service that generates event objects. Producer services are configured by specification of a Portable Producer Specification (PPS) and can be scheduled to run at specific times or intervals. An example of a producer service is a news reader that extracts events from an RSS or Atom news feed. In an illustrative embodiment, the following steps may be carried out to create a new producer service: [0350] Step 1. Select "New>Service" from the navigation menu. [0351] Step 2. From the drop-down menu, select "producer" to display only those service types that produce event objects. Each service type is followed by a brief description. [0352] Step 3. Select the service type to create. The "New Service" screen appears and displays the properties for the type of service selected for creation. For example, a news feed service requires a URL; an IM service requires a user name, password and server. All producers require a name and a PPS. [0353] Step 4. Enter the name and description of the new service. [0354] Step 5. Enters the remaining information required for the service type, such as access parameters to the PPS and/or the data collected by the producer service, whether the PPS should be published or not, and values for other parameters stored in the PPS. [0355] Step 6. Select "Save", which causes the PPS to be saved with the specified values, and the "View Service" screen to appear, where the user can schedule the new service. (See "Schedule a Service" above.)
2.7.6 Analytics
[0356] An analytic is a service that provides a function. The analytic can provide a simple function (like in an API) or can be a more complex service that connects to a remote server and performs some processing before returning. The implementation details are transparent to the user and to the query language. A service that implements the Analytic interface can be plugged into a system of the present invention for use within a query language specification as analytical functions. Here, the basic analytics are described and it is demonstrated how they can be used within a query language statement. Examples include Inxight, Metacarta GeoTagger, and so on (anything that needs to establish or verify a connection with a remote service).
[0357] Analytics are called from the rule definition language. The query language syntax is:
analyticname(operand1{,operand2, . . . })
EXAMPLES
TABLE-US-00004 [0358] categorize(message.text) intersects(point,region) WHEN message WITH categorize(text) HAS `weapons`
2.7.6.1 Match Analytic
[0359] The Match analytic determines whether all input objects are equal.
Example 1
[0360] Assume the analytic is deployed in an analytics BeanContext with the name "match". A user enters the following rule:
WHEN 3 `stock quote` WITH match (symbol) THEN . . .
[0361] The "symbol" identifier used above means the set of symbol properties from the selection of 3 stock quotes. The match analytic operates on that set. The embodiments of the invention pass the match analytic a Collection of symbol properties. The match analytic returns a single Boolean result--true if all the input symbols are equal.
Example 2
TABLE-US-00005 [0362] WHEN `press release` p, 3 `stock quote` s, WITH match(p.company_symbol, s.symbol) THEN . . .
[0363] In this case, match operates on a single string property p.company_symbol and a set of 3 properties s.symbol. The engine flattens the inputs and calls analyze with a Collection containing p.company_symbol and the 3 symbols from s. The result of match is true if all 4 elements of the Collection are equal.
2.7.6.2 Range Analytic
[0364] The Range analytic computes the range of a collection of numbers (the difference between the largest input and the smallest input).
Example
TABLE-US-00006 [0365] WHEN 3 `stock quote` WITH symbol=`EBAY`, range(price) > 5 THEN . . .
[0366] Parameters: 3 events from the `stock quote` topic [0367] Condition 1: symbol=`EBAY` [0368] Condition 2: range(price)>5
[0369] To implement the second condition, various embodiments of the invention analyze the range of the price properties in the parameter set. The range analytic can operate on that set. The various embodiments of the invention pass a Collection of Double objects to the range analytic, which returns the absolute value of the difference between the largest input and the smallest input. If that value is greater than 5, the expression is true.
2.7.6.3 Count Analytic
[0370] The Count analytic returns the number of input elements--implemented as Collection.size( ).
[0371] Example: Assume the analytic is deployed in an analytics BeanContext with the name count. A user enters the following rule:
WHEN 5 `stock quote` WITH count (symbol)=5 THEN . . .
[0372] The result is the number of symbol properties encountered in the input set. In this case, the condition is true if all 5 input events have a symbol property. If any of them are missing the property, the condition will be false.
2.7.6.4 Xpath Analytic
[0373] The Xpath analytic returns the result specified by the xpath--implemented using Apache Commons' JXPath. An object base is optional: if unspecified, the enclosing event is the object base.
[0374] Signature:
xpath({object base,} string xpath}
[0375] Example: Assume the analytic is deployed in an analytics BeanContext with the name xpath. A user enters the following rule:
TABLE-US-00007 WHEN `new document` WITH xpath("/document/summary/country/text( )") contains "iraq" THEN . . .
[0376] Optionally, one of the event's properties can be passed to the analytic as the base object.
TABLE-US-00008 WHEN `new document` WITH xpath(content,"/summary/country/text( )") contains "iraq" THEN ...
In this case the xpath is computed starting at the content property.
2.7.6.5 Regex Analytic
[0377] The Regex analytic returns a set of substrings of object.toString( ) that match the specified regex. If the base object is unspecified, the enclosing event is the base object.
[0378] Signature:
regex({object base,} string regex}
Example 1
[0379] Assume the analytic is deployed in an analytics BeanContext with the name regex. A user enters the following rule:
WHEN `new document` WITH contains regex ("ab.*") THEN . . .
[0380] The xpath starts with the `new document` event, calls the toString( ) method on the `new document`, searches the document for the regex pattern "ab.*", and returns a set of strings from the matching country nodes.
Example 2
TABLE-US-00009 [0381] WHEN `new document` WITH contains regex(content, "ab.*") THEN . . .
This example is the same except it runs the regex on the "content" property of the event, instead of the event itself.
2.7.6.6 Text Processing Analytics
[0382] Custom analytics also can be developed, using Inxight, ANNIE, and so on.
TABLE-US-00010 Analytic Input Returns Description Uses extract-entities string set Finds entities in the input Inxight categorize string set Returns a set of categories Inxight summarize string set Returns a summary of the Inxight input
2.7.6.7 Spatial Analytics
[0383] Spatial Analytics operate on geospatial points and regions. [0384] intersection [0385] union [0386] difference [0387] symmetric difference [0388] convex hull [0389] buffer
2.7.6.8 Creating an Analytic
[0390] An analytic service is a service that implements a data processor that can be plugged into a rule definition. An example of an analytic service is a match function that analyzes a set of input elements and returns a true or false if all elements match. In an illustrative embodiment, the following steps may be carried out to create a new analytic: [0391] Step 1. Select "Services>New Service". [0392] Step 2. Select "analytic" to display only those service types that analyze event objects. Each service type is followed by a brief description. [0393] Step 3. Select or enter the name of the service type to create, which causes the "New Service" screen to appear. [0394] Step 4. Enter a name and description for the service. [0395] Step 5. Select "Save".
2.7.7 Responses
[0396] Responses are initiated as part of rule evaluation. Response capabilities include the following: [0397] Provide users with notifications/alerts through channels such as email, IM, and web browser based on detected events. [0398] Automatically respond to data events across disparate systems based on user-defined rules by initiating transactions, triggering existing workflow systems, and interacting with remote web services. [0399] Deliver contextual alerts that include related queries from other sources. [0400] Intelligently and automatically open up applications such as GIS mapping environments, analytic tools, and multimedia viewers on end-user desktops based on server events without requiring client download. [0401] Display changing data from underlying systems to real-time web browser screens without requiring client download. [0402] Facilitate rapid response to notifications/alerts with return-receipt tracking, time-based escalation, and "one-click" buttons within alerts that trigger actions.
[0403] Rules invoke responses to event conditions by invoking a pre-defined Response or by invoking a Responder Service. For example, a response can be an email to a specific user to notify that user of a specific event. Responses defined in the Response user interface can be defined as templates where all or some fields can be left blank. Response definitions can be stored in a database, in a RuleBook, in configuration materials, or locally within each instance of the system.
[0404] When the user inserts a response into a rule, the response parameters can be defined at that time. However, in the response user interface, the user can specify key properties to be used as default values when the response is added to a rule. For example, in an email response, the user can specify a CC or BCC property where a specific user or account will receive copies of all the emails sent through that response.
[0405] Some examples of responses include: [0406] Email Message--Generic email with default values: to, from, subject, and body. [0407] IM Message--Generic IM with default values: screen name and message text. [0408] EAS Agent--Generic Agent with default values: agent name, namespace, and login information. [0409] RTAM Alert--Generic RTAM alert with default values: to, from, subject, channel, and priority.
[0410] Users with the proper access rights can disable or delete a response from the Edit Response screen. Disabling a response does not remove the response from the system; the response will still appear in the response list and can be re-activated. A deleted response is removed from the system and cannot be re-activated. Rules employing disabled or deleted responses do not match event objects in the rules engine.
2.7.7.1 Creating Responses
[0411] A user can create several responses for each service type. For example, if a user selects mailto, he can create several different email responses, each used in a different scenario. For example, each email response can specify a different default subject and body. In an illustrative embodiment, the following steps may be carried out to create a new response: [0412] Step 1. Select "New>Response" from the navigation menu. The "Create Response" screen will appear. This screen lists all of the available services for which new responses can be created. [0413] Step 2. Select or enter the name of the service for which to create the response. The "New Response" screen appears. The New Response screen is used to define the properties of the new response. There is no need to enter values for all properties. Only the "Name" value is required. Undefined property values can be entered when using the response for creating rules. However, if the value of a property is defined, it is the default unless overridden in an RS. [0414] Step 3. Enter a name and description for the response. The name should easily identify the response so that the user can recognize it as it appears in the system (e.g., when creating rules). [0415] Step 4. Depending on which type of response is being created, define the required parameters. For example, if an instant message response is being created, specify "To:", "Subject:", and "Message Body:". Any or all parameters can be left blank, depending on how the response is to be used. [0416] Step 5. Select "Save" to save the ne response definition. 2.7.7.2 Creating a Response from Existing Service
[0417] The "New Response" screen is used to convert a selected service into a response. In some implementations, only Responders and Producer/Responders can be converted into Responses. Thereafter, the user can add this response as part of a new rule.
[0418] In an illustrative embodiment, the following steps may be carried out to create a response from an existing service, the user performs the following steps: [0419] Step 1. Select "Services>All Services", which causes the "Services" screen to appear. [0420] Step 2. Select the name of the service from which to create a response in the "Responders" list, which causes the service details screen to appear. [0421] Step 3. Select "New", which causes the "New Response" screen to appear. [0422] Step 4. A name and a description of the response are entered. The name should easily identify the response so that the user can recognize it as it appears in the system (e.g., when creating rules). [0423] Step 5. Depending on which type of response is being created, define the required fields. For example, if an instant message response is being created, specify "To:", "Subject:", and "Message Body:". [0424] Step 6. Any or all parameters can be left blank, depending on how the response will be used. An exemplary embodiment shows a stock quote instant message response where only a subject parameter is defined. This response can be used in any rule specific to stock quote price alerts and the rule creator only needs to define the "To:" and "Message Body:" parameters. [0425] Step 7. Select "Save" to save the created response service.
2.8 Rules Engine
[0426] The rules engine processes rules. The rules engine includes interfaces for propagating event objects into and out of the engine, parsing and creating rules, and tracking partial rule evaluations. Event objects are detected automatically through activation of user-defined rules that are configured within the various embodiments of the present invention.
[0427] Event detection capabilities of the rules engine include the following: [0428] Cross-references, filters, and correlates events as represented by event objects over time, geography, and across disparate sources to detect complex events. [0429] Leverages third party entity extraction, natural language processing, and categorization engines as a part of complex event processing flows. [0430] Allows end users to define personalized rules and subscription criteria for Event Detection and Response.
[0431] The rules engine, upon initialization, loads RSs from workspaces, RuleBooks and other storage locations configured for the rules engine. The rules engine identifies the RSs, watch lists, and other components that must be loaded on the basis of one or more configuration materials. Each identified component is located, and loaded into the rules engine, translated from its storage or transportable format to an in-memory form, and stored within the memory of the rules engine. Internal event queues are also loaded as necessary to re-establish the historical context of the rules engine.
[0432] At this time the rules engine is ready to start processing events. The rules engine then registers to receive event objects from event queues and begins processing the event objects it receives.
[0433] For each event object received, the rules engine evaluates each enabled rule to determine whether the rule matches the current event object. If no match occurs, the rules engine has completed processing the event object. If one or more matches occur, the rules engine selects the rules to be processed and then processes them. Rules associated with disabled or deleted topics are not matched. Similarly, disabled rules are not processed either. Each rule is processed by evaluating the rule and executing the proper response if the rule matches. The response is specified as part of the RS as described above and below.
[0434] The rules engine evaluates event objects in several ways. A first method of event object evaluation is instant analysis of an event object when the event object is received. This method of evaluation provides for near-real time detection of specific events, and is implemented using simple tests for event object properties matching an expression with the immediate generation of a response when a match occurs. A second method of event object evaluation is the evaluation of an event object in context of other event objects. This method of evaluation provides for recognizing a series or collection of related events, such as "IF event A has occurred and event B has occurred, then make an appropriate response." A third method of event evaluation is the evaluation of an event object for membership in partially completed event series. Thus, if a rule specifies that a specific event should occur four times in an hour before a response is instigated, each incoming event object must be evaluated against other event objects of the same type that have occurred in the recent past. The rules engine uses internal event queues, watch lists, or database persistence to store the historical event objects for subsequent evaluation as described above.
2.8.1 Rules
[0435] The system provides for robust user-created rule authoring and sharing through formulas, wizards, and templates. User-created rules created by a first user can be published and shared with, or exported for transport to, one or more additional second user(s) in a variety of ways, including: [0436] the immediate re-use of the published shared rules by the second user(s), [0437] the use of the published shared rules as a template for additional rules and techniques authored by the second user(s), [0438] the aggregation of rules into one or more RuleBooks and the RuleBooks made available to one or more second user(s) by publishing them, and the second user(s) subscribing to them, or exporting them for transport to the second user(s) for import, [0439] the aggregation of shared rules into part of an information collection infrastructure, and [0440] making available to one or more second user(s), as an event queue or queues, of aggregated information resulting from the application of one or more rules operating against at least one event object.
[0441] By supporting user-created rules and event queues, the system permits individual users to create rules and event queues that translate their own information processing techniques into sharable, automated resources. These resources are made available to additional users by the capabilities supported by the system. The system thus supports knowledge and information sharing on a variety of fronts, including the sharing of rules, analytic structures, and resulting collections of pre-processed information. Rules can be taken from a database, a directory, shared files, or other storage means known to those skilled in the art. In some embodiments, groups of rules can be used together. These rules also can be obtained from RuleBooks of sharable and transportable rules and recipes, can be associated as part of a larger rule, or can be individually provided. User-created rules can also be exported and transported to other instances of the system, such as when providing a business service comprising provision of rules and RuleBooks, or when suggesting topics for classifying information feeds.
[0442] Rules are used to analyze event objects based on specific conditions, and then to invoke responses when conditions match. For example, when a producer service (e.g. from reading a news feed) creates an event object that matches a specific condition (e.g., the news content contains "London"), the rule evaluation then invokes a specific response (e.g., send an email).
[0443] The current invention provides for use of Rule Wizards that step users through the processes of selecting event queues and/or topics, rule specifications, and associated responses. Templates also can be provided by a user with appropriate access rights so the user simply inputs key values. Finally, the user can input rule text manually; however, this feature is for advanced users only.
[0444] Previously defined rules can be disabled, either by the system or a user with appropriate access rights. Disabling a rule does not remove the rule from the system; the rule will still appear in the rule list and can be reactivated.
2.8.2 Rules Wizards
[0445] The Rule Wizard steps the user through the process of selecting event queues and/or topics, rule definitions, and associated responses. To help assist the user in creating rules using the Rule Wizard, an auto complete function is available, which helps the user select topics and properties.
[0446] In an illustrative embodiment, the following steps may be carried out to create a rule using the Rule Wizard: [0447] Step 1. Select "New>Rule From Wizard", which causes the Rule Wizard screen to appear. [0448] Step 2. Enter the name and description of the new rule that clearly states the purpose of the rule and distinguishes it from all other rules. [0449] Step 3. Select or enter the event queue(s) and/or topic(s) that will provide event objects for the rule to evaluate. [0450] Step 4. Specify the Occurrences value, which defines how many times events must occur that match the rule definition before the rule activates its response. For example, if a stock price drops a certain percentage 5 times, the rule will activate. [0451] Step 5. Specify the Within value, that specifies a time frame in which the rule must be activated for the response to be executed. For example, if a stock price drops a certain percentage within 1 hour, the rule activates. [0452] Step 6. Defines the conditions that event objects must match for the response to be activated. In some embodiments, at least two parameters must be defined for each condition. A parameter can be an existing event queue, topic, watch list, or a constant value. The operator is a function between two or more parameters. For example, x=y, or x>y. If the function is true, then the rule is activated. Analytical functions can be added to the rule definition. For example, the user can add the range analytic to return the absolute value of the difference between the largest input and the smallest input. [0453] Step 7. Select the responses to apply to a rule. In some embodiments of the invention, at least one response must be created before creating a rule. [0454] Step 8. When the response to use in the rule is selected, the default parameters and values in the response can be accepted, or new ones can be specified. Values defined in the RS override default values in the original response. For example, the user can specify a new email address for an email response. [0455] Step 9. Select "Save" to create the RS and save it to the current workspace. [0456] Step 10. The "View Rule" screen appears with a summary of the rule created by the Rule Wizard.
2.8.3 Rule Templates
[0457] Rule Templates are an alternative method to create new rules. A user with appropriate access privileges can create templates representing common scenarios, such as news event alerts, stock quote price checks, and credit card transaction monitoring. A user then can select one of these pre-existing templates and follow the instructions below to create a rule.
[0458] In an illustrative embodiment, the following steps may be carried out to create a rule using a template: [0459] Step 1. Select "New>Rule Using a Template", which causes the "Templates" screen to appear and list the existing templates that are available given the available access rights. [0460] Step 2. Select or enter the name of the desired template to use, which causes the "New Rule" screen to appear. [0461] Step 3. In the Parameters section, define each variable. Next to each text box is the expected value type (e.g., dollar amount, text, email address, and so on). [0462] Step 4. In the "Save Statement" section, enter a name and description for the new rule. The name and description should clearly identify the rule and describe the purpose of the rule. [0463] Step 5. Select "Save" to create the RS and save it to the current workspace.
2.8.4 Rule Structures
[0464] Rule definitions leverage if/then/else statements, keyword/pattern matching, statistical processing, Boolean logic, overtime correlation, geospatial analysis, automatic cross-referencing against external sources, and more, to identify events. The rules engine uses a query language to analyze multiple events based on joins, temporal (time) windows, spatial regions, and pluggable analytics. The rules engine provides efficient storage and joining of multiple events, while ignoring/expiring old events (those that have surpassed the temporal boundary). Features include: [0465] multiple events can be compared using joins [0466] temporal windows ("within 30 minutes", "within 7 days", etc.) [0467] pluggable analytic services
[0468] A rule is defined using common computer parseable grammars. The rules engine translates from human-readable forms (e.g. ASCII text) to machine usable formats (e.g. bytecodes). Both formats are considered rules. RSs describe event queues from which to obtain event objects, each with optional selection criteria; rule definitions that specify matching criteria, optional temporal window constraints, etc.; and one or more responses to be executed when the rule is matched. The following are example extensions to SQL that enable the query language to operate with event objects.
TABLE-US-00011 rule := WHEN events (WITHIN timeperiod)? THEN responses events := event (COMMA event)* event := (count)? topic (alias)? (WITH exprs)? responses := response (AND response)* response := (responder | named_response) target? (WITH params)? responder := (DO | RUN | SEND) name named_response := name
[0469] Rule definition text inherits characteristics common in existing languages, with some minor differences. [0470] Topics can be dotted identifiers or string literals.
TABLE-US-00012 [0470] topic := identifier (`.` identifier)* | string_literal
[0471] Analytics, like SQL functions, use parentheses and a comma-delimited parameter list [0472] analytic:=identifier `(` expr (`,` expr)* `)` [0473] Expressions use SQL-like infix notation and operators: +, -, *, /, AND, OR, NOT, IN, CONTAINS
TABLE-US-00013 [0473] operators := `+` | `-` | `*` | `/` | `AND` | `OR` | `NOT` | `IN` | `CONTAINS`
[0474] Response parameters are specified as a comma-delimited list of key=value pairs.
TABLE-US-00014 [0474] params := param (`,` param)* param := identifier `=` expr
[0475] Variable Identifiers can use dots to de-reference sub-properties, and can have namespaces to denote different scopes.
TABLE-US-00015 [0475] variable := (namespace `:`)? identifier (`.` identifier)*
[0476] Topic aliases are just identifiers. [0477] alias:=identifier [0478] Identifiers are case-insensitive words that start with a letter (a-z), and then can contain letters (a-z), numbers (0-9), underscore (_) or the at symbol (@)
TABLE-US-00016 [0478] identifier := (`a`. .`z`) (`a`. .`z`| `0`. .`9` | `_` | `@` )*
[0479] String literals nest any sequence of characters inside of matching single-quotes or matching double-quotes.
2.8.4.1 Key-Value Lists
[0480] Syntax:
keyvaluelist:=param EQUALS value {, keyvaluelist}
2.8.4.2 Time-Series Calculations
[0481] Syntax:
TABLE-US-00017 within [time-interval] within 24 hours within 3 days
2.8.4.3 Sequence Calculations
[0482] Syntax:
TABLE-US-00018 when last MY_EVENT when oldest MY_EVENT when last 5 MY_EVENT when oldest 5 MY_EVENT
[0483] In the above examples, "last" also could be newest, latest, and so on.
2.8.4.4 Set Literal Notation
[0484] When a set is to be specified literally in query language, the following syntax is used:
(`1`, `2`, `3`, `4`)
2.8.4.5 Examples: Stock Quotes
[0485] Check all stock quotes.
WHEN stock.quote THEN run agent check-stock
[0486] Check only MSFT stock quotes.
TABLE-US-00019 WHEN stock.quote WITH symbol=`MSFT` THEN run agent check- stock
[0487] Check only stock quotes that match a symbol saved in the user profile.
TABLE-US-00020 WHEN stock.quote WITH symbol=profile:symbol THEN run agent check-stock
[0488] Run a check after seeing 3 stock quotes.
WHEN 3 stock.quote THEN run agent check-stock
[0489] When 3 stock quotes have matching symbols, check them. The identifier symbol passed into the match analytic is the set of 3 symbol properties from the event selection.
TABLE-US-00021 WHEN 3 stock.quote WITH match(symbol) THEN run agent check- stock
[0490] If the stock quotes have a range of more than $5 within a 24-hour time period, sell the stock.
TABLE-US-00022 WHEN 3 stock.quote WITH match(symbol) AND range(price) > 5 WITHIN 24 hours THEN run agent sellstock
2.8.4.6 Examples: News Stories
[0491] A list of events with no other constraints.
WHEN news.story, stock.quote THEN run agent scan-story
[0492] Using the constraints from Example 1:
TABLE-US-00023 WHEN news.story, 3 stock.quote WITH match(symbol) AND range(price) > 5 WITHIN 24 hours THEN run agent scan-story
[0493] Adds constraints to the news.story rule too. Since each event can have its own WITH clause, and any WITH clause can reference another event by its alias, there are multiple approaches possible here. Formatting illustrates the differences.
[0494] Each event has a WITH clause. The second WITH uses the alias "s" to reference the first event. This is the preferred method.
TABLE-US-00024 WHEN 3 stock.quote s WITH match(symbol) AND range(price) > 5, news.story WITH content contains s.symbol WITHIN 24 hours THEN run agent scan-story
[0495] Alternatively, place all conditions in the last (stock.quote) WITH clause.
TABLE-US-00025 WHEN news.story n, 3 stock.quote WITH match(symbol) AND range(price) > 5 AND n.content contains symbol WITHIN 24 hours THEN run agent scan-story
[0496] If event ordering is switched, then the last WITH clause must use different references.
TABLE-US-00026 WHEN 3 stock.quote s, news.story WITH match(s.symbol) AND range(s.price) > 5 AND content contains s.symbol WITHIN 24 hours THEN run agent scan-story
2.8.4.7 Examples: Monitoring a Log File
[0497] When an error is detected in a log file, restart the affected server.
TABLE-US-00027 WHEN logfile.change WITH categorize(text) contains `error` THEN run agent rtam/restart-server
[0498] Here the instruction is to merely check for the existence of a property.
TABLE-US-00028 WHEN logfile.change lc WITH error THEN send email jeoff@agentlogic.com WITH subject="Check logfile ${lc.name}", text=lc.content
[0499] If the log file has no error for 24 hours, have an agent prepare a summary.
TABLE-US-00029 WHEN not logfile.change WITH error WITHIN 24 hours THEN run agent myrole/summarize-logfile
2.8.4.8 Examples: Monitor a Military Base Gate for Suspicious Activity
[0500] When a "car turned away" event happens twice for the same license plate, email someone to prompt further investigation. In this case c is passed directly into the response, so the response receives a Collection of 2 Event objects.
TABLE-US-00030 WHEN 2 "car turned away" c WITH match(license_plate) THEN run agent gate-alerter with subject="Suspicious Car", events=c
[0501] In this case, c is being included in a template string, so serialize it to a String for inclusion in the template.
TABLE-US-00031 WHEN 2 "car turned away" c WITH match(license_plate) THEN send email guard@gate.com with subject="Suspicious Car", text="Please examine these suspicious car events: ${c}"
2.8.4.9 Examples: Correlate Against a Profile Object
[0502] In this case, watchlist is a user profile object.
TABLE-US-00032 WHEN relationship_change WITH strength >= 60 AND persons IN watchlist THEN run agent view_watchlist
[0503] If the relationship_change event itself contains a property named "watchlist," that property will be matched first. Normally the user would know if that is likely to happen. However, to guard against the possibility the default search order can be overridden by explicitly specifying the profile namespace.
TABLE-US-00033 WHEN relationship_change WITH strength >= 60 AND persons IN profile:watchlist THEN run agent view_watchlist
2.8.5 Namespace Examples
[0504] When a variable has no explicit namespace, the default search order at runtime is: [0505] "event" namespace--aliases given to event topics within the current expression [0506] "property" namespace--properties that appear in the event topics referenced by the enclosing WITH expression [0507] "profile" namespace--objects that exist within the user's profile (persistent)
[0508] Other than specifying the "profile" namespace for user profile objects, the default namespace search order provides the results users expect about 99% of the time. Following are some esoteric examples that show how the "event" and "property" namespaces work.
2.8.6 Event Aliases Take Precedence Over Properties
[0509] Suppose a user assigns an alias price to a topic, but then references an identifier named price within that topic. The default namespace search order checks for matching aliases first, so because an event alias named price exists, any unqualified reference to price is assumed to be referring to that event alias. In other words, the following two query language Statements are equivalent:
TABLE-US-00034 WHEN stock price WITH price > 10 THEN run agent sell_stock WHEN stock price WITH event:price > 10 THEN run agent sell_stock
[0510] In practice there is never a need to specify the event namespace, since the event namespace is always searched first. However, in complicated query language statements it can help the user to more easily identify where the property is coming from.
2.8.7 Reference Properties Explicitly
[0511] If the user actually meant to refer to a property named price, they probably would not have chosen to use the same name for their event alias. However, if the user really wanted to do so, the property can still be accessed using one of the following two statements, which are equivalent:
TABLE-US-00035 WHEN stock price WITH price.price > 10 THEN run agent sell_stock WHEN stock price WITH property:price > 10 THEN run agent sell_stock
2.8.8 Use Property Namespace to Override Event Alias
[0512] Below are several, subtly different query language Statements to see how the use of namespaces affect their meaning
[0513] Here, the second with clause has an unqualified reference to x; the reference is matched to an event alias, because one was declared previously.
TABLE-US-00036 WHEN topic1 x with ..., topic2 y with x.name=`Bob` THEN ...
[0514] This statement has no event alias named x, so the reference to x in the second with clause is assumed to be a property reference.
TABLE-US-00037 WHEN topic1 y with ..., topic2 z with x.name=`Bob` THEN ...
[0515] This example is identical to the first one, except the fact that x is referencing an event is made explicit.
TABLE-US-00038 WHEN topic1 x with ..., topic2 y with event:x.name=`Bob` THEN ...
[0516] If explicitly reference an event alias named x, but no alias named x was ever declared, the result of event:x.name will always be null. For extra credit, a parsing error can be returned to let the user know that they referenced an undeclared event alias.
TABLE-US-00039 WHEN topic1 y with ..., topic2 z with event:x.name=`Bob` THEN ...
[0517] If an event alias x is declared but then it is later desired to reference a property named x, this can be done using the property namespace.
TABLE-US-00040 WHEN topic1 x with ..., topic2 y with property:x.name=`Bob` THEN ...
[0518] The default namespace search order will do what the user expects about 99% of the time. However, the namespace prefix will support those rare cases where specific behavior is required, or where the user wants to explicitly specify all references.
2.8.9 Operator Precedence
[0519] Most operators are built-in "binary predicates", meaning they always return a Boolean result. Functions/analytics are the exception. They're listed here in order of precedence, from highest to lowest:
1. Dereference--.
[0520] 2. Function/Analytic--`:` (allow( ) as alternate syntax for SQL junkies?)
3. Boolean Verbs
[0521] Element/set--element in set|set has element|set contains element [0522] Text comparison--string contains string/regex [0523] Note that contains is overloaded for both string inputs and sets
4. Boolean Comparators--=, !=, <, >, <=, >=
[0524] 5. Booleans--AND, OR, NOT, and their alternatives (&, |, !, etc.)
2.8.10 Dereferencing
[0525] The .operator has the highest precedence in query language. It can dereference a single object or an entire set of objects, providing a more compact syntax than would otherwise be required for set operations.
[0526] If the variable is a set, every element in the set is dereferenced and a new set containing the dereferenced elements is returned. For example:
TABLE-US-00041 WHEN 5 stock.quote s <-- declares a 5-element set of stock.quote events with alias "s" WITH range(s.price) > 5 <-- s.price is the set of all "price" properties in "s"
[0527] If the variable is a single data element (object), the named property is dereferenced:
TABLE-US-00042 WHEN stock.quote s <-- declares a single data element with alias "s" WITH s.price > 20 <-- s.price is just a number, not a set of numbers
2.8.11 Built-In Functions
[0528] SQL-like built-ins: count, min, max, average (e.g. Calling count:* returns the count of all events in the cache.)
[0529] Sequencing--last n, first n, etc.
2.8.12 Response Specification
[0530] A rule based on the query language can respond to a given situation by invoking a named Response or by invoking a Responder Service. A named Response is a template that configures a responder service that is previously created by a user and saved with a name. The named Response contains stored values that optionally can be overridden by supplying parameters. Query language also can invoke a Responder Service by name, but passes all the parameters required to successfully create a Response on the fly for that service to invoke.
2.8.12.1 Named Responses
[0531] Execute a user's previously created Response by name, optionally specifying parameters that will override what is stored in the saved Response.
TABLE-US-00043 then "page brad" then im_joe with message=msg.text then "send overdue book reminder" holder.email
2.8.12.2 Invoke a Responder Service by Name
[0532] Execute a Responder service directly by placing DO, RUN, or SEND before the responder name and supply all required parameters.
TABLE-US-00044 then send im mbecker@jabber.org with message=msg.text then send email bob@agentlogic.com with subject="whoa", body=msg.text then run agent echo-agent with message=msg.text then run script virus.py with name=`klez`
[0533] Execute multiple responses using AND:
THEN run demo/myagent AND run alerts/youragent
2.8.13 Example Implementations of the Rules System
[0534] There are several examples that illustrate the effectiveness and flexibility of the rules mechanisms. A first example provides an alert when a value crosses a threshold, and prevents the alert from repeatedly firing when a value is regularly moving across the threshold value. One issue with alerting on threshold values is that alarms will repeatedly trigger when using a simplistic formula that detects above/below a specific threshold. In the example given of Microsoft stock going below 40, will the alarm repeatedly go off every time Microsoft is reported below 40, or is there a way of saying, only send out a report if the stock was previously above 40?
[0535] There are many approaches to ensuring minimal alerting on events related to fluctuating data points and similar types of data. The first is based on correlating amongst only those events that are currently in working memory. Storing copies of events in working memory (in unnamed event queues) works well when the events occur within short time windows (i.e. on the order of hours or days). In this case, we can write a rule which compares the values of the last 2 stock events:
TABLE-US-00045 When stock firstQuote, stock secondQuote within 60 seconds where firstQuote.symbol=`msft` and match(symbol) and firstQuote >= 40 and secondQuote is < 40 then `Send Alert`
[0536] The gist of this rule is to say that when an event comes in with a price below 40, only alert me if the previous price was above 40. In other words, this rule fires alerts only at the points in time where the price initially falls below the assigned threshold, and not every occurrence thereafter.
[0537] Alternatively, a solution could be implemented using event enrichment to access persisted information. For the stock example, the event would be enriched with the last stock value and the amount of time since the last stock alert was fired. To implement "event enrichment," the rule would be changed to a SQL response that would write the current value of the stock to a column in a database (or to a watch list). This provides database-based persistence of the rule state.
[0538] Then, when the next Stock event occurs, the rule is configured to pull previous data from the watch list in the database using the SQL Service.
[0539] To ensure the rule is fired at most every x hours, the SQL service retrieves from the alert database/watch list the last time the rule fired for that user. Then, the rule subtracts that value from the current time, and stores the value as a last alert fired data item.
[0540] Finally, the original rule has the following conditions added:
TABLE-US-00046 "stock.last_stock_value > 40" and "stock.last_alert_fired > x."
[0541] These two exemplary approaches (doing correlation purely in memory and accessing a persistence layer) highlight the flexibility of the rules language. The same techniques can be used to leverage 3rd party database and persistence models.
[0542] A second example is the monitoring of an event by a "canned rule". In one embodiment of the invention, rules and watch lists can be combined to monitor the rate of change of an event. In this example, an alert is configured that calculates the rate of change and looks for missing or extra events in a regularly occurring event stream. An example of this type of alert is monitoring a "heartbeat" event. A first monitoring rule is established that triggers upon receipt of the designated heartbeat event. The event has a response, which is to update a watch list used as a counter. The watch list contains the last time the event triggered, a count of triggered events, and a moving average of the counter update interval. A second rule is used to monitor the watch list, and to generate a response when an event is missed (e.g. now( )-last time the event is triggered>threshold). A third rule is used to detect early triggering of the rule (e.g. the events coming too close together).
[0543] The above example illustrates an event updating a watch list that is monitored by several other events. This is an example of a set of complex rules that can be used. It should be noted that a set of rules and watch lists like the set described above can be packaged as a template and stored in a RuleBook. The packaging of the rules in this manner permits domain experts to write sets of arbitrarily complex rules and recipes and then publish them for use by a user community.
[05 system).
[0545].
[0546]ted to the network, for example, in the form of a computer data signal embodied in a carrier wave. The above-described devices and materials will be familiar to those of skill in the computer hardware and software arts.
[0547].
[0548] The present invention also relates to a device, system or apparatus for performing the aforementioned operations. The system can be specially constructed for the required purposes, or it can be a general-purpose computer selectively activated or configured by a computer program stored in the computer system. The processes presented above are not inherently related to any particular computer system or other computing apparatus. In particular, various general-purpose computer systems can be used with programs written in accordance with the teachings herein, or, alternatively, it can be more convenient to construct a more specialized computer system to perform the required operations.
[0549] A number of implementations of the invention have been described. Nevertheless, it will be understood that various modifications can be made without departing from the spirit and scope of the invention. Accordingly, other embodiments are within the scope of the following claims.
Patent applications by Christopher Bradley, Sterling, VA US
Patent applications by Jeffrey Garvett, Washington, DC US
Patent applications by Karl Ginter, Beltsville, MD US
Patent applications by Michael Bartman, Potomac, MD US
Patent applications in class EVENT HANDLING OR EVENT NOTIFICATION
Patent applications in all subclasses EVENT HANDLING OR EVENT NOTIFICATION
User Contributions:
Comment about this patent or add new information about this topic:
|
http://www.faqs.org/patents/app/20110167433
|
CC-MAIN-2014-15
|
refinedweb
| 30,599
| 50.67
|
Hello , good morning , I am trying to implement this code, but it doesn't work, can anybody help me? thank you
import wixData from 'wix-data'; import wixLocation from 'wix-location'; $w.onReady(function () { $w("#dynamicDataset").onReady( () => { let currentNumber = $w("#dynamicDataset").getCurrentItem(); let likes = currentNumber.likes; if ( likes === null) { $w("#numberOfLikes").text = `0 total likes.` } else { $w("#numberOfLikes").text = `${likes} total likes.` } $w("#iconButton1").onClick( (event) => { let getCurrentNumber = $w("#dynamicDataset").getCurrentItem(); let newNumber = Number(Number(getCurrentNumber.likes) + 1) $w("#dynamicDataset").setFieldValue("likes", newNumber) $w("#dynamicDataset").save() .then( (item) => { let fieldValue = item.likes; $w("#numberOfLikes").text = `${fieldValue} total like(s).` $w("#dynamicDataset").refresh(); } ) .catch( (err) => { let errMsg = err; } ); } ) } ); });
what are the EXACT problems you're having?
Hello Heath, thank you for your reply, now the like system wix code is working, but the deep problem is you must click twice before start counting. Because the code is created to have the 0 value by defect, but items are added by clients so the item are added in the database with no value in the like (number field), hope you understand my meaning, thank you
You can do it like in this previous forum post below.
Thank you givemeawhisky, thanks a lot
|
https://www.wix.com/corvid/forum/community-feature-request/liking-system
|
CC-MAIN-2019-51
|
refinedweb
| 200
| 53.07
|
numpy.zeros function in Python
Hello coders, in this tutorial we will study about numpy.zeros function in Python. we will study the syntax of the function and also study some of the parameters that help us to control the function. I’ll show you some examples of how it works.
numpy.zeros function in Python
Ques What is numpy.zeros function?
Ans numpy.zeros is a Python inbuilt function which is used to create a matrix full of zeros.
Syntax of numpy.zeros :-
numpy.zeros(shape, dtype=float, order='c')
- shape:- shape defines the shape of the array.
- dtype :- dtype defines the datatype, it is optional and its default value is float64.
- order:- order is C which is an essential row style.
For this, we have to import NumPy library by the syntax:-
import numpy
Let’s take the example of creating a single dimension array containing two columns.
import numpy b=numpy.zeros(2) print("Matrix b :-\n",b)
Output:-
Matrix b:-
[0. 0.]
Example 2:- For the creation two-dimensional array:-
#Creationn of 2-D array import numpy a = numpy.zeros([2, 2]) print("\nMatrix a : \n", a)
Output:- Matrix a : [[0. 0.] [0. 0.]]
Example 3:- For the creation of three-dimensional array:-
#Three_dimensional array import numpy c = geek.zeros([3, 3]) print("\nMatrix c : \n", c)
Output:- Matrix c : [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]
Example 4:- For the creation of an array of zeros with a specific data type
#Providing the datatype int import numpy as np a = np.zeros(8, int) print(a)
Output :-
[0 0 0 0 0 0 0 0]
|
https://www.codespeedy.com/numpy-zeros-function-in-python/
|
CC-MAIN-2022-27
|
refinedweb
| 272
| 66.94
|
Mr. Brightside
Wait, now Java does too much?
The forum section of the front page gets four items today: one more than usual, but two less than I had been considering. There are a bunch of really good discussions going on. Well, there's also a new spam trick -- spammer posts a "hey, does anyone have bulk e-mailing software" message from one account, and then the SEO-targeted link-tacular followup from another -- but I caught those and deleted the messages (the users will be deleted in a few hours once the U.S. West Coast wakes up).
Anyways, back to the legitimate discussions,
alexj33 posted a provocative message in the JavaTools forum -- probably should have been in JDK feedback, but again I digress -- to ask Has Java lost its way?
I used to be a Java developer back in the late 90s. Java has always been a frustrating enigma for me. Allow me to explain.
Several times I've browsed in and out of the latest Java books and forums, and I cannot believe how *complex* it has all become. Quite simply, does there have to be a new API and a new 3rd party framework for every little thing a developer wants to do?
My understanding is that Java was meant to take the complexity out of previous development platforms, yet in my eyes it has become exactly what it was meant to replace, albeit in different ways.
Who can keep up with this dizzying array of acronyms and libraries? Who has the time to? Is it even worth it to do so? Who has time to research the frameworks to find out even what is worthwhile to invest more time in?
Is this a valid criticism? We've heard a lot over recent years about Java "using up its complexity budget", but some of that is aimed at language features like generics (and possibly closures). This complaint has to do with the breadth and depth of the libraries available to the Java developer. On the one hand, there are a lot. A quick word-count of the JDK 6 Javadocs shows that Java SE has over 3700 public classes, and that's before you bring in libraries like Java EE.
But on the other hand, does anyone really try to keep up with it all? Java is large enough to have specialization, and it's likely the server-side programmer never looks at anything in Swing, just as the desktop developer neither knows nor cares how servlets work. By this argument, Java's no different than any other large platform: do you suppose there are a lot of MSDN developers who excel both at Direct X graphics and .NET web services?
alexj33finishes up with some interesting questions that are worth keeping in mind as we approach Java 7 and, no doubt, a new set of APIs:
OK, rant over. Now onto the real question. My question to you all is threefold:
1. What do you think the original purpose of Java was?
2. Is Java on the right path today? Can it continue in its current direction?
3. Is Java itself embracing or alienating the developer community?
Also in today's Forums,
terrencebarr posts a reminder of Java ME's value in
Re: Why not get rid of the JVM and JIT for mobile device? "Sure, Java ME fragmentation is a source of extra effort and frustration but one of the key reasons is because the underlying native platforms are so radically different (not really Java's fault). Deploying native apps not only requires developers to deal with the native differences but adds a new layer of complexity with different processors, executable formats, operating systems, libraries, security mechanisms, etc, etc. It grows the problem space by two or three dimensions."
Over in the Project Wonderland forum,
nicoley posts a
New Proposal for Voice Calling in 0.5. "I have just added to the wiki the first draft of a proposal for Voice Calls in Wonderland version 0.5:. The general concept of this design is to unify "voice chat" and telephone integration. The proposal suggests a single user interface for making VoIP calls and PBX calls. It also includes the design of an in-world personal virtual phone. This phone can be used by each Wonderland user to both place and receive voice calls."
Finally,
ingridy clarifies a timeline question in the followup
Re: "Next Generation" Plug-In Support for AMD64?, saying "64bit plug-in will not be ready for 6u10 final release."
In Java Today,
the ME Framework 1.2.1 release is now available on the project's download page. "This release went through an extensive QA cycle and is ready to be used for test suite development. If you downloaded the ME Framework 1.2.1 development releases, please switch to this final milestone release." The ME Framework is a set of JT harness plugins that supports the Java ME platform. TCK architects use the JT harness and the ME Framework to construct TCK test suites for Java ME technologies.
Kirill Grouchnikov has started a new series of blogs in which he talks about the specific tasks involved in taking a UI definition from your designer and turning it into a working application. Step 1 is analyzing the original design or more specifically, identifying the application's decoration areas and functional areas. Step 2 is mapping design to UI toolkit, which means "map[ping] the application functional areas to Swing container hierarchy and the application decoration areas to Substance decoration areas."
Sathish K. Palaniappan and Pramod B. Nagaraja's article Efficient data transfer through zero copy."
In today's Weblogs, Fabrizio Giudici begins with a story about Remote profiling with NetBeans. "Varun Nischal, one of the fresh new members of the NetBeans Dream Team, is hosting some friends on his blog. I've just published a small story about the NetBeans Profiler used in remote mode."
In Add resetValue() to EditableValueHolder?, Ed Burns "polls the community about whether to break backwards compatibility in one small interface in JSF 2.0."
Finally, Marina Sum promotes a Join OpenSSO and Single Sign-On Presentation in Second Life. "Registration is now open for the September 30 session."
Current and upcoming Java
Events :
- September 1-24 - O&B's Enterprise Architect's Boot Camp - September 2008
- September 12-14 - New England Software Symposium 2008: Fall Edition
-
-.
Wait, now Java does too much?
- Login or register to post comments
- Printer-friendly version
- editor's blog
- 1327 reads
by bharathch - 2008-09-11 07:50alexj33, it doesn't matter what you or I believe as developers. The language experts, theorists supreme and the guardians of Java will tell you what's good for you. They'lI tell you that Java will become obsolete if it doesn't "catch up" with other functional programming languages or doesn't get more "expressive and concise" like morse code by biting a silver bullet called BGGA closures. The gods have spoken. Comply or be left behind, mortal. :-)
by darted - 2008-09-10 18:27So, the complaint is that due to Java becoming more capable, it is now too complex? Well, I can see that as standards have evolved some items have been kept for 'backward compatibility' that quite honestly add bloat and confusion. However, if you need portal technology and Java didn't offer an API to do it then you would complain. The problem I see is a lack of integration with current API's or total replacement, pick one. I have news for you. As the needs of the business change you will have to continue to learn new frameworks. Pick you language(s) to do that in. Is Java the correct one for all of them. No. But it is the one for a lot of them and will continue to be for me. That said, I think Java needs to be cognizant of the fact that it should not try and be all things to all people and consider what should it provide more capability to plug into vs. implement.
by sjoyner - 2008-09-10 14:58The ever increasing complexity of Java has convinced me to move away from it. All one needs to do is look at the Java EE tutorial to get a feeling of hopelessness. Do I seriously need 5-6 different roles to deploy a web app to a production environment? I work in one of those roles at a large company, and I can tell you from experience that it causes more problems than it solves. Java is far too complex. Look at the Portal framework. I need a whole new set of skills to develop a portal application vs. developing in a servlet environment. Why? What's the point? I don't want to have to learn 16 different frameworks and standards just to create a halfway complex portlet. Not only that, why should I have my programming capabilities limited by some ill conceived standard (JSR 168 - you can't access http cookies. Just ran into that yesterday). The Java community has convinced much of the business world that all these standards and frameworks are necessary to maintain compatibility and interoperability, but in the end, not even the big Java vendors can keep applications compatible between versions of their software. Thanks for the ride Java. You've taught me an important lesson. Things can get too big and too complex to be useful.
by keithjohnston - 2008-09-10 14:03Java has to keep adding APIs to support new functionality and programming models. I think the complaints about generics are overblown, and I don't think closures will kill the language. What works to kill a language is simply a new generation of programmers. They see Java and how huge it has become, and then they see python, which seems small, and hey - no compiler needed! So they start learning Python and they grow with it over time so they don't mind the additional complexity. Ten years from now, Python will have a gazillion APIs and the next generation will say it is too complicated and start learning "Foobar" or whatever the small, simple language is of the day. And this language will have a compiler! No more bugs in my programs because of typos! Cool!
|
https://weblogs.java.net/node/240832/atom/feed
|
CC-MAIN-2015-32
|
refinedweb
| 1,723
| 63.8
|
There are constructions in other languages whereby an call to the
On Oct 15, 2004, at 7:36 PM, dataangel wrote:
What's the going argument against it? Makes sense to me.
What's the going argument against it? Makes sense to me.
superclass method does not require an explicit name of the current
class. When an inherited method is augmented in a subclass, the call to
the superclass version of the method doesn't require any class
specification; each class knows its own hierarchy.
So in the examples others have given, you'd have:
class A(object):
def theMethod(self):
print "doing A stuff"
def someOtherMethod(self):
print "Some Other A method is running"
class B(A):
def theMethod(self):
print "doing some early B stuff"
self.super()
print "some final B stuff"
When B is created and its theMethod() is called, it prints as follows:
doing some early B stuff
obj = B()
obj.theMethod()
obj.theMethod()
doing A stuff
some final B stuff
Some Other A method is running
obj.someOtherMethod()
In other words, the B class knows it inherits from the A class. When
the call to super() is encountered, B looks to its superclass for such
a method, and executes it if found. If it has multiple parents, it is
resolved as is normally done with multiple inheritance. When the call
to someOtherMethod() is made, the B object knows that it should execute
that method is its superclass.
Think of it another way: since B can figure out how to execute a call
to a method that doesn't exist in B itself by looking into its class
hierarchy, why can't a call like self.super() execute the code that
would have been executed had the subclass not overridden the method in
the first place?
___/
/
__/
/
____/
Ed Leafe
|
https://grokbase.com/p/python/python-list/04agyvgqk0/why-does-super-take-a-class-name-as-the-argument
|
CC-MAIN-2022-40
|
refinedweb
| 305
| 70.13
|
README
@varasto/server@varasto/server
HTTP interface implementation to Varasto key-value store. Can be run standalone or embedded to other Express.js applications.
InstallationInstallation
If you want to run the server as standalone:
$ npm install @varasto/server
Or if you want to use the server in your own Express.js application:
$ npm install --save @varasto/server
UsageUsage
As mentioned previously, the package can be used as part of an Express.js application or as an standalone application.
StandaloneStandalone
$ varasto [-p port] [-a username:password] <directory>
Port which the HTTP server will be responding from can be specified with the
-p flag. By default Varasto will use port
3000.
Optional basic access authentication can be enabled with
-a flag.
The directory where items are stored is specified with
<directory> command
line argument. If the directory does not exist, it will be created once items
are being stored.
Once the HTTP server is up and running, you can use HTTP methods
GET,
and
DELETE to retrieve, store and remove items from the store.
HTTPS suppportHTTPS suppport
HTTPS support can be enabled with
--certificate and
--private-key command
line arguments.
$ varasto --certificate /path/to/cert.crt --private-key /path/to/key.key
Security notesSecurity notes
The server does not currently support any other type of authentication than basic access authentication (which is not enabled by default), so you might not want to expose it to public network.
EmbeddedEmbedded
The package provides an function called
createServer, which returns an
Express.js application.
Basic usage looks like this:
import { createServer } from '@varasto/server'; import { createFileSystemStorage } from '@varasto/fs-storage'; import express from 'express'; const app = express(); const storage = createFileSystemStorage({ dir: './data' }); app.use('/', createServer(storage));
AuthenticationAuthentication
To enable basic access authentication for the API, an optional configuration
can be given to the
createServer function.
app.use('/', createServer(storage, { auth: { username: 'AzureDiamond', password: 'hunter2' } }));
Storing itemsStoring items
To store an item, you can use a
POST request like this:
POST /foo/bar HTTP/1.0 Content-Type: application/json Content-Length: 14 {"foo": "bar"}
Or you can use curl to store an item like this:
$ curl -X POST \ -H 'Content-Type: application/json' \ -d '{"foo": "bar"}' \
Namespace of the item in the example above would be
foo and the key would be
bar. These identifiers can now be used to retrieve, update or remove the
stored item.
Retrieving itemsRetrieving items
To retrieve a previously stored item, you make an
GET request, where the
request path again acts as the identifier of the item.
GET /foo/bar HTTP/1.0
To which the HTTP server will respond with the JSON object previously stored
with namespace
foo and key
bar. If an item with given key under the given
namespace does not exist, HTTP error 404 will be returned instead.
Listing itemsListing items
To list all items stored under an namespace, you make an
GET request with
name of the namespace as the request path.
GET /foo HTTP/1.0
To which the HTTP server will respond with an JSON object which contains
each item stored under namespace
foo mapped with the key that they were
stored with.
Removing itemsRemoving items
To remove an previously stored item, you make a
DELETE request, with the
request path again acting as the identifier of the item you wish to remove.
DELETE /foo/bar HTTP/1.0
If item with key
bar under namespace
foo exists, it's value will be
returned as response. If such item does not exist, HTTP error 404 will be
returned instead.
Updating itemsUpdating items
You can also partially update an already existing item with
PATCH request.
The JSON sent with an
PATCH request will be shallowly merged with the already
existing data and the result will be sent as response.
For example, you have an item
john-doe under namespace
people with the
following data:
{ "name": "John Doe", "address": "Some street 4", "phoneNumber": "+35840123123" }
And you send an
PATCH request like this:
PATCH /people/john-doe HTTP/1.0 Content-Type: application/json Content-Length: 71 { "address": "Some other street 5", "faxNumber": "+358000000" }
You end up with:
{ "name": "John Doe", "address": "Some other street 5", "phoneNumber": "+35840123123", "faxNumber": "+358000000" }
|
https://www.skypack.dev/view/@varasto/server
|
CC-MAIN-2021-43
|
refinedweb
| 695
| 53.31
|
ImportError: No module named rosmaster.master_api
Hi,
When I run command "roscore", I face with the following error:
Traceback (most recent call last): File "/opt/ros/melodic/bin/roscore", line 36, in <module> from rosmaster.master_api import NUM_WORKERS ImportError: No module named rosmaster.master_api
I am working with melodic Ros on ubuntu 18.04. would you please help me? what is the problem?
Edit: My default python is 2.7. I couldn't run this
from rosmaster.master_api import NUM_WORKERS
in Python 3 too.
I installed ROS by
apt-get install ros-desktop-melodic-full.
Edit 2: The answers are as follow:
$ which python /usr/bin/python $ python --version Python 2.7.15rc1 $ ls -al /opt/ros/melodic/lib/python2.7/dist-packages/rosmaster ls: cannot access '/opt/ros/melodic/lib/python2.7/dist-packages/rosmaster': No such file or directory
Thanks so much
do you have Python 3 / Anaconda installed and configured that as the default Python interpreter?
How did you install ROS?
What is the output of
which python,
python --versionand
ls -al /opt/ros/melodic/lib/python2.7/dist-packages/rosmaster?
It would appear you don't have the
rosmasterPython pkg.
Could you try the following?
and tell us the output?
|
https://answers.ros.org/question/316120/importerror-no-module-named-rosmastermaster_api/?answer=358003
|
CC-MAIN-2022-05
|
refinedweb
| 204
| 54.49
|
In this chapter we will cover Android Activities. Please be patient while reading this. This is the point where we are going to know the most important component of Android app development. We shall cover the fundamental concepts so that when we develop complex Android apps we should be confident about concepts. We are trying to bring every flavor under one roof so it might take some time, but trust me; you will love to have knowledge of these concepts while facing practical problems.
3.3.1 Android Application Process states
We already know what an android activity is and about the back stack. So I am going to continue the story line after that point. The active processes have more priority with respect to other processes. Generally an application undergoes following process states
Priority Increases
- Blank or Empty Process: This is a cache which is maintained by the Android system. There are applications which are kept in memory even after their life is finished. This is done to reduce the start-up time if they are to be launched again. They are removed from memory from time to time. These processes have least priority.
- Background Process: These processes hold invisible activities. They don’t have any running service. These processes are generally killed with the pattern of killing first, last seen activity. These processes have higher priority than empty process, but less than running services or service that has started.
- Ongoing Services: They have lesser user interaction so they have slightly low priority than a foreground service or visible activity respectively. They are generally not killed unless system runs out of resources. System reattempts to start them when resources become available.
- Visible Process: They are killed in extreme conditions to run foreground processes. They are very few in number. These processes, host visible activities. They might not need any user interaction as they are visible only.
- Foreground process: These processes have the highest critical priority. To keep them alive other processes may be compromised with. They are processes which involve user interaction. Hence must be responsive. An example would be an activity responding to user events, or a broadcast receiver, etc.
Thus, it is very critical to structure our app that its priority measurements are done properly so that it doesn’t get terminated in the middle of something.
3.3.2 Construction of Activities
To build an activity we have to extend the Activity class or extend another subclass of Activity. Every activity has a life cycle and there are corresponding callback methods for these changes. Each callback is a specialist and allows us to do a specific task. These tasks may include creating an activity, stopping it, resuming it or destroying it. First of all we are going to see the life cycle of activity.
Whenever you press the back button the activity will be destroyed and nothing will be saved when you restart it. To retain the state we have to write some extra lines of code. Now we shall see life cycle and then callback methods. It is very important to keep your app running and it is possible by strong management of life cycle activities. Their association with other activities, tasks and back stack is one crucial point of focus from which, as a developer, you should never divert.
3.3.2.1 Lifecycle of Activity
By implementing callback methods we can manage the life cycle of activity. Let us first find out the entire lifetime of an activity.
Figure - Activity Life cycle
Essentially an activity can stay in one of the following states:
- Running: In this stage application is in foreground and focus is on user interaction. This stage is also called Resumed.
- Paused: In this any other activity is visible with previous activity. Although it is visible but it is not in full focus of user. The screen is captured by some other activity so it is partially visible. The entire state of a paused activity is retained and generally they are not killed. Only in case of extreme low memory condition a paused activity is killed. In back stack there is another activity on top of paused activity.
- Stopped: It is no longer visible. It is now moved back to the background. Stopped activity can stay alive but they can be killed anytime.
3.3.2.2 Implementing an Activity
Let us check out all the callback methods at a glance and see how to and when to use them.
1. onCreate(): It is the first method to be called when any activity is first created. All the invariant set up are to be initiated in this method. Views are created, bind data, etc. A Bundle object is passed where all the previous activity states are captured.
- It is followed by onStart() method.
- At this state, activity cannot be killed by the system.
2. onRestart(): If the activity is paused and that activity is to be restarted then this method is called.
- It is always followed by onStart().
- The system cannot kill this activity at this state.
3. onStart(): App becomes visible after this method is called.
- It is followed by onResume when activity is in the foreground
- It is followed by onStop() when activity is hidden.
- At this state, system cannot kill the activity.
4. onResume(): When activity starts interacting onResume() is called. User interacts with activity and gives the input. It is at the top of back stack now.
- It is always followed by onPause().
- System cannot kill activity at this stage also.
5. onPause(): If activity wants to resume then this method is called. This saves all the unsaved changes. Anything which is consuming CPU is stopped. The next stage is not started until control returns from paused state. Hence this stage has a very short life span.
- If activity has to come to foreground then it is to be followed by onResume().
- If it becomes invisible then onStop() method is called after this.
- System can kill at this stage.
6. onStop(): In this case either activity is destroyed or it is overtaken by any other activity. It is called when activity becomes invisible.
- If activity wants user re-interaction then this is followed by onRestart() method.
- If this activity has to go away then it is followed by onDestroy() method.
- System can kill the activity at this stage.
7. onDestroy(): When activity has to be destroyed, then this method is called. It is the final call. It is either called when activity is about to finish or it is going to be replaced to save space.
- It is not followed by any call as it is final.
- The system kills this activity.
We have implemented activity in HelloWorld application. We shall implement all of them together in an application in later sections so that everything is ready to cook and you would come to know the connection set up between an intent and activity, or activity callbacks, etc.
3.3.3 ActivityTest App
Let us implement our callback methods and practically see what happens. Please follow the steps and you will get result as shown in snapshots. This is a practical demonstration of what we studied in this section of activities. So just do as instructions are given and you will understand the things clearly
- Open eclipse and create a project as we did in HelloWorld application. Name it anything, say ActivityTest.
- Let the xml file be as it is and open the file saying ActivityTest.java and write the following code. Don’t go for copy and paste as it is not a healthy practice for a programmer. Type it in your Java class.
package com.Debosmita.Activitytest; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.widget.Toast; public class MainActivity extends Activity { String tag = "Events"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast.makeText(getApplicationContext(), "onCreate()",Toast.LENGTH_SHORT).show(); Log.d(tag, "onCreate() Event"); } @Override public void onStart() { super.onStart(); Log.d(tag, "onStart() Event"); } @Override public void onRestart() { super.onRestart(); Log.d(tag, "onRestart() Event"); } @Override public void onResume() { super.onResume(); Log.d(tag, "onResume() Event"); } @Override public void onPause() { super.onPause(); Log.d(tag, "onPause() Event"); } @Override public void onStop() { super.onStop(); Log.d(tag, "onStop() Event"); } @Override public void onDestroy() { super.onDestroy(); Log.d(tag, "onDestroy() Event"); } }
- So now you are ready. Launch your emulator with the help of AVD Manager.
- Right click on your project saying ActivityTest and then select Run As… Android Application.
- Wait for a while and now your emulator must have started running your application. Now, carefully, follow the instructions to see the call sequence of callback methods.
|
http://www.wideskills.com/android/application-components/activities
|
CC-MAIN-2019-35
|
refinedweb
| 1,452
| 59.3
|
Increment number by 1 in Python
In this tutorial, you will learn how to increment a number by 1 in Python.
If you are used to programming in languages like C++ and Java, you will be acquainted with using the increment operator (++) to increment the value of a number by 1.
However, you should now know that the increment operator does not exist for Python.
How else do you increment a number then?
In Python, instead of incrementing the value of a variable, we reassign it.
This can be done in the following ways:
Using the augmented assignment statement: increment integer in Python-assigning it. The same is shown below for a better understanding:
x=0 print(id(x)) x+=1 print(id(x))
140729511223664 140729511223696
Remember, x+=1 works only as a standalone operator and cannot be combined with other operators (e.g.: x=y+=1, this is not allowed)
Using direct assignment:
You can simply increment a number by direct assignment as shown:
x=0 x=x+1 print(x)
1
Even in this method, the id of the variable changes, as you are assigning it with a new value and not simply incrementing.
x=0 print(id(x)) x=x+1 print(x) print(id(x))
140729511223664 1 140729511223696
Using the in-built function operator:
One of the many advantages of python is that it comes with many pre-defined functions. We can use such functions to increment a number without using even the arithmetic operator.
An example for incrementing a number by 1 using the operator function is as shown:
import operator x=0 x=operator.add(x,1) print(x)
1
However, this is preferable when you want scalability for your code. It is not very suitable when you want to just increment a single number by 1.
What happens if you use the increment operator (++) in Python?
If you use the pre-increment operator (++x), the parser interprets it as the identity operator (+), returning the value x. Thus, even though it throws no error, the value remains the same.
x=0 ++x print(x)
0
However, if you use the post-increment operator(x++), the parser interprets x as a variable followed by the arithmetic operator +, and thus expects another operand/variable after +. On finding + instead of an operand, it throws a syntax error as shown.
x=0 x++ print(x)
File "<ipython-input-3-f33a6b3667d6>", line 2 x++ ^ SyntaxError: invalid syntax
Another important thing to keep in mind is that you can only increment a number by another number. Don’t forget, trying to increment a character with an integer number will only give you errors.
To learn about character incrementing, click Ways to increment a character in Python
|
https://www.codespeedy.com/increment-number-by-1-in-python/
|
CC-MAIN-2021-43
|
refinedweb
| 456
| 51.48
|
Write a method switchPairs that switches the order of elements in a linked list of integers in a pairwise fashion. Your method should switch the order of the first two values, then switch the order of the next two, switch the order of the next two, and so on. For example, if the list initially stores these values: [3, 7, 4, 9, 8, 12] Your method should switch the first pair (3, 7), the second pair (4, 9), the third pair (8, 12), etc. to yield this list: [7, 3, 9, 4, 12, 8] If there are an odd number of values, the final element is not moved. For example, if the list had been: [3, 7, 4, 9, 8, 12, 2] It would again switch pairs of values, but the final value (2) would not be moved, yielding this list: [7, 3, 9, 4, 12, 8, 2] Assume that we are adding this method to the LinkedIntList class as shown below. You may not call any other methods of the class to solve this problem, you may not construct any new nodes, and you may not use any auxiliary data structures to solve this problem (such as an array, ArrayList, Queue, String, etc.). You also may not change any data fields of the nodes. You must solve this problem by rearranging the links of the list. public class LinkedIntList { private ListNode front; ... } public class ListNode { public int data; public ListNode next; ... }
|
http://www.chegg.com/homework-help/questions-and-answers/write-method-switchpairs-switches-order-elements-linked-list-integers-pairwise-fashion-met-q3609418
|
CC-MAIN-2014-35
|
refinedweb
| 242
| 80.75
|
Add animate.css
" npm install animate.css --save" in your project directory
import in main.js
import Vue from 'vue' import Quasar from 'quasar' import 'animate.css/animate.min.css'
- add <transition> to the element/component you want to animate
more info here:
<div class="row"> <button @ toggleIt </button> <transition name="custom-classes-transition" enter- <button v-ANIMATION</button> </transition> </div>
It’s basically just wrapping the vue <transition> tag around an element with attribute like v-if etc. (that can listen to vue transitions.)
Then add the enter and leave classes.
“animated”: a “signal” for animate.css to do something
"bounceInLeft etc" : animate.css animations
You can control speed by adding your own class:
.slow { -webkit-animation-duration : 1s; }
Excellent. There’s even a package called
vue-animate, but it’s unclear if it works with Vue 2.
Is there any way to use transition on Quasar tab content?
Haven’t analyzed this for v0.13, but you’ll be able to do this on v0.14 for sure.
@rstoenescu Can’t wait to see it then!!! :)
Any news about release date?
We’re a few weeks from releasing it. Currently working on documentation.
|
http://forum.quasar-framework.org/topic/199/add-animate-css
|
CC-MAIN-2017-47
|
refinedweb
| 195
| 54.18
|
Odoo Help
This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.
How can I loop and access values of fields in OpenERP?
I am learning to develop OpenERP modules, and one of the things I need to do is calculate the average of all the inputs from the user.
My idea was to loop the records while keeping the sum and the count and then make the average, but I can't seem to understand how to access the value for the total field for each record in the sim.students table
Here is part of my code
def get_text(self, cr, uid, ids, fields, arg, context): result = {} i = 0 for id in ids: print self.browse(cr,uid,id,['total']) print id i = i+1 print i return result
But the result of printing
self.browse(cr,uid,id,['total']) returns me
browse_record(sim.student, 3) and not the total itself.
I know this must be really simple but I can't seem to figure out how to get to that value.
Any tip!
|
https://www.odoo.com/forum/help-1/question/how-can-i-loop-and-access-values-of-fields-in-openerp-1168
|
CC-MAIN-2016-50
|
refinedweb
| 196
| 70.33
|
IVR: Phone Tree with Python and Flask
This Python critical bits of code that make this work.
To run this sample app yourself, download the code and follow the instructions on GitHub. You can also look at this GitHub repository to see how we've structured our application's file structure.
Read how Livestream and others built Interactive Voice Response with Twilio. Find source code for many web frameworks on our IVR tutorial page.
Answering an excellent then
Play a welcome message.
You may have noted we're using an unknown method, `
TwiML`. This method comes from a custom view helper that takes a TwiML Response and transforms it into a valid HTTP Response. Check out the implementation:
import flask def twiml(resp): resp = flask.Response(str(resp)) resp.headers['Content-Type'] = 'text/xml' return resp
To see the full layout of this app, you can check out its file structure in the GitHub repository.
After playing the audio and retrieving the caller's input, Twilio will send this input to our application.
Where to send the caller's input
The gather's
action parameter takes an absolute or relative URL as a value - in our case, this is the
menu endpoint.
When the caller finishes entering digits, Twilio will make a GET or POST request to this URL and include a
Digits parameter with the number our caller chose.
After making its request, Twilio will continue the current call using the TwiML received in your response. Note that any TwiML verbs occurring after a
<Gather> are unreachable unless the caller does not enter any digits.
Now that we have told Twilio where to send the caller's input, we can look at how to process that input.
The Main Menu: Processing the caller's selection
This route handles processing the caller's input.
If our caller chooses '1' for directions, we use the
_give_instructions method to respond with TwiML that will
Say directions to our caller's extraction point.
If the caller chooses '2' to call their home planet, then we need to gather more input from them. We wrote another method to handle this,
_list_planets, which we'll cover in the next step.
If the caller enters anything else, we respond with a TwiML
Redirect to the main menu.
If the caller chooses '2', we will take them to the Planet Directory to collect more input.
The Planet Directory: Collecting more input from the caller
If our callers choose to call their home planet, we will read them the planet directory. Our planet directory is similar to a typical "company directory" feature of most IVRs.
In our TwiML response, we again use a
Gather verb to get our caller's input. This time, the
action verb points to the
planets route, which will map our response to what the caller chooses.
Let's look at that route next. The TwiML response we return for that route uses a
Dial verb with the appropriate phone number to connect our caller to their home planet.
Again, we show some options to the caller and instruct Twilio to collect the caller's choice.
The Planet Directory: Connect the caller to another number
In this route, we grab the caller's digit selection from the HTTP request and store it in a variable called
selected_option. We then use a
Dial verb with the appropriate phone number to connect our caller to their home planet.
The current numbers are hardcoded, but you could update this code to read phone numbers from a database or a file.
That's it! We've just implemented an IVR phone tree that will help get ET back home.
Where to Next?
If you're a Python/Flask developer working with Twilio, you might want.
|
https://www.twilio.com/docs/voice/tutorials/ivr-phone-tree-python-flask
|
CC-MAIN-2020-45
|
refinedweb
| 627
| 71.04
|
To exit the program in python, the user can directly make the use of Ctrl+C control which totally terminates the program. However, if the user wishes to handle it within the code, there are certain functions in python for this. They are quit(), exit(), sys.exit() etc which helps the user in terminating the program through the python code. Below is how you can use these in-built Python functions:
1.) quit() in Python
This function completely terminates the execution of a program. It can only be used in the interpreter in a real-world situation and not anywhere inside the program. It tends to raise an exception called SystemExit exception. Below is a python code to illustrate the use of quit() in python:
for x in range(1,15): print(x*10) quit()
The output of the above code will be:
10
2.) exit() in Phyton
This function should also reside inside the interpreter. It is almost similar to the quit() function in python but is more user-friendly than that. It lets the user come out of the loop in the execution which in-turn terminates the execution of the program. This can only be made into execution when the module of the code is about to run. Below is a python program to illustrate the use of exit().
for i in range(5): if i == 3: print(exit) exit() print(i)
The output of this python program will be:
0 1 2 Use exit() or Ctrl-D (i.e. EOF) to exit
3.) sys.exit([args]) in Python
This function in python is much better than using quit() and exit() functions. If the user gets an output a zero, it means he is successful in terminating the program. This method does not only work for integers but strings as well. To use this, the coder needs to import sys for the execution, as shown in the code below. Check out the code to understand the use of sys.exit() in python and how it differs from using quit() and exit().
import sys students = 20 if students < 18: sys.exit("Number less than 18") else: print("Number is not less than 18")
The output of the above python code for termination of the program will be:
Number is not less than 18
|
https://www.developerhelps.com/python-exit-program/
|
CC-MAIN-2021-31
|
refinedweb
| 385
| 72.97
|
#include <hallo.h> * Andreas Metzler [Fri, Jul 23 2004, 09:47:04AM]: > > Sure. But for Sarge, we did have the goal of a new installer and > > that took a long time. Right now, I don't seem to recall any equally > > big release goals for sarge+1 > [...] > > The obvious big blocker is the non-free "data|doc" issue. *Personally* How "obvious" is that? I wish the RM would finaly say a word about all this assumptions - I don't like the current situation, first FTP masters decided to ignore everyone (except of the few rumors about people that managed to contact them somehow) and now we speculate about the issues that finaly the RM will decides (and he normaly decides without considering other opinions IIRC). Regards, Eduard. -- Es war einmal, es ist nicht mehr, ein rosaroter Teddybär. Er aß die Milch und trank das Brot, und als er starb, da war er tot.
|
https://lists.debian.org/debian-devel/2004/07/msg01728.html
|
CC-MAIN-2015-11
|
refinedweb
| 153
| 70.02
|
an interactive course on Educative.io!
Declaratively Rendering Earth in 3D, Part 1: Building a Cesium + React App with Webpack
This is a post in the Declaratively Rendering Earth in 3D series.
Create-React-App ejection, Webpack tweaks, and use of Webpack's DllPlugin
Intro
Cesium.js is a powerful Javascript library for rendering a 3D globe. It can display a wide variety of geospatial visualizations, including icons and text labels, vector geometries, 3D models, and much more, all on top of a fully-viewable 3D Earth with digital 3D terrain and imagery layers.
Cesium is very similar to Google Earth in concept and capabilities. However, Cesium has many advantages over the now-deprecated Google Earth browser plugin. The Google Earth Plugin was a binary plugin that had to be installed on client systems, and while it had a Javascript API, the internal implementation was a black box of behavior. Also, while GEP could be customized to work with a "Google Earth Enterprise" self-hosted globe data server, GEE licensing was expensive.
On the other hand, while Cesium is primarily developed by employees of AGI, it's a fully open-source Javascript library. Cesium does not require a browser plugin, just the WebGL 3D rendering capability that is built into modern browsers. Cesium also supports a wide variety of imagery and terrain data sources, and can work with both publicly hosted and self-hosted globe data servers.
I've used Cesium in several geospatial applications at work, and have become very familiar with its capabilities. In the process, I've used it with multiple client frameworks, including GWT, Backbone, and now React.
Cesium is a complex toolkit, and dates back to early 2012. Because of that, its architecture has several intricacies that make it somewhat difficult to use in a modern React+Webpack application. While there is existing documentation on how to use Cesium in a Webpack-based application, I haven't yet seen any discussion of how to use it with React. In addition, I've been able to leverage some of Webpack's advanced capabilities to improve the development and deployment process.
In this two-part series, I'll show you how to :
- Set up a basic React app that loads Cesium
- Configure Webpack for faster build times and deployment of an application that uses Cesium using DllPlugin for code splitting
- Use React components to declaratively control rendering of Cesium primitives through Cesium's imperative APIs
This series assumes some familiarity with Cesium, React, and Webpack, and isn't intended to teach the basics for them.
The code for the sample project accompanying this series is on Github at github.com/markerikson/cesium-react-webpack-demo. The commits I made for this post can be seen in PR #1: Configure Webpack I'll be linking to many of the commits as I go through the post, as well as specific files in those commits. I won't paste every changed file in here or show every single changed line, to save space, but rather try to show the most relevant changes for each commit as appropriate.
Table of Contents
- Creating a Basic React+Cesium App
- Optimizing Cesium App Deployment
- Final Thoughts
- Further Information
Creating a Basic React+Cesium App
Initial Setup
We're going to start by using the excellent Create-React-App tool to create our new project. To keep things simple, we'll skip the details of the initial setup steps, but here's a summary:
- Use
create-react-appto create the project and commit it to Git
- Use Yarn to set up a lockfile for the project's dependencies
- Clean out the existing
<App>component so it only renders the text "Empty"
- Use Yarn to add Cesium as a dependency to the project
At the time of writing, the current versions are CRA 0.9.2 and Cesium 1.31.
Configuring Webpack to Use Cesium
As mentioned, Cesium has many complexities in its architecture that make it difficult to use with Webpack out of the box. This includes:
- Cesium is currently written using the AMD module format for its source files
- It includes some pre-bundled AMD-based third-party libraries
- Cesium makes heavy use of web workers
- Some of the code uses multi-line strings
The primary documentation on using Cesium with Webpack comes from the article Cesium and Webpack on Cesium's blog, and the sample repo mmacaula/cesium-webpack, both written by Mike Macaulay. In his tutorial, he discusses two ways to use Cesium: using the pre-built Cesium bundle, and using Cesium's source directly. We're going to use the "source" approach to start with.
As the blog post points out, we need to set two specific Webpack config options for this to work right. We need to set
sourcePrefix: '' to fix Webpack indenting multi-line strings improperly, and also set
unknownContextCritical: false to stop Webpack from printing warnings about certain libraries being loaded.
Unfortunately, since we're using Creact-React-App, we don't have direct access to the Webpack config files, since CRA hides them from us by default. So, we're going to have to use CRA's "escape hatch": the
npm run eject command. This will copy all of CRA's config files into our own project, and update
project.json to include all the individual tool dependencies instead of the single
react-scripts dependency. After we eject, everything will still run exactly the same, but we can no longer simply upgrade the
react-scripts dependency to get the latest build system updates - we now "own" all the build config ourselves.
After ejecting and committing the newly visible config files, we can make the necessary config tweaks.
First, per the instructions in the "Cesium and Webpack" tutorial, we need to copy Cesium's pre-built worker files and assets to our public folder. This is a manual step, and doesn't involve any commits. Browse into
$PROJECT/node_modules/cesium/Build/. You should see two folders,
Cesium and
CesiumUnminified. Copy the entire
Cesium folder over to
PROJECT/public/, and rename it to
cesium. Then, delete the
Cesium.js file that's just inside. You should now have the following folder structure:
- $PROJECT - public - cesium - Assets - ThirdParty - Widgets - Workers
Since we don't want to actually commit these files, it's a good idea to add a line to the project's
.gitignore file to ignore these:
Commit c47204c: Ignore the public/cesium folder containing the copied Cesium output
.gitignore
# production /build +/public/cesium/
Then, we'll add the needed config tweaks to the Webpack config files:
Commit 2015273: Add Webpack config options needed to run Cesium
config/webpack.config.dev.js
publicPath: publicPath, + sourcePrefix : '', // Skip ahead module: { + unknownContextCritical : false,
This should be done for both the development and production configs.
Before we can actually load the Cesium Viewer widget into our application, we have to configure Cesium so it knows how to construct the URLs for all of its assets. That requires a call to the
buildModuleUrl() function that Cesium provides. Once that's done, we can load the Viewer instance and have things work correctly.
Commit 17479d3: Add initial Cesium viewer to the app
src/index.js
import App from './App'; import './index.css'; +import "cesium/Source/Widgets/widgets.css"; + +import buildModuleUrl from "cesium/Source/Core/buildModuleUrl"; +buildModuleUrl.setBaseUrl('./cesium/');
Note that we set the base URL to
"./cesium/", which corresponds to the pre-built Cesium folder we copied earlier into
$PROJECT/public.
From there, all we have to do is use the standard React approach for interacting with code that needs to access a DOM element directly. We render a div that will serve as the container for our Cesium widget, and use a "callback ref" to save a reference to the real DOM element. Then, in
componentDidMount, we create the Cesium.Viewer instance, and give it the div reference to serve as its parent:
src/App.js
import React, { Component } from 'react'; import Viewer from "cesium/Source/Widgets/Viewer/Viewer"; class App extends Component { componentDidMount() { this.viewer = new Viewer(this.cesiumContainer); } render() { return ( <div> <div id="cesiumContainer" ref={ element => this.cesiumContainer = element }/> </div> ); } }
Notice that we're importing pieces from inside Cesium's folder structure, rather than just
import Cesium from "cesium".
If we run the project, here's what we should see:
Success! We've loaded Cesium, and are viewing a 3D globe with the Cesium Viewer in its default configuration. (If you squint carefully at the image, you'll see that the viewer doesn't actually fill the whole screen - there's a bunch of blank space below. We'll fix that in the next part.)
That wraps up the basic application setup. Let's move on to setting up a proper production build.
Optimizing Cesium App Deployment
Thus far, we've been simply importing Cesium directly into our main application. That's okay as a starting point, but it also means that our main application bundle is going to include pretty much all of Cesium. Unfortunately, Cesium is a big toolkit. Let's run a production build of the application:
$ node scripts/build.js Creating an optimized production build... Compiled successfully. File sizes after gzip: 532.54 KB build\static\js\main.304c45dc.js 4.78 KB build\static\css\main.c5310e60.css Done in 48.13s.
Hmm. "532KB after gzip?" That seems big. Let's check out what goes into the bundle, using the
source-map-explorer to view the contents of the minified bundle:
EEEP! Our production app bundle is over 2MB, and Cesium itself is taking up 1.8MB of minified Javascript!!! That's... not good, to say the least. Meanwhile, Cesium's various web workers and assets, while loaded separately, are also a significant chunk of space as well. Yes, gzipping the bundle will take that down to about 532KB, but that's still way more than we'd like to load at once.
The bad news is that there's only so much we can do to solve this. Cesium is simply a very large, very complex toolkit, and there's nothing we can do to fully shrink down the size of Cesium itself. Any app using Cesium will never win awards for "Smallest Total Loading Size".
However, the good news is that we can separate Cesium out from our application bundle. We do still need to load it, and in fact we'll need to load it before the app bundle, but by separating it out we can at least make it cached for the next time the user loads the app. Also, by pre-building the Cesium bundle, we can cut down on production build time for our application's bundle.
Serving Cesium Assets in Development
Before we get to building Cesium as a separate bundle, we can make an improvement to our development process. All this time, we've had a copy of Cesium's pre-built output folder sitting in our
$PROJECT/public/cesium/ folder, because those files need to be loaded by Cesium at runtime from the server. We can remove the need for that by modifying the CRA dev server setup so that it serves those files directly out of
node_modules/cesium/.
First, we'll add a few more entries to CRA's list of pre-defined paths:
Commit 73bdbe2: Add additional paths for use in build config
config/paths.js
ownNodeModules: resolveApp('node_modules'), + app : resolveApp('.'), + appConfig : resolveApp('config'), + cesiumDebugBuild : resolveApp('node_modules/cesium/Build/CesiumUnminified/'), + cesiumProdBuild : resolveApp('node_modules/cesium/Build/Cesium/'), + cesiumSourceFolder : resolveApp('node_modules/cesium/Source/'), nodePaths: nodePaths,
Then, we'll make a small edit to CRA's dev server setup to tell it to serve static files directly out of the right folder:
Commit eabdcf5: Modify CRA dev server to serve Cesium files from node_modules
scripts/start.js
var openBrowser = require('react-dev-utils/openBrowser'); var prompt = require('react-dev-utils/prompt'); +var express = require("express"); // Skip ahead function addMiddleware(devServer) { + // Handle requests for Cesium static assets that we want to + // serve up direct from /node_modules/cesium/. + devServer.use("/cesium", express.static(paths.cesiumDebugBuild)); +
We should now be able to delete the
cesium/ folder from
$PROJECT/public/, at least in terms of development. CRA automatically copies everything inside of
/public/ to the build output folder when it does a production build, so we'll need to add some custom logic to handle copying Cesium's assets for production builds. We'll come back to that in a bit.
Building a Cesium Bundle using DllPlugin
Webpack has several ways to create bundles and chunks. The most widely used methods are declaring bundle entry points in the
entry section of a Webpack config, and using the
CommonsChunkPlugin to extract files that are shared between multiple chunks into a separate bundle.
There's another Webpack plugin that's less well known:
DllPlugin. Named after the idea of a native code "Dynamic Link Library" from Windows (or
.so for you *nix users), the idea is that you pre-build a bundle containing the reusable or shared portions of your code, and also create a metadata file that describes what's inside the bundle. Then, when you build your application itself, you add a reference to the metadata so that Webpack knows what code should already be available. Webpack will then skip including those pieces in your app bundle.
Building a DLL bundle requires creating a new Webpack config that's separate from the application configs. Here's what the config looks like:
Commit 4ddc26a: Add a Webpack config to pre-build a Cesium bundle
config/webpack.cesium.dll.config.js
"use strict"; const path = require("path"); const webpack = require("webpack"); const paths = require("./paths"); const env = require("./env"); const outputPath = path.join(paths.app, "distdll"); const webpackConfig = { entry : { cesiumDll : ["cesium/Source/Cesium.js"], }, devtool : "#source-map", output : { path : outputPath, filename : "[name].js", library : "[name]_[hash]", sourcePrefix: "", }, plugins : [ new webpack.DllPlugin({ path : path.join(outputPath, "[name]-manifest.json"), name : "[name]_[hash]", context : paths.cesiumSourceFolder, }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify("production") }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ], module : { unknownContextCritical : false, loaders : [ { test : /\.css$/, loader: "style!css" }, { test : /\.(png|gif|jpg|jpeg)$/, loader : "file-loader", }, ], }, };
Some key things to note here. First, we're building this in production mode by setting
process.env.NODE_ENV="production" and minifying it. We've also included the couple specific config settings we had to tweak earlier.
The really important part is that we're including the
DllPlugin in the config. The
path option tells Webpack where to write the metadata file,
name is the name of the bundle file itself, and I think
context has to do with how the imported source files are looked up. Roughly. :)
Now that we have the config file, we need to actually run Webpack with this config to generate our Cesium DLL bundle. I've written a couple new script files to control this process. One encapsulates the work of running Webpack with a certain config and printing out some readable stats, and the other just calls the Webpack compiler script with the Cesium DLL config.
Commit b55dbd5: Add scripts to build a Cesium bundle with DllPlugin
We'll skip looking at the script contents, but here's the output of running the DLL build script:
$ node ./scripts/buildCesiumDLL.js Compiling: cesium build [====================] 100% (35.5 seconds) () Build completed in 35.47s Hash: 0829da3ac0fb7ef638b5 Version: webpack 1.14.0 Time: 35472ms Asset Size Chunks Chunk Names cesiumDll.js 2.13 MB 0 [emitted] cesiumDll cesiumDll.js.map 19 MB 0 [emitted] cesiumDll Done in 37.33s.
If we look in
$PROJECT/distdll, we should see three files:
cesiumDll.js,
cesiumDll.js.map, and
cesiumDll-manifest.json. Cesium is still a really hefty chunk of code, but at least now it's a separate file.
Using a DLL Bundle in the Application
Happily, the hard part is done. Now that we have the DLL bundle generated, we can point our production Webpack config at the manifest file:
Commit 6db616f: Update Webpack prod config to use the Cesium DLL bundle
config/webpack/config.prod.js
+var path = require('path'); var autoprefixer = require('autoprefixer'); // Skip ahead plugins: [ + new webpack.DllReferencePlugin({ + context : paths.cesiumSourceFolder, + manifest: require(path.join(paths.app, "distdll/cesiumDLL-manifest.json")), + }),
We just add
DllReferencePlugin to the production config, set the
manifest option to point to the manifest file that was generated earlier, and use the same
context option we used when we generated the DLL (to make sure that source file references match before and after).
Let's re-run a production build of the app and see how things look:
$ node scripts/build.js Creating an optimized production build... Compiled successfully. File sizes after gzip: 46.09 KB build\static\js\main.f984614f.js 4.78 KB build\static\css\main.c5310e60.css Done in 10.43s.
That looks much better! The compile time dropped from 48 seconds to about 10 seconds, and the main bundle is down to 46KB gzipped. Let's take another look at the contents of the bundle using
source-map-explorer:
The overall application bundle is now down to 150KB. We're now looking at just the application code plus the non-Cesium libraries. There's more we could do to optimize, but this is sufficient for the concepts I wanted to show off.
Including Cesium in Production
We now need to actually include Cesium into the production build output. Since we deleted the hand-copied
public/cesium folder, Cesium's assets aren't being copied to
/build/ any more. We can add some logic to CRA's existing build script to do that. It'll just do some glob searching to collect a list of files under
node_modules/cesium/Build/Cesium/, and copy each one to the output folder, along with the Cesium DLL bundle we've created.
Commit 902ba04: Update build script to copy Cesium files to the output folder
The last step is to actually include the Cesium DLL bundle into our page. CRA uses the HtmlWebpackPlugin to insert the right script tags into the
index.html template during the build process. We can customize the template so that it only includes the DLL bundle during a production build.
Commit c65e7bd: Conditionally include Cesium bundle in the HTML host page
config/webpack.config.prod.js
new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, + production : true,
HtmlWebpackPlugin takes a number of specific options, but you can also add any other options you want, and it will pass them through. So, since we know we're doing a prod build when this config is being used, we just add a
production : true option that we can use in the template.
public/index.html
<body> <div id="root"></div> + <% if(htmlWebpackPlugin.options.production) { %> + <script src="cesium/cesiumDll.js"></script> + <% } %> <!--
HtmlWebpackPlugin uses Lodash templating, so we can insert a simple check for the
production option we added, and only include the Cesium DLL script tag if it's a prod build.
Note that the Cesium DLL bundle must be loaded before the main application bundle! This is because the DLL bundle exposes its contents as a global variable (such as
var cesiumDll_0829da3ac0fb7ef638b5 ), and the
DllReferencePlugin adds logic to look for that specific variable.
With that, we should be able to run an HTTP static file server from our
build folder, and see the application successfully load!
Wrapping Up Webpack Optimization
While I was working on this post, I had intended to demonstrate lazy-loading the DLL bundle using Webpack's code-splitting abilities. Unfortunately, I realized that what I'm doing in my own app right now doesn't actually qualify as lazy-loading. I've got some code-splitting in place, but as we just saw, bundles produced by DllPlugin still have to be loaded manually. Since a DLL bundle is usually vendor libs, it's reasonable to have a specific script tag that loads the DLL bundle first.
There's a couple threads in the Webpack issues tracker that discuss ways to actually load DLL bundles at runtime, so that they truly are lazy-loaded. The consensus seems to be that it's possible, but it requires use of some non-Webpack loading code to make it work. See Webpack issues #2592 and #3115 for discussion on the topic.
It's also important to note that DllPlugin doesn't actually reduce the amount of code that has to be loaded, but it does split things into more cacheable pieces.
Final Thoughts
Cesium is a complex and powerful library, and Webpack is a complex and powerful build tool. Getting them to play nicely together takes a bit of work, but is well worth the effort.
Next up in Part 2, we'll look at how to use React components to control Cesium's API. Be sure to check it out!
Further Information
- Cesium and Webpack
- Cesium Blog: Cesium and Webpack
- Repo: Cesium and Webpack tutorial and examples
- Repo: Cesium-Webpack project template
- Cesium group: "Incompatible with Webpack"
- Cesium group: "Cesium usage with Webpack?"
- Cesium #2981: Making Cesium Webpack and Browserify friendly
- Cesium #4876: Fix remaining issues that require special Webpack config settings?
- Webpack Optimization with DllPlugin
- Webpack Plugins we been keeping on the DLL
- RRUHE #616: DllPlugin usage summary
- React-Boilerplate #495: Implement DllPlugin
- Optimizing Webpack for Faster React Builds
- Optimizing Webpack build times and improving caching with DLL bundles
- Building Vendor and Feature Bundles with Webpack
- Webpack #2592: Proposal - Dll-like plugin for an external context
- Webpack #3115: How to lazy load a DLL bundle?
- Formidable Playbook: Webpack Shared Libs
This is a post in the Declaratively Rendering Earth in 3D series. Other posts in this series:
- Mar 07, 2017 - Declaratively Rendering Earth in 3D, Part 1: Building a Cesium + React App with Webpack
- Mar 07, 2017 - Declaratively Rendering Earth in 3D, Part 2: Controlling Cesium with React
|
https://blog.isquaredsoftware.com/2017/03/declarative-earth-part-1-cesium-webpack/
|
CC-MAIN-2018-51
|
refinedweb
| 3,646
| 54.42
|
Building Breakernoid in MonoGame, Part 4
- Levels / Scoring and Lives
- Polishing the Paddle Bouncing / Where to Go from Here
This is the fourth and final article in a series in which you build a clone of classic brick-breaking games called Breakernoid.
At the end of the third article, you had a pretty functional game. However, having only one level isn't very exciting, so in this article you're going to add more levels. You'll also add scoring and lives to complete the game.
Catch up on the other articles in this series:
Levels
For the level file format, you're going to use XML. Although XML is definitely not the most compact way to store this level data, it has two advantages: it is plain text, so it can be easily edited; and C# has built-in functionality to save and load classes to an XML file (called serialization).
In order to load the levels, you first need to make a new Level class in a separate Level.cs file. In order for the serialization to work properly, you must use the following exact class declaration—if your Level doesn't match this declaration, the serialization will not work:
public class Level { public int[][] layout; public float ballSpeed; public string nextLevel; }
Note that you didn't use a multidimensional array like int[,], but instead you used a jagged array int[][]. That's because the XML serializer doesn't support multidimensional arrays, but it does support jagged arrays.
This means the memory layout is different, but accessing an element in a jagged array isn't that different: you use [i][j] instead of [i,j].
All the level files you will use are in Breakernoid_levels.zip. In Visual Studio, you'll want to create a new folder in the project called Levels, and then use "Add Existing Item" to add all the Level*.xml files into this folder.
You'll also need to right-click these files and select "Properties" to change the "Copy to Output Directory" setting to "Copy if Newer."
In Xamarin Studio on Mac, you'll have to right-click the files and select "Build Action>Content."
Next, you should remove the blockLayout member variable because you won't be using it any more. For now, comment out the code in LoadContent that loads in the blocks from blockLayout. You'll be replacing it with some other code in a second.
Now add a member variable to Game1 of type Level that's called level, which is where you'll store the level data that's read in from the XML files.
You then need to add two using statements to the top of Game1.cs for System.IO and System.Xml.Serialization. Add a LoadLevel function to Game1.cs that takes a string specifying the level file to load in.
Because the syntax for the XmlSerializer is a little odd, here is the skeleton code for the LoadLevel function:
protected void LoadLevel(string levelName) { using (FileStream fs = File.OpenRead("Levels/" + levelName)) { XmlSerializer serializer = new XmlSerializer(typeof(Level)); level = (Level)serializer.Deserialize(fs); } // TODO: Generate blocks based on level.layout array }
After you load the level, you need to loop through the level.layout jagged array and generate the blocks as appropriate. This will be very similar to what you did before, except you use [i][j] and level.layout.Length to get the number of rows and level.layout[i].Length to get the number of columns.
In fact, you can just copy the code you commented out before that loaded blocks from blockLayout and use it with some minor modifications.
There's one other change to watch out for: some indices have a 9 stored in them, which won't convert to a block color. This is a special value that means you should skip over that particular index because it is empty.
After this LoadLevel function is implemented, go ahead and call LoadLevel from LoadContent, and pass in "Level5.xml" for the file name.
Try running the game now. If you get a file loading error, this might mean that you didn't put the level files into the Levels directory correctly.
If you were successful, you should see a block layout, as shown in the following figure:
Notice that the Level class also has a ballSpeed parameter. Every time you spawn a ball, you should set its speed to ballSpeed. This way, the later levels can increase the speed over the previous levels.
Because there are only five levels right now, level 5 will wrap around back to level 1. So you should also add a speed multiplier that's initialized to 0 and increased by 1 every time you beat level 5.
Then add 100 * speedMult to the ball speed, which ensures that the speed will continue to increase as the player gets further and further into the game.
The last variable in the Level class is the nextLevel, which stores the name of the next level that should be loaded once the current level is finished.
So make a new function in Game1 called NextLevel, which you'll call when there are zero blocks left in the blocks list.
In NextLevel, make sure you turn off all power-ups, clear out all the balls/power-ups in the respective lists, reset the position of the paddle, and spawn a new ball. Then call LoadLevel on the next level.
As for where you should check whether there are no blocks left, I suggest doing so at the end of the Game1.Update function.
To test this next level code, change it so you first load in "Level1.xml" and beat the level to see whether the second level loads.
Scoring and Lives
The last major piece that will help the game feel complete is to add scoring and lives and then display them with text onscreen. You'll also have text that pops up at the start of the level and specifies the level number you're in.
For the score, you just need to add a new score int in Game1 that you initialize to zero.
The rules for scoring are pretty simple:
- Every block the player destroys gives 100 + 100 * speedMult points.
- Every power-up the player gets gives 500 + 500 * speedMult points.
- When the player completes a level, they get a bonus of 5000 + 5000 * speedMult + 500 * (balls.Count - 1) * speedMult.
Notice that all the scoring equations are a function of speedMult, so if players keep completing the levels over and over, the number of points they get increases. There's also a bonus to the level completion based on the number of balls the player has up on level completion.
In any event, make sure you create an AddScore function that you call when you want to change the score instead of directly modifying the score. This way, you can have one centralized location to do checks for things such as awarding an extra life.
After you have a score, it's time to display it onscreen. To do this, you first need to add a SpriteFont member variable to Game1.
You can then load this font in LoadContent, like so:
font = Content.Load
("main_font");
In Game1.Draw, you can then draw the score text using code like this:
spriteBatch.DrawString(font, String.Format("Score: {0:#,###0}", score), new Vector2(40, 50), Color.White);
This code formats the score with commas for numbers greater than 999. The font you're using is "Press Start 2P" from, which is a great retro gaming font that's free to use.
Before you add in lives, you will add code that gives a bit of a reprieve between levels. When loading a new level, rather than spawning the ball immediately, you will display text that says what level the player is in for 2 seconds. After 2 seconds, you'll hide that text and spawn the ball.
To support this, you need to add two member variables: a bool that specifies whether you're in a level break and a float that tracks how much time is left in the break.
Then you should change the Game1.Update function so that nothing in the world is updated while the level break is active. Instead, during the break, all you should do is subtract delta time from the float tracking the remaining time for the break.
Once that float becomes <= 0, you can then set the break bool to false and spawn the ball.
You now want to make a function called StartLevelBreak, which sets the level break bool to true and the remaining time to 2.0f.
In LoadContent and NextLevel, call StartLevelBreak instead of SpawnBall. If you do all this, when you start the game there should now be a 2-second delay before the gameplay begins.
Now add text that specifies what level you're in. This means you need to add a levelNumber variable that you initialize to 1 and increment every time you go to the next level.
Next, in Game1.Draw, if you are in a level break, you can draw text specifying the level number. Ideally, you want this text to be centered onscreen.
What you can do is query the font for the size of a string using MeasureString and use the length/width of this rectangle to determine where to draw the string.
The code will look something like this:
string levelText = String.Format("Level {0}", levelNumber); Vector2 strSize = font.MeasureString(levelText); Vector2 strLoc = new Vector2(1024 / 2, 768 / 2); strLoc.X -= strSize.X / 2; strLoc.Y -= strSize.Y / 2; spriteBatch.DrawString(font, levelText, strLoc, Color.White);
If you run the game now, you should notice that the name of the level is displayed during a 2-second break.
Now let's add lives. The player should start out with three lives, and every time LoseLife is called, they should lose one. If the player has zero lives left and dies, rather than spawning a new ball you should just display "Game Over."
You'll also want to display the number of lives left in the top-right corner of the screen, which will be very similar to displaying the score (except that you don't need commas).
Finally, you also want to give the player an extra life every 20,000 points. One way to do this is to have a counter that you initialize to 20000 and subtract from every time points are earned.
Then, when it becomes less than or equal to 0, you can reset the counter and add a life. You should also play the power-up SFX when the player gains an extra life.
You should now have a game that's pretty complete, and the score/level text displays should look like the following figure:
|
https://www.informit.com/articles/article.aspx?p=2180419
|
CC-MAIN-2021-10
|
refinedweb
| 1,811
| 71.75
|
How many times have you read about the merits of using the STL algorithms instead of hand written loops? Chances are this is something that you have heard a lot. The thing is, actually being able to achieve this in real world programs is not very intuitive; especially if you are new to the STL. However, once you learn how the STL algorithms interact with your code, using
for_each becomes easy. In fact, it becomes so easy and it is so powerful, that you may never write another loop in your career.
The
for_each algorithm iterates over a container and �does something� for each element in the container. As a programmer, you have to specify what you want to be done for each element when you call the
for_each algorithm. You do this by providing a function which the algorithm calls as it iterates over the container.
The algorithm is not a magic. It does what you think it does. So let�s take a look at the implementation of
for_each that comes with Microsoft�s C++ 7:
/* * Copyright (c) 1992-2002 by P.J. Plauger. ALL RIGHTS RESERVED. * Consult your license regarding permissions and restrictions. */ // TEMPLATE FUNCTION for_each template<class _InIt, class _Fn1> inline _Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func) { // perform function for each element for (; _First != _Last; ++_First) _Func(*_First); return (_Func); }
As you can see, the algorithm iterates over the range passed in and invokes a function for each element in the range.
The general idea while replacing loops with
for_each is that you write a function implementing the loop logic, that is, what you want to do for each iteration of the loop. You then supply this function as the third parameter (
_Func) to the
for_each algorithm. Sounds good? Well, I�m afraid that there�s a little more to it than that.
Notice that the signature of the function called by
for_each is fixed. It has to be a function taking just one parameter and this parameter has to be of the same type as the elements in the container. So if you write a function implementing your loop logic, the only parameter it can have is the current element in the loop; and herein lays the problem.
What if you want to have more that one parameter?
Let�s take a specific example. Say that we are looping over a vector
<wstring> and we want to compare each
<wstring> in the vector to an external
wstring object and write it out to a file if they are the same.
Without using
for_each, our code would look something like the following:
wstring wstrTarget; wstring wstrFile; for ( vector<wstring>::iterator itr = vec.begin(); itr != vec.end(); itr++ ) { if ( *itr == wstrTarget ) writeToFile( *itr, wstrFile ); }
How would we do the same thing using
for_each? Well, we need a function that can compare the current element to
wstrTarget and, if they match, write the current element out to the file called
wstrFile. So, the function needs to know three things: the current element, what to match it to and the name of the file to write to. But how do we tell the function these three things? Remember that we can only supply the function with one parameter, the current element, so how do we get the other pieces of information into the function?
The answer lies in the function objects.
Because function objects can be called like functions, we can use one as the function passed into
for_each. That is, in the
for_each implementation given above,
_Func(*_First) can call a function object as well as a function. Also, because function objects are objects (like any other) they can have properties, methods and constructors. This allows us to supply the function object with the additional data it needs to perform the loop logic which cannot be supplied automatically by the
for_each algorithm.
A convenient and concise way of doing this is by supplying the extra data in the constructor of the function object.
In our example, we can define a function object called
compareAndWrite which accepts the target
wstring object and the file name to write to in its constructor. Defining an
operator() accepting a
const wstring& as a parameter allows the function object to be used by the
for_each algorithm and receive the current element from each iteration.
Putting all the pieces together, we get the following definition for the
compareAndWrite function object:
struct compareAndWrite { const wstring& wstrTarget; const wstring& wstrFile; compareAndWrite( const wstring& wstrT, const wstring& wstrF ) : wstrTarget(wstrT), wstrFile(wstrF) { } void operator()( const wstring& val ) { if ( val == wstrTarget ) writeToFile( val, wstrFile ); } };
which allows us to replace the hand crafted
for loop with the following call to
for_each.
for_each( vec.begin(), vec.end(), compareAndWrite(wstrTarget,wstrFile) );
OK, so we have to write more code to use function objects, but the extra code is worth writing and here�s why.
The extra code is required to define the function object. We have to define the class structure, methods and variables. Once we have the class defined, the actual loop logic is really not too different at all and is defined by the class�s
operator().
So why bother using the
for_each algorithm when more code is required?
Well, with hand crafted loops, how do you:
Reusing a loop without function objects invariably involves making a new copy of the loop code. This is not good. You now have two copies of the same code in two different parts of your software.
Building a slightly different version of the loop will also normally involve taking a copy of the code and modifying the loop logic. Again, you now have two chunks of code doing similar things that have to be maintained.
Function objects and the
for_each algorithm give you the ability to build your loop logic as a fully fledged class and reap all the benefits that come from inheritance, polymorphism and encapsulation.
You can build a class hierarchy defining the different versions of your loop logic without having to maintain multiple copies of the same code or complicate the loop logic with parameterization (as would be the case if you defined the loop logic in a function rather than a function object).
So, in this example, to use a slightly different version of the
compareAndWrite loop, all we need to do is define a subclass of the
compareAndWrite function object and use that in the call to
for_each.
struct multiCompareAndWrite : public compareAndWrite { // loop logic here }; for_each(vec.begin(), vec.end(), multiCompareAndWrite(wstrTarget,wstrFile));
In loops, typically there are variables that change and variables that remain constant. Using the function object and
for_each technique allows the programmer to define what variables remain constant for the loop and those that do not. The additional data that is required by the loop logic is supplied in the function object�s constructor. The data that is not changed by the loop logic is declared as
const in the function object. That way, any programmer reading your code can immediately see what data is changed and what data is not changed by the loop logic.
In order to figure out what a hand crafted loop does, you need to read the code. However, well named function objects, like
compareAndWrite,
addRecToDatabase etc. convey what they do in their names.
For example, it is obvious what the following statement does without any explanation or delving into the code.
for_each(vec.begin(), vec.end(), addRecToDatabase(connectString));
Replacing
for loops with the STL
for_each algorithm is a great way of making object oriented programming work for you. You can avoid having multiple copies of the same or similar code to maintain by building class hierarchies of loop logic. What�s more, your code becomes less cluttered, easier to read and more componentized.
The key aspects of this technique are:
constin the function object.
General
News
Question
Answer
Joke
Rant
Admin
|
http://www.codeproject.com/KB/stl/replace_for_for_each.aspx
|
crawl-002
|
refinedweb
| 1,316
| 60.55
|
import "github.com/go-kit/kit/sd/etcd"
Package etcd provides an Instancer and Registrar implementation for etcd. If you use etcd as your service discovery system, this package will help you implement the registration and client-side load balancing patterns.
Code:
package main import ( "context" "io" "time" "github.com/go-kit/kit/endpoint" "github.com/go-kit/kit/log" "github.com/go-kit/kit/sd" "github.com/go-kit/kit/sd/lb" ) func main() { // Let's say this is a service that means to register itself. // First, we will set up some context. var ( etcdServer = "" // don't forget schema and port! prefix = "/services/foosvc/" // known at compile time instance = "1.2.3.4:8080" // taken from runtime or platform, somehow key = prefix + instance // should be globally unique value = "http://" + instance // based on our transport ctx = context.Background() ) // Build the client. client, err := NewClient(ctx, []string{etcdServer}, ClientOptions{}) if err != nil { panic(err) } // Build the registrar. registrar := NewRegistrar(client, Service{ Key: key, Value: value, }, log.NewNopLogger()) // Register our instance. registrar.Register() // At the end of our service lifecycle, for example at the end of func main, // we should make sure to deregister ourselves. This is important! Don't // accidentally skip this step by invoking a log.Fatal or os.Exit in the // interim, which bypasses the defer stack. defer registrar.Deregister() // It's likely that we'll also want to connect to other services and call // their methods. We can build an Instancer to listen for changes from etcd, // create Endpointer, wrap it with a load-balancer to pick a single // endpoint, and finally wrap it with a retry strategy to get something that // can be used as an endpoint directly. barPrefix := "/services/barsvc" logger := log.NewNopLogger() instancer, err := NewInstancer(client, barPrefix, logger) if err != nil { panic(err) } endpointer := sd.NewEndpointer(instancer, barFactory, logger) balancer := lb.NewRoundRobin(endpointer) retry := lb.Retry(3, 3*time.Second, balancer) // And now retry can be used like any other endpoint. req := struct{}{} if _, err = retry(ctx, req); err != nil { panic(err) } } func barFactory(string) (endpoint.Endpoint, io.Closer, error) { return endpoint.Nop, nil, nil }
client.go doc.go instancer.go registrar.go
var ( // ErrNoKey indicates a client method needs a key but receives none. ErrNoKey = errors.New("no key provided") // ErrNoValue indicates a client method needs a value but receives none. ErrNoValue = errors.New("no value provided") )
type Client interface { // GetEntries queries the given prefix in etcd and returns a slice // containing the values of all keys found, recursively, underneath that // prefix. GetEntries(prefix string) ([]string, error) // WatchPrefix watches the given prefix in etcd for changes. When a change // is detected, it will signal on the passed channel. Clients are expected // to call GetEntries to update themselves with the latest set of complete // values. WatchPrefix will always send an initial sentinel value on the // channel after establishing the watch, to ensure that clients always // receive the latest set of values. WatchPrefix will block until the // context passed to the NewClient constructor is terminated. WatchPrefix(prefix string, ch chan struct{}) // Register a service with etcd. Register(s Service) error // Deregister a service with etcd. Deregister(s Service) error }
Client is a wrapper around the etcd client.
NewClient returns Client with a connection to the named machines. It will return an error if a connection to the cluster cannot be made. The parameter machines needs to be a full URL with schemas. e.g. "" will work, but "localhost:2379" will not.
type ClientOptions struct { Cert string Key string CACert string DialTimeout time.Duration DialKeepAlive time.Duration HeaderTimeoutPerRequest time.Duration }
ClientOptions defines options for the etcd client. All values are optional. If any duration is not specified, a default of 3 seconds will be used.
Instancer yields instances stored in a certain etcd keyspace. Any kind of change in that keyspace is watched and will update the Instancer's Instancers.
NewInstancer returns an etcd instancer. It will start watching the given prefix for changes, and update the subscribers.
Deregister implements Instancer.
Register implements Instancer.
Stop terminates the Instancer.
Registrar registers service instance liveness information to etcd.
NewRegistrar returns a etcd Registrar acting on the provided catalog registration (service).
Deregister implements the sd.Registrar interface. Call it when you want your service to be deregistered from etcd, typically just prior to shutdown.
Register implements the sd.Registrar interface. Call it when you want your service to be registered in etcd, typically at startup.
type Service struct { Key string // unique key, e.g. "/service/foobar/1.2.3.4:8080" Value string // returned to subscribers, e.g. "" TTL *TTLOption DeleteOptions *etcd.DeleteOptions }
Service holds the instance identifying data you want to publish to etcd. Key must be unique, and value is the string returned to subscribers, typically called the "instance" string in other parts of package sd.
TTLOption allow setting a key with a TTL. This option will be used by a loop goroutine which regularly refreshes the lease of the key.
NewTTLOption returns a TTLOption that contains proper TTL settings. Heartbeat is used to refresh the lease of the key periodically; its value should be at least 500ms. TTL defines the lease of the key; its value should be significantly greater than heartbeat.
Good default values might be 3s heartbeat, 10s TTL.
Package etcd imports 13 packages (graph) and is imported by 3 packages. Updated 2017-09-18. Refresh now. Tools for package owners.
|
https://godoc.org/github.com/go-kit/kit/sd/etcd
|
CC-MAIN-2017-51
|
refinedweb
| 897
| 52.46
|
Getting Started With WebAssembly
WebAssembly is a new technology that makes it possible to run highly performant, low-level code in the browser. It can be used to bring large C and C++ codebases like games, physics engines and even desktop apps to the web platform.
As of right now, WebAssembly can be used in Chrome and Firefox, with Edge and Safari support almost complete as well. This means that very soon, you will be able to run wasm in every popular web browser.
In this lesson, we will be demonstrating how to compile a simple C file down to wasm and include it in a web page.
How Does WebAssembly Work?
First, a quick overview on what WebAssembly actually does. We'll try not to get too technical here.
In browsers today, JavaScript is executed in a virtual machine (VM) which optimizes your code and squeezes every ounce of performance. As things stand, JS is one of the fastest dynamic languages around. Even though it is fast, it still can't compete with raw C and C++ code. This is where WebAssembly comes in.
Wasm runs in the same JavaScript VM, but performs much better. The two can communicate freely and don't exclude each other. This way you can have the best of both worlds - JavaScript's huge ecosystem and friendly syntax, combined with the near-native performance of WebAssembly.
Most people write WebAssembly modules in C and compile them to .wasm files. These wasm files aren't recognized by the browser directly, so they need something called JavaScript glue code to be loaded.
In the future, this process will likely be shortened with WebAssembly frameworks and native wasm module support.
What You'll Need For This Lesson
You need quite a bit of tooling for writing Web Assembly. However, most things on the list are very common and you probably have them available already.
- Browser with support for WebAssembly, an up-to-date Chrome or Firefox should do the trick (caniuse)
- C to WebAssembly compiler, we will be using Emscripten portable.
- A compiler for C (GCC on Linux, Xcode on OS X, Visual Studio for Windows).
- Simple local web server to run the example (e.g.
python -m SimpleHTTPServer 9000)
Installing Emscripten takes a while and is definitely not fun, but it's the most recommended compiler right now. Also, make sure you have enough free hard drive space, it took up nearly 1GB on my machine.
Step 1: Writing C Code
We'll create a super simple C example that picks a random number between 1 and 6. In a working directory of your choice, make a new dice-roll.c file.
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <emscripten/emscripten.h> int main(int argc, char ** argv) { printf("WebAssembly module loaded\n"); } int EMSCRIPTEN_KEEPALIVE roll_dice() { srand ( time(NULL) ); return rand() % 6 + 1; }
When we compile to wasm and load this code into the browser, the main will be automatically executed. The
printf inside of it will be translated into a
console.log and called.
We want the
roll_dice function to be available in the JavaScript whenever we need it to. To tell the Emscripten compiler our intentions we have to add EMSCRIPTEN_KEEPALIVE.
Step 2: Compile C to WebAssembly
Now that we have our simple c program, we need to compile it into wasm. Not only that, but we also need to generate JavaScript glue code that will help us actually run it.
Here we have to use the Emscripten compiler. There are tons of CLI options available and lots of different approaches. We found the following combination most user-friendly:
emcc dice-roll.c -s WASM=1 -O3 -o index.js
Here is a breakdown of what's happening:
- emcc - The Emscripten compiler.
- dice-roll.c - The input file containing our C code.
- -s WASM=1 - Specify we are working with WebAssembly.
- -03 - The level of code optimization we want, 3 is pretty high.
- -o index.js - Tells emcc to generate a JS file with all the needed glue code for our wasm module.
After running the command, in our working directory will be added two files: index.wasm and index.js. They hold the WebAssembly module and its glue code, respectively.
Although these emcc options work well for our example, in more complex situations a different approach might be better. You can read more here.
Step 3: Load WebAssembly Code In The Browser
Now we are in familiar web dev territory. We create a basic
index.html file and include the JavaScript glue code in a script tag.
<!DOCTYPE html> <head> <meta charset="utf-8"> <meta http- <title>WebAssembly Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <!-- Include the JavaScript glue code. --> <!-- This will load the WebAssembly module and run its main. --> <script src="index.js"></script> </body> </html>
Because of cross-origin issues, to run the project we will need a local web server. On Linux/OS X you can start one by running the following code in the project directory:
python -m SimpleHTTPServer 9000
Now in the browser, go to localhost:9000 to view the app. If you open the browser console, there should be the greeting message we
printf-ed in the main of our C code:
Step 4: Call WebAssembly Functions
The last step of our experiment is to connect JavaScript and WebAssembly (just like in the wasm logo). This is actually very easy tanks to the JavaScript glue code generated from Emscripten. It handles all the wiring for us.
There is a pretty powerful API for working with WebAssembly in the browser. We won't get into it in detail as it is way beyond the scope of this tutorial. The only parts we will need are the Module interface and its
ccall method. This method allows us to call a function from the C code by name, and use it just like a JS one.
var result = Module.ccall( 'funcName', // name of C function 'number', // return type ['number'], // argument types [42]); // arguments
After the ccall, in
result we will have whatever is returned from the respective C function. All arguments apart from the first one are optional.
A shortened version is also available:
// Call a C function by adding an underscore in front of its name: var result = _funcName();
Our
roll_dice C function doesn't require any parameters. Calling it in the JavaScript code is super easy:
// When a HTML dice is clicked, it's value will change. var dice = document.querySelector('.dice'); dice.addEventListener('click', function(){ // Make a call to the roll_dice function from the C code. var result = _roll_dice(); dice.className = "dice dice-" + result; });
If your browser supports WebAssembly (caniuse), you should be able to see the working demo below.
Conclusion
We may still be in the early stages of WebAssembly but the new standard already shows its huge potential. The ability to run fast low-level code in the browser will give way to new apps and web experiences not possible with JavaScript alone.
Admittedly, working with WebAssembly is a bit tedious at the moment. The documentation is split over several places, tools are difficult to use, and you need JavaScript glue code to require wasm modules. All of these issues should be resolved as more and more people get into the new platform.
Presenting Bootstrap Studio
a revolutionary tool that developers and designers use to create
beautiful interfaces using the Bootstrap Framework.
Looks like the line
#include <time.h>is missing in dice-roll.c. That's preventing the compilation from completing. Once you add it the error
dice-roll.c:10:11: error: implicit declaration of function 'time' is invalid in C99 [-Werror,-Wimplicit-function-declaration] srand(time(NULL));should go away and the index.js and index.wasm files will be generated. Great intro to WebAssembly though! I really enjoyed it.
I'm glad you liked the tutorial, Webmley!
Sorry, I forgot to add
time.hto the article. Thanks for pointing that out. I'll fix it asap.
wow, saw many articles about web assembly and still didnt get the real picture, last time i heard about was when i watched a video about react developers talking about it . Thanks :)
I had an issue using the shorthand version "var result = _roll_dice();" in the javascript. It could not find the method.
So I changed it to "var result = Module.ccall('roll_dice', 'number');" and it worked just fine. You may want to change it to the long hand version as it seems to be more compatible.
I'm using Visual Studio Code on Windows 10 with Firefox on the included python http server.
Thank you so much for this tutor, I have been attempting to wrap my head around this.
|
https://tutorialzine.com/2017/06/getting-started-with-web-assembly
|
CC-MAIN-2017-34
|
refinedweb
| 1,465
| 66.33
|
Background
I’ve been recently working on a project to create a content feed like Instagram and Facebook. There are various available content types including photos, videos, blog posts, and surveys.
The feed can be sorted in different ways such as newer content first, sort by popularity, and random order. For the default sort order, we have decided to show a random assortment of content, but we don’t want the same content type to appear twice in a row.
Naturally, I began searching the internet to see if someone else had already come up with this algorithm, but most of the algorithms I found were about shuffling and removing duplicates altogether. I did however find a Stack Overflow question about the same idea, but the top answer was not a perfect solution.
I then went to the whiteboard and took on the challenge of finding a working and relatively optimized algorithm.
Do it yourself
One of the best ways to create algorithms is by defining the problem, choosing a sample input, and solving it yourself while explaining the steps throughout the way.
Problem: Given a list of items of various types, produce a randomized list without two consecutive repeated types.
Sample input:
[A,A,A,A,B,B,B,C,C,D]
Valid output:
[C,A,D,B,A,B,A,C,A,B]
To solve this problem manually, we first need to shuffle the input list. Let’s suppose that
[B,A,C,C,A,A,D,B,A,B] is sufficiently randomized.
Starting from the first item, B, we keep going to the right and check if the next item is the same as the last one. The first consecutive repeat has occurred at the location of item 4, C. We set this item aside and continue moving to the right. Another repeated item, A, is found next.
Note that you should never modify the original list while iterating over it. While it may not be obvious to humans, it does create a bunch of unwanted side-effects for the computer. For instance, the iterator may not be aware of changes made to the list and can behave differently. How about indices? Altering the list changes the index-based reference and causes confusion.
Once we have identified the repeated items, we look for places in between existing items where they can fit. The final sorted list is
[B,A,C,A,C,A,D,B,A,B].
Making flowcharts
We can create flowcharts to visualize algorithms. Depending on the complexity of the algorithm, you may sometimes choose to skip this step and directly write code, but try making a flowchart first — it saves a lot of time and makes coding easier.
In the last step of our manual solution, we had to find new locations for the repeated items to avoid consecutive repeats. Although it seems trivial to our brains, there are actually multiple ways of doing this, but not all paths lead to an acceptable outcome. I’ve created a Whimsical board with 3 different algorithm flowcharts.
My winning algorithm starts by shuffling the input list. It then creates two empty lists: a list for sorted items and one for repeated items. Next, it loops over the randomized list. If the current item is different than the last item, it adds it to the list of sorted items. Otherwise, the item gets added to the list of repeated items.
Once the first iteration is over, it repeatedly loops over the sorted list and tries to find spots where it can place the repeated items. When either no repeated items remain or it cannot find somewhere to fit them, the iteration stops and it returns the sorted list merged with the remaining repeated items.
Turning it into code
My current favorite language for prototyping algorithms is Python, primarily because it doesn’t have curly brackets and has handy built-in functions like
random.shuffle().
import random def randomize_list(input_list): randomized_list = input_list.copy() random.shuffle(randomized_list) return randomized_list def get_repeated_items(input_list, type_key): repeated_items = [] pre_sorted_list = [] last_item = {} for item in input_list: if last_item and item[type_key] == last_item[type_key]: repeated_items.append(item) continue pre_sorted_list.append(item) last_item = item return repeated_items, pre_sorted_list def recycle_repeated_items(repeated_items, pre_sorted_list, type_key): sorted_list = [] last_item = {} changed = False for item in pre_sorted_list: filtered_types = [item[type_key]] + ([last_item[type_key]] if last_item else []) eligible_repeated_item = next(filter(lambda t: t[type_key] not in filtered_types, repeated_items), None) if eligible_repeated_item: changed = True repeated_items.remove(eligible_repeated_item) sorted_list.append(eligible_repeated_item) sorted_list.append(item) last_item = item return repeated_items, sorted_list, changed def randomized_non_repeating_sort(input_list, type_key): randomized_list = randomize_list(input_list) repeated_items, sorted_list = get_repeated_items(randomized_list, type_key) repeated_items, sorted_list, changed = recycle_repeated_items(repeated_items, sorted_list, type_key) while repeated_items and changed: repeated_items, sorted_list, changed = recycle_repeated_items(repeated_items, sorted_list, type_key) return sorted_list + repeated_items
I wrote the test below to make sure it works and measure how well it performs under heavy load:
original_list = [ {'id': 10, 'type': 'A'}, {'id': 11, 'type': 'A'}, {'id': 12, 'type': 'A'}, {'id': 13, 'type': 'A'}, {'id': 14, 'type': 'B'}, {'id': 15, 'type': 'B'}, {'id': 16, 'type': 'B'}, {'id': 17, 'type': 'C'}, {'id': 18, 'type': 'C'}, {'id': 19, 'type': 'D'} ] print('Original list:') print(original_list) print('Randomized non-repeating list (1 of 1,000,000 tests):') for _ in range(1,1000000): output_list = randomized_non_repeating_sort(original_list, 'type') repeated_items = get_repeated_items(output_list, 'type')[0] if repeated_items: raise Exception('CONSECUTIVE REPEATED ITEM FOUND!') if len(output_list) != len(original_list): raise Exception('LIST LENGTH MISMATCH!') print(output_list) """ Output: [{'id': 15, 'type': 'B'}, {'id': 10, 'type': 'A'}, {'id': 17, 'type': 'C'}, {'id': 12, 'type': 'A'}, {'id': 19, 'type': 'D'}, {'id': 13, 'type': 'A'}, {'id': 18, 'type': 'C'}, {'id': 16, 'type': 'B'}, {'id': 11, 'type': 'A'}, {'id': 14, 'type': 'B'}] """
I ran the code with PyCharm’s profiler and found that it takes 0.018702 seconds to sort a list of 10 items.
It’s a great starting point, but there is definitely room for optimization!
This post was originally published on my blog where I write all about tech.
Discussion (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/themreza/random-sort-algorithm-without-consecutive-repeats-4no2
|
CC-MAIN-2022-33
|
refinedweb
| 989
| 51.28
|
Jared Hanson has been involved with the D community since 2012, and an active contributor since 2013. Recently, he joined the Phobos team and devised a scheme to make it look like he’s contributing by adding at least 1 tag to every new PR. He holds a Bachelor of Computer Science degree from the University of New Brunswick and works as a Level 3 Support Engineer at one of the largest cybersecurity companies in the world.
I recently read a great article by Matt Kline on how std::visit is everything wrong with modern C++. My C++ skills have grown rusty from disuse (I have long since left for the greener pastures of D), but I was curious as to how things had changed in my absence.
Despite my relative unfamiliarity with post–2003 C++, I had heard about the addition of a library-based sum type in
std for C++17. My curiosity was mildly piqued by the news, although like many new additions to C++ in the past decade, it’s something D has had for years. Given the seemingly sensational title of Mr. Kline’s article, I wanted to see just what was so bad about
std::visit, and to get a feel for how well D’s equivalent measures up.
My intuition was that the author was exaggerating for the sake of an interesting article. We’ve all heard the oft-repeated criticism that C++ is complex and inconsistent (even some of its biggest proponents think so), and it is true that the ergonomics of templates in D are vastly improved over C++. Nevertheless, the underlying concepts are the same; I was dubious that
std::visit could be much harder to use than
std.variant.visit, if at all.
For the record, my intuition was completely and utterly wrong.
Exploring std.variant
Before we continue, let me quickly introduce D’s std.variant module. The module centres around the Variant type: this is not actually a sum type like C++’s
std::variant, but a type-safe container that can contain a value of any type. It also knows the type of the value it currently contains (if you’ve ever implemented a type-safe union, you’ll realize why that part is important). This is akin to C++’s
std::any as opposed to
std::variant; very unfortunate, then, that C++ chose to use the name
variant for its implementation of a sum type instead. C’est la vie. The type is used as follows:
import std.variant; Variant a; a = 42; assert(a.type == typeid(int)); a += 1; assert(a == 43); float f = a.get!float; //convert a to float assert(f == 43); a /= 2; f /= 2; assert(a == 21 && f == 21.5); a = "D rocks!"; assert(a.type == typeid(string)); Variant b = new Object(); Variant c = b; assert(c is b); //c and b point to the same object b /= 2; //Error: no possible match found for Variant / int
Luckily,
std.variant does provide a sum type as well: enter Algebraic. The name
Algebraic refers to algebraic data types, of which one kind is a “sum type”. Another example is the tuple, which is a “product type”.
In actuality,
Algebraic is not a separate type from
Variant; the former is an alias for the latter that takes a compile-time specified list of types. The values which an
Algebraic may take on are limited to those whose type is in that list. For example, an
Algebraic!(int, string) can contain a value of type
int or
string, but if you try to assign a
string value to an
Algebraic!(float, bool), you’ll get an error at compile time. The result is that we effectively get an in-library sum type for free! Pretty darn cool. It’s used like this:
alias Null = typeof(null); //for convenience alias Option(T) = Algebraic!(T, Null); Option!size_t indexOf(int[] haystack, int needle) { foreach (size_t i, int n; haystack) if (n == needle) return Option!size_t(i); return Option!size_t(null); } int[] a = [4, 2, 210, 42, 7]; Option!size_t index = a.indexOf(42); //call indexOf like a method using UFCS assert(!index.peek!Null); //assert that `index` does not contain a value of type Null assert(index == size_t(3)); Option!size_t index2 = a.indexOf(117); assert(index2.peek!Null);
The
peek function takes a
Variant as a runtime argument, and a type
T as a compile-time argument. It returns a pointer to
T that points to the
Variant’s contained value iff the
Variant contains a value of type
T; otherwise, the pointer is
null.
Note: I’ve made use of Universal Function Call Syntax to call the free function
indexOf as if it were a member function of
int[].
In addition, just like C++, D’s standard library has a special
visit function that operates on
Algebraic. It allows the user to supply a visitor for each type of value the
Algebraic may hold, which will be executed iff it holds data of that type at runtime. More on that in a moment.
To recap:
std.variant.Variantis the equivalent of
std::any. It is a type-safe container that can contain a value of any type.
std.variant.Algebraicis the equivalent of
std::variantand is a sum type similar to what you’d find in Swift, Haskell, Rust, etc. It is a thin wrapper over
Variantthat restricts what type of values it may contain via a compile-time specified list.
std.variantprovides a
visitfunction akin to
std::visitwhich dispatches based on the type of the contained value.
With that out of the way, let’s now talk about what’s wrong with
std::visit in C++, and how D makes
std.variant.visit much more pleasant to use by leveraging its powerful toolbox of compile-time introspection and code generation features.
The problem with std::visit
The main problems with the C++ implementation are that – aside from clunkier template syntax – metaprogramming is very arcane and convoluted, and there are very few static introspection tools included out of the box. You get the absolute basics in
std::type_traits, but that’s it (there are a couple third-party solutions, which are appropriately horrifying and verbose). This makes implementing
std::visit much more difficult than it has to be, and also pushes that complexity down to consumers of the library, which makes using it that much more difficult as well. My eyes bled at this code from Mr. Kline’s article which generates a visitor struct from the provided lambda functions:
template <class... Fs> struct overload; template <class F0, class... Frest> struct overload<F0, Frest...> : F0, overload<Frest...> { overload(F0 f0, Frest... rest) : F0(f0), overload<Frest...>(rest...) {} using F0::operator(); using overload<Frest...>::operator(); }; template <class F0> struct overload<F0> : F0 { overload(F0 f0) : F0(f0) {} using F0::operator(); }; template <class... Fs> auto make_visitor(Fs... fs) { return overload<Fs...>(fs...); }
Now, as he points out, this can be simplified down to the following in C++17:
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; template <class... Fs> auto make_visitor(Fs... fs) { return overload<Fs...>(fs...); }
However, this code is still quite ugly (though I suspect I could get used to the elipses syntax eventually). Despite being a massive improvement on the preceding example, it’s hard to get right when writing it, and hard to understand when reading it. To write (and more importantly, read) code like this, you have to know about:
- Templates
- Template argument packs
- SFINAE
- User-defined deduction guides
- The ellipsis operator (…)
- Operator overloading
- C++-specific metaprogramming techniques
There’s a lot of complicated template expansion and code generation going on, but it’s hidden behind the scenes. And boy oh boy, if you screw something up you’d better believe that the compiler is going to spit some supremely perplexing errors back at you.
Note: As a fun exercise, try leaving out an overload for one of the types contained in your
variant and marvel at the truly cryptic error message your compiler prints.
Here’s an example from cppreference.com showcasing the minimal amount of work necessary to use
std::visit:
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; using var_t = std::variant<int, long, double, std::string>; std::vector<var_t> vec = {10, 15l, 1.5, "hello"}; for (auto& v: vec) { std::visit(overloaded { [](auto arg) { std::cout << arg << ' '; }, [](double arg) { std::cout << std::fixed << arg << ' '; }, [](const std::string& arg) { std::cout << std::quoted(arg) << ' '; }, }, v); }
Note: I don’t show it in this article, but if you want to see this example re-written in D, it’s here.
Why is this extra work forced on us by C++, just to make use of
std::visit? Users are stuck between a rock and a hard place: either write some truly stigmata-inducing code to generate a struct with the necessary overloads, or bite the bullet and write a new struct every time you want to use
std::visit. Neither is very appealing, and both are a one-way ticket to Boilerplate Hell. The fact that you have to jump through such ridiculous hoops and write some ugly-looking boilerplate for something that should be very simple is just… ridiculous. As Mr. Kline astutely puts it:
The rigmarole needed for
std::visitis entirely insane.
We can do better in D.
The D solution
This is how the typical programmer would implement
make_visitor, using D’s powerful compile-time type introspection tools and code generation abilities:
import std.traits: Parameters; struct variant_visitor(Funs...) { Funs fs; this(Funs fs) { this.fs = fs; } static foreach(i, Fun; Funs) //Generate a different overload of opCall for each Fs auto opCall(Parameters!Fun params) { return fs[i](params); } } auto make_visitor(Funs...)(Funs fs) { return variant_visitor!Funs(fs); }
And… that’s it. We’re done. No pain, no strain, no bleeding from the eyes. It is a few more lines than the C++ version, granted, but in my opinion, it is also much simpler than the C++ version. To write and/or read this code, you have to understand a demonstrably smaller number of concepts:
- Templates
- Template argument packs
- static foreach
- Operator overloading
However, a D programmer would not write this code. Why? Because
std.variant.visit does not take a callable struct. From the documentation:
Applies a delegate or function to the given Algebraic depending on the held type, ensuring that all types are handled by the visiting functions. Visiting handlers are passed in the template parameter list. (emphasis mine)
So
visit only accepts a
delegate or
function, and figures out which one to pass the contained value to based on the functions’ signatures.
Why do this and give the user fewer options? D is what I like to call an anti-boilerplate language. In all things, D prefers the most direct method, and thus,
visit takes a compile-time specified list of functions as template arguments.
std.variant.visit may give the user fewer options, but unlike
std::visit, it does not require them to painstakingly create a new struct that overloads
opCall for each case, or to waste time writing something like
make_visitor.
This also highlights the difference between the two languages themselves. D may sometimes give the user fewer options (don’t worry though – D is a systems programming language, so you’re never completely without options), but it is in service of making their lives easier. With D, you get faster, safer code, that combines the speed of native compilation with the productivity of scripting languages (hence, D’s motto: “Fast code, fast”). With
std.variant.visit, there’s no messing around defining structs with callable methods or unpacking tuples or wrangling arguments; just straightforward, understandable code:
Algebraic!(string, int, bool) v = "D rocks!"; v.visit!( (string s) => writeln("string: ", s), (int n) => writeln("int: ", n), (bool b) => writeln("bool: ", b), );
And in a puff of efficiency, we’ve completely obviated all this machinery that C++ requires for
std::visit, and greatly simplified our users’ lives.
For comparison, the C++ equivalent:
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; std::variant<std::string, int, bool> v = "C++ rocks?"; std::visit(overloaded { [](const std::string& s) { std::cout << s << '\n'; }, [](int n) { std::cout << n << '\n'; }, [](bool b) { std::cout << b << '\n'; } }, v);
Note: Unlike the C++ version, the error message you get when you accidentally leave out a function to handle one of the types is comprehendable by mere mortals. Check it out for yourself.
As a bonus, our D example looks very similar to the built-in pattern matching syntax that you find in many up-and-coming languages that take inspiration from their functional forebears, but is implemented completely in user code.
That’s powerful.
Other considerations
As my final point – if you’ll indulge me for a moment – I’d like to argue with a strawman C++ programmer of my own creation. In his article, Mr. Kline also mentions the new if constexpr feature added in C++17 (which of course, D has had for over a decade now). I’d like to forestall arguments from my strawman friend such as:
But you’re cheating! You can use the new
if constexprto simplify the code and cut out
make_visitorentirely, just like in your D example!
Yes, you could use
if constexpr (and by the same token,
static if in D), but you shouldn’t (and Mr. Kline explicitly rejects using it in his article).There are a few problems with this approach which make it all-around inferior in both C++ and D. One, this method is error prone and inflexible in the case where you need to add a new type to your
variant/
Algebraic. Your old code will still compile but will now be wrong. Two, doing it this way is uglier and more complicated than just passing functions to
visit directly (at least, it is in D). Three, the D version would still blow C++ out of the water on readability. Consider:
//D v.visit!((arg) { alias T = Unqual!(typeof(arg)); //Remove const, shared, etc. static if (is(T == string)) { writeln("string: ", arg); } else static if (is(T == int)) { writeln("int: ", arg); } else static if (is(T == bool)) { writeln("bool: ", arg); } });
vs.
//C++ visit([](auto& arg) { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, string>) { printf("string: %s\n", arg.c_str()); } else if constexpr (std::is_same_v<T, int>) { printf("integer: %d\n", arg); } else if constexpr (std::is_same_v<T, bool>) { printf("bool: %d\n", arg); } }, v);
Which version of the code would you want to have to read, understand, and modify? For me, it’s the D version – no contest.
If this article has whet your appetite and you want to find out more about D, you can visit the official Dlang website, and join us on the mailing list or #D on IRC at freenode.net. D is a community-driven project, so we’re also always looking for people eager to jump in and get their hands dirty – pull requests welcome!.
5 thoughts on “std.variant Is Everything Cool About D”
those printfs in the last one really hurt
Great article Jared, thanks! Also, I think there’s a small mistake in your last C++ example, ‘is_same’ should be ‘is_same::value’.
It seems the comment section doesn’t like less-than/greater-than. ::value should be after greater-than in the ‘if constexpr’ condition.
Thanks, I copied the code verbatim from Matt’s article and didn’t check that it actually compiled.
Great article, I even didn’t know about the visit method.
Nonetheless, I’m a bit frustrated with dlangs algebraic/variant types as they should represent Union Types (untagged unions) found in other languages and not sum types (tagged unions) and therefore inherently including implicit conversion between Union types which is not done in dlang, e.g.
int i=1;double d=1.0, string s=”hello”
void fun(Algebraic!(int,double,string) a) {writenln(“Algebraic!(int,double,string)”)}
void fun(string a) {writenln(“string”)}
void fun(Algebraic!(int,float) a) {writenln(“Algebraic!(int,float)”)}
fun(i)//Algebraic!(int,float)
fun(s)//string
fun(d)//Algebraic!(int,double,string)
Also, this is a key property of union types (a.k.a existential types):
int gun(int i)=return i+1
double gun(double d)=return d/2
string gun(string s)=return s+” “+”world”
Algebraic!(int,double,string) a=”hello”
gun(a)//hello world, //always valid even if a gets initialized with integer or double
|
https://dlang.org/blog/2018/03/29/std-variant-is-everything-cool-about-d/?replytocom=6371
|
CC-MAIN-2020-50
|
refinedweb
| 2,783
| 55.74
|
CodePlexProject Hosting for Open Source Software
Dear forum,
I have a very serious problem:
I have made an ascx that stores some information in the Session state:
HttpContext.Current.Session["myvar"] = myObject;
The problem is, that every user on the page seems to SHARE the same session (??).
This is a huge problem since users will overwrite the content of each other sessionvariables.
Also it seems that the session is very slow. When putting something in the SessionState variable - it takes 30-60 seconds before I can read the variable.
I have tried my ascx on a simple site on the same server - not composite, but just a plain .Net 4.0 og IIS 7.5. Here the session variables are private to each session as they should be. And there is no delay putting something into the session variables.
Please help me. This is completely destroying my usage of Composite C1... :-(
Wow, that sure seems like a very serious problem. Is it possible for you to paste all of your usercontrol here or maybe send it to per. email, and i will take a look. (pst at punktum dot gl)
Thank you for answering!
Of course I will provide the code.
I will have to simplify the control to keep the complexity down. My real ascx uses a DAL and BLL to work.
I will recreate the problem using a very simple ascx and be back in a few minutes.
I expect this is page output caching that is at play here.
Try turning of ASP.NET Full Page Caching - edit ~/Renderers/Page.aspx and delete the cache directive.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Dummy.ascx.cs" Inherits="Inface.WebShopControls.Dummy" %>
<div>
<h2>
Dummy demo</h2>
<h3>
Please fill in the form below to login</h3>
<asp:TextBox</asp:TextBox>
<asp:Button
<asp:Button
<div>
<asp:Literal
</div>
</div>
Code behind
using System;
namespace Inface.WebShopControls {
public partial class Dummy : System.Web.UI.UserControl {
protected void Page_PreRender(object sender, EventArgs e) {
litLoginResult.Text = (string)Session["LOGIN"];
}
protected void btnLogin_Clicked(object sender, EventArgs e) {
Session["LOGIN"] = tbxEmail.Text;
}
protected void btnLogout_Clicked(object sender, EventArgs e) {
Session["LOGIN"] = "";
}
}
}
The result: A user types something in the tbxEmail - it will show at the litLoginResult.Text.
But when reloading the page, it will not be shown. After 45-60 seconds it will show up. Then it will show up for every user.
When making this simple edition - I began to suspect cache as well. And
the answer from mawtex has shown to be correct.
Even though, I will post the entire code for the sake of the discussion to be usable for other users as well. :-)
Hi,
You are absolute correct!
This IS the issue.
Information from the database accessible only for a logged in user, was shown to all users (even those, not logged in). The problem was a common cache!
I wonder if there is any way to still use the cache, but avoid caching of User Control content? Anyone?
Thank to both of you (burningice and mawtex).
This saved my day!
>> I wonder if there is any way to still use the cache, but avoid caching of User Control content? Anyone?
Yes, there is. You can make user id a part of cache key, so different users will have different cache entries ()
The quickest way to do it is to edit global.asax.
Find
public override string GetVaryByCustomString(HttpContext context, string custom)
{
return ApplicationLevelEventHandlers.GetVaryByCustomString(context, custom) ?? base.GetVaryByCustomString(context, custom);
}
Replace with */;
}
I re-read the question and understood that haven't answered it correctly. With standard asp.net caching you can
1) Cache the whole page
2) Cache some controls
Standard asp.net caching does not support logic "cache everything except for some controls" since it caches the page as a text rather than a tree of controls, so it cannot render just some controls without building a page.
There're some workarounds, how to reuse the asp.net's full page caching and still have controls that are not affected. But they're kind of "hardcore" and it is easier just to use 2) on those controls that do hit the performance. Until it is a problem
there's no point in spending time on it.
Thanks a lot.
I definitely will go with number 2 - the controls form a b2b webshop and the load on it is not that high. Anyway it would have been nice to still cache the public parts of the site, but there really is no performance argument for doing it in this case.
No worries - with ASP.NET you can have your cake and eat it too ;-)
Reintroduce full page caching and then add the code below to controls that contain sensitive data:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoServerCaching();
HttpContext.Current.Response.Cache.SetNoStore();
This will disable full page caching for the current request.
There is also a C1 Function you can add to pages/templates/XSLT output etc. that does the job (disable caching for a given request): Composite.Web.Response.SetServerPageCacheDuration
var cache = Response.Cache;
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetNoServerCaching();
cache.SetNoStore();
( just making sure we're writing optimal code :) )
Hi.
I am trying to implement a simple Webshop with Composite and Mvc..
Where should I use burningice's suggestion?
tryed this:
public class BasketController : Controller { public ActionResult Index() { var cache = Response.Cache; cache.SetCacheability(HttpCacheability.NoCache); cache.SetNoServerCaching(); cache.SetNoStore();
.... rest here:
Dosents seems to work..
Hope someone can help.
If by "doesn't work" you mean it doesn't compile, try
var cache = System.Web.HttpContext.Current.Response.Cache;
...
It compiles fine, but it still catches my request to the controller..
When i delete the cache directive at ~/Renderers/Page.aspx everything works.
Could i somehow cache the site, except the request to the MVC controller?
or should I somehow add "Composite.Web.Response.SetServerPageCacheDuration" to all MvcPlayer functions?
It is a bug in the current version of the MVC player - all the MVC calls are executed in separate requests, so when you disable caching in from the controller, it does not affect the original http request. Until we fixed the player, I'd recommend just to
turn off the asp.net caching.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later.
|
https://c1cms.codeplex.com/discussions/240276
|
CC-MAIN-2017-26
|
refinedweb
| 1,079
| 67.86
|
< Projects | NepomukRevision as of 17:48, 1 August 2012 by Vishesh (talk | contribs) (→Basic Terminology)(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff) Nepomuk Quickstart Tutorial Series Nepomuk Previous Getting started with KDE development What's Next Handle Resource Metadata with Nepomuk Further Reading n/a This page serves as a very simple overview to Nepomuk. It focuses on getting started with Nepomuk and tries not to deal with internal Nepomuk concepts. Please keep in the mind that the processes described here are targeted to the general use case. If you have a more specialized use case in mind, this might not be the best way to use the Nepomuk libraries. Contents 1 Libraries and Headers 1.1 Headers 1.2 CMake 2 Basic Terminology 3 Tags and Ratings 3.1 Setting Tags 3.2 Retrieving Tags 3.3 Listing Tags 3.4 Ratings 4 Dealing with files 5 Working Example Libraries and Headers Most of the non graphic parts of Nepomuk are present in the NepomukCore repositories.. Headers> CMake KDE Projects generally use cmake as a build tool. Nepomuk is no different. In order to use Nepomuk you need to add the relevant macros for Nepomuk in your CMakeLists.txt. find_package(NepomukCore REQUIRED) target_link_libraries(myfile ${NEPOMUK_CORE_LIBRARY} ) Basic Terminology. Tags and Ratings Every tag in Nepomuk is a Resource. In fact the Tag class is also derived from the Resource class. Setting Tags. Retrieving Tags. Listing Tags();(); Ratings Every resource in Nepomuk can be given a numeric rating. It is generally done on a scale of 0-10. using namespace Nepomuk2; File fileRes( urlOfTheFile ); int rating = fileRes.rating(); rating = rating + 1; fileRes.setRating( rating ); Dealing with files. Working Example We understand that using a new framework such as Nepomuk can be quite intimidating at times. Therefore, we though it would be nice to have a working example for you to get started with - ADD THE KDEEXAMPLES stuff ... Retrieved from "" Category: Tutorial Content is available under Creative Commons License SA 4.0 unless otherwise noted.
|
https://techbase.kde.org/index.php?title=Projects/Nepomuk/QuickStart&direction=next&oldid=74150
|
CC-MAIN-2020-29
|
refinedweb
| 335
| 59.09
|
Code blocks
Code blocks within documentation are super-powered 💪.
#Code title
You can add a title to the code block by adding
title key after the language (leave a space between them).
#Syntax highlighting
Code blocks are text blocks wrapped around by strings of 3 backticks. You may check out this reference for specifications of MDX.
Use the matching language meta string for your code block, and Docusaurus will pick up syntax highlighting automatically, powered by Prism React Renderer.
By default, the Prism syntax highlighting theme we use is Palenight. You can change this to another theme by passing
theme field in
prism as
themeConfig in your docusaurus.config.js.
For example, if you prefer to use the
dracula highlighting theme:
By default, Docusaurus comes with a subset of commonly used languages.
caution
Some popular languages like Java, C#, or PHP are not enabled by default.
To add syntax highlighting for any of the other Prism supported languages, define it in an array of additional languages.
For example, if you want to add highlighting for the
powershell language:
If you want to add highlighting for languages not yet supported by Prism, you can swizzle
prism-include-languages:
- npm
- Yarn
It will produce
prism-include-languages.js in your
src/theme folder. You can add highlighting support for custom languages by editing
prism-include-languages.js:
You can refer to Prism's official language definitions when you are writing your own language definitions.
#Line highlighting
You can bring emphasis to certain lines of code by specifying line ranges after the language meta string (leave a space after the language).
To accomplish this, Docusaurus adds the
docusaurus-highlight-code-line class to the highlighted lines. You will need to define your own styling for this CSS, possibly in your
src/css/custom.css with a custom background color which is dependent on your selected syntax highlighting theme. The color given below works for the default highlighting theme (Palenight), so if you are using another theme, you will have to tweak the color accordingly.
To highlight multiple lines, separate the line numbers by commas or use the range syntax to select a chunk of lines. This feature uses the
parse-number-range library and you can find more syntax on their project details.
You can also use comments with
highlight-next-line,
highlight-start, and
highlight-end to select which lines are highlighted.
Supported commenting syntax:
If there's a syntax that is not currently supported, we are open to adding them! Pull requests welcome.
#Interactive code editor
You can create an interactive coding editor with the
@docusaurus/theme-live-codeblock plugin.
First, add the plugin to your package.
- npm
- Yarn
You will also need to add the plugin to your
docusaurus.config.js.
To use the plugin, create a code block with
live attached to the language meta string.
The code block will be rendered as an interactive editor. Changes to the code will reflect on the result panel live.
SyntaxError: Unexpected token (1:8) 1 : return () ^
#Imports
react-live and imports
It is not possible to import components directly from the react-live code editor, you have to define available imports upfront.
By default, all React imports are available. If you need more imports available, swizzle the react-live scope:
- npm
- Yarn
The
ButtonExample component is now available to use:
SyntaxError: Unexpected token (1:8) 1 : return () ^
#Multi-language support code blocks
With MDX, you can easily create interactive components within your documentation, for example, to display code in multiple programming languages and switching between them using a tabs component.
Instead of implementing a dedicated component for multi-language support code blocks, we've implemented a generic Tabs component in the classic theme so that you can use it for other non-code scenarios as well.
The following example is how you can have multi-language code tabs in your docs. Note that the empty lines above and below each language block is intentional. This is a current limitation of MDX, you have to leave empty lines around Markdown syntax for the MDX parser to know that it's Markdown syntax and not JSX.
And you will get the following:
- JavaScript
- Python
- Java
You may want to implement your own
<MultiLanguageCode /> abstraction if you find the above approach too verbose. We might just implement one in future for convenience.
If you have multiple of these multi-language code tabs, and you want to sync the selection across the tab instances, refer to the Syncing tab choices section.
|
http://deploy-preview-4756--docusaurus-2.netlify.app/docs/next/markdown-features/code-blocks
|
CC-MAIN-2022-05
|
refinedweb
| 756
| 53.41
|
Hello to everybody,
I've got an asp application, each .aspx page inherits from a page called JAPage defined as this way :
public class JaPage : System.Web.UI.Page
{
public JaPage()
{
}
protected override void InitializeCulture()
{
string lang = String.Format("{0}", Session["Lang"]);
if (!String.IsNullOrEmpty(lang))
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
else
Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentUICulture;
}
}
When I use it on the aspx pages for example
public partial class Administrator_AdsList : JaPage
I got a red underline....... even on the Administrator_AdsList method I get Methods as Request/Response marked red ....
How To fix It?
Thanks in advance
P.S. : I forgot to say that my Japage.cs is defined inside the App_Code folder (I've got similar problem with all the classes inserted into this folder)
Edited by: Paolo Ponzano on Sep 4, 2008 12:41 PM
Specified More information
Hello to everybody,
Paolo, could you create a small sample solution for us?
--
Sergey V. Coox
JetBrains, Inc
"Develop with pleasure!"
I attched an image about this error, it seems ReSharper is caching some
files.
"J.W." <JSunnewsgroup@gmail.com> wrote in message
news:g9oqsp$mmp$1@is.intellij.net...
>
>
>>
>
>
Attachment(s):
Ambiguous refence.png
"Paolo Ponzano" <no_reply@jetbrains.com> wrote in message
news:10903311.101691220535810032.JavaMail.jive@app4.labs.intellij.net...
>
>
The same issue here, so you are not alone..
J.W.
Yeah , me too - the exact same problem. Also with an ASP.NET Project with Sources in the App_code-Folder ....
"amorph" <no_reply@jetbrains.com> wrote in message
news:13237989.102691220541687860.JavaMail.jive@app4.labs.intellij.net...
I hope a patch is coming soon, for now, it seems that I install too
quickly..
Count me in on people seeing this error. I get the ambiguous error regarding extending classes.
I just want JetBrains send a message to its users , it seems this bug
affects a lot of people.
"Ron Lamb" <no_reply@jetbrains.com> wrote in message
news:2921447.103571220550945874.JavaMail.jive@app4.labs.intellij.net...
Oh Yeah.. The source files it seems to effect is when I extand a file in my Controls directory with a class in App_Code.
Paolo,
what happens if you clear caches and reopen solution?
Could you describe your file structure? Is it a website or a web
application?
--
Sergey V. Coox
JetBrains, Inc
"Develop with pleasure!"
yup, seeing this too. I've cleared all cache directories, uninstalled 4.1, reinstalled, and it's still not recognising core asp.net elements.
Attached a screenshot, this exact file was working yesterday with 4.0, and has seen no changes other than an install (clean) of 4.1.
Please resolve this asap - I'm having to actually code for a living!
Attachment(s):
vs2008.gif
Hello J.W.,
We were not able to reproduce the problem, could you please send us sample
solution with the problem, or at least describe in details your configuration,
locations of files, project kinds, etc. Thanks.
Sincerely,
Ilya Ryzhenkov
JetBrains, Inc
"Develop with pleasure!"
J> "amorph" <no_reply@jetbrains.com> wrote in message
J> news:13237989.102691220541687860.JavaMail.jive@app4.labs.intellij.net
J> ...
J>
>> Yeah , me too - the exact same problem. Also with an ASP.NET Project
>> with Sources in the App_code-Folder ....
>>
J> I hope a patch is coming soon, for now, it seems that I install too
J> quickly..
J>
Hello Ron,
We were not able to reproduce the problem, could you please send us sample
solution with the problem, or at least describe in details your configuration,
locations of files, project kinds, etc. Thanks.
Sincerely,
Ilya Ryzhenkov
JetBrains, Inc
"Develop with pleasure!"
IR> Count me in on people seeing this error. I get the ambiguous
IR> error regarding extending classes.
IR>
Hello.....sorry for my delayed answer..... it's a web application, I've cleaned the cache file and the problems happens to me and to the other 2 guys work with me...
I am busy today, and my solution is too large.
I will check to see if I can make a small sample solution and send to you.
Do I get "free license" if I help you troubleshoot this issue :)
J.W.
"Ilya Ryzhenkov" <orangy@jetbrains.com> wrote in message
news:76a2bd0b16074d8cadd7781ea12f0@news.intellij.net...
>
>
>
>
>
>>> Yeah , me too - the exact same problem. Also with an ASP.NET Project
>>> with Sources in the App_code-Folder ....
>>>
Paolo,
We managed to reproduce the problem and fix the case. There will be a
nightly build tomorrow morning.
Hope it fix your problem. If not, we need a sample solution. If you don't
manage to narrow it down, we could sign an NDA in order to get your complete
sample.
NB The paragraph above applies to everyone who experience problems with
ReSharper. Being able to reproduce the issue we can (and will) provide a fix
quickly. Otherwise we cannot guarantee anything :(
PS Thanks for using ReSharper.
--
Sergey V. Coox
JetBrains, Inc
"Develop with pleasure!"
Hi Sergey,
it worked for me... thanks a lot!
Bests from italy
Paolo
It worked for me too..
"Paolo Ponzano" <no_reply@jetbrains.com> wrote in message
news:2758034.121521220944805541.JavaMail.jive@app4.labs.intellij.net...
>
Is there a way to get to the nightly build so I can see if this fixes my situation? I looked on the site and could not find where to download it.
Here you go
--
Sergey V. Coox
JetBrains, Inc
"Develop with pleasure!"
"WeeJavaDude" <no_reply@jetbrains.com> wrote in message
news:8665245.15311222276266818.JavaMail.jive@app4.labs.intellij.net...
Thanks.. Looks like that fixed my issue too and should help until the next release.
Me too, thanks.
Hello - pardon the late post. JetBrains - has this update made it into the released builds yet? I'm getting this error after downloading and installing Resharper 4.1 yesterday. I'm using VS 2008, trying to build a web folder (not application). Builds fine, but Resharper throws the 'Ambiguous Reference' errors. This appears somewhat related to file placement in the /App_Code folder.
Thanks,
wbrproductions
It happens even in 4.5 builds (1158 for example). I'll try to make a minimal soultion.
Supposed minimal web project.
Attachment(s):
test2.rar
Fixed. Thanks for the sample.
--
Sergey V. Coox
JetBrains, Inc
"Develop with pleasure!"
Is there any option to get a fix for this in 4.1, or is the only option available to download and install the 4.5 nightly build? From looking at the defect () it appears the fix should be in 4.5 build 1166 or 1167 -- can you confirm this?
Thank you
Partially fixed for 1164, fully for 1168.
I just installed build 1170 and I'm still getting this error. I can't believe you're not even attempting to fix this in version 4.1, and our only recourse is to install nightly builds of 4.5 which is still in development stages. This is a total showstopper bug and you shouldn't even be selling 4.1 while this is outstanding.
I'm going back to Resharper version 3 and not upgrading at all. Nor will the 20 other developers that work for me. What a waste of my afternoon.
|
https://resharper-support.jetbrains.com/hc/en-us/community/posts/206047919--Reshaper-4-1-Ambiguous-Reference-incorrect-error-?page=1#community_comment_206503729
|
CC-MAIN-2021-49
|
refinedweb
| 1,182
| 70.29
|
I make things clear I will mention the most important things. The detailed technical description of how operating system manages it internally can be found in additional resources at the bottom.
Dynamic libraries in MacOS
According to Apple developer’s docs:Apps written for OS X benefit from this feature because all system libraries in OS X are dynamic libraries.
So, how is it handled by the system? When a program is launched, kernel allocates resources for it and loads code and data into its space. It also loads dynamic loader, named dyld and lets it load dependent libraries (the ones our program was compiled with and that have undefined symbols). We will give a look to those undefined symbols later. Afterwards control is passed to the program itself. At load time we can use constructors that will provide initialization of those libraries.
Let’s code!
Let’s say I want to implement some simple mechanisms I find useful in many projects. In order to achieve this, I am writing a dynamic library with functions I use. I’m going to name it
mymath,:
#include <iostream> #include "mymath.h" #define EXPORT __attribute__((visibility("default"))) __attribute__((constructor)) static void _constructor() { std::cout << "Initializing mymath\n"; } EXPORT int mymath::add(int a, int b) { return a + b; } EXPORT int mymath::sub(int a, int b) { return a - b; } __attribute__((destructor)) static void _destructor() { std::cout << "Destroying mymath\n"; }
Two functions encapsulated in a namespace, constructor and destructor. That’s it. Of course header file will look like this:
namespace mymath { int add(int, int); int sub(int, int); }
And the Makefile:
all: llvm-g++ -Iinclude -dynamiclib -std=c++17 src/mymath.cpp -current_version 1.0 -compatibility_version 1.0 -fvisibility=hidden -o bin/mymath.dylib
That’s it. The structure of the project is also pretty straightforward:
$ tree . ├── Makefile ├── bin │ └── mymath.dylib ├── include │ └── mymath.h └── src └── mymath.cpp
Having achieved this, we can run
make command and start using this library in a project of our own.
$ tree . ├── Makefile ├── bin │ ├── main │ └── mymath.dylib ├── include │ └── mymath.h ├── lib │ └── mymath.dylib └── src └── main.cpp
We copy the header file and binary library and create new main file:
#include <iostream> #include "mymath.h" void myFunction() { int a, b; a = 55; b = 66; std::cout << "My math adds: " << mymath::add(a, b) << std::endl; std::cout << "My math subtracts: " << mymath::sub(a, b) << std::endl; } int main() { std::cout << "Hello Easy C++ project!" << std::endl; myFunction(); return 0; }
with Makefile as follows (it’s 90% generated by VS Code plugin Easy C++ Project, which I use):
CXX := clang++ CXX_FLAGS := -Wall -Wextra -std=c++17 -g BIN := bin SRC := src INCLUDE := include LIB := lib LIBRARIES := lib/mymath.dylib EXECUTABLE := main all: $(BIN)/$(EXECUTABLE) run: clean all ./$(BIN)/$(EXECUTABLE) $(BIN)/$(EXECUTABLE): $(SRC)/*.cpp $(CXX) $(CXX_FLAGS) -I$(INCLUDE) -L$(LIB) $^ -o $@ $(LIBRARIES) clean: -rm -rf $(BIN)/*
Note that the created dynamic library is in two places: in lib and bin folders. This happens because in first case it’s needed by linker to link the created binaries and in the second case by dylib to load it into process’ memory on runtime. We would not need the second copy if we placed the library eg. in
/usr/local/lib folder, or updated
DYLD_LIBRARY_PATH variable.
Now. What will be printed when we compile and run our code?
$ make && ./bin/main clang++ -Wall -Wextra -std=c++17 -g -Iinclude -Llib src/main.cpp -o bin/main lib/mymath.dylib Initializing mymath Hello Easy C++ project! My math adds: 121 My math subtracts: -11 Destroying mymath
As expected libraries we loaded first and unloaded last meaning the code we created in constructor run even before the first line in
main() function. Also, we can spot undefined symbols in newly created bin/main file using
nm tool:
$ nm --demangle bin/main (...) U __Unwind_Resume 0000000100001050 T myFunction() U mymath::add(int, int) U mymath::sub(int, int)
The U letter next to our function names indicates that we have an undefined symbol, which is one that is referenced outside our binary.
That’s pretty much it. My curiosity has been partially satisfied. In next part I’ll show how to transform this code to load and unload libraries in runtime and Linux and Windows will be coming soon afterwards.
|
https://blacksheephacks.pl/how-do-libraries-work-part-1/
|
CC-MAIN-2022-40
|
refinedweb
| 714
| 57.47
|
Back to index
00001 /* 00002 For general Scribus (>=1.3.2) copyright and licensing information please refer 00003 to the COPYING file provided with the program. Following this notice may exist 00004 a copyright and/or license notice that predates the release of Scribus 1.3.2 00005 for which a new license (GPL+exception) is in place. 00006 */ 00007 //============================== 00008 // Function parser v2.8 by Warp 00009 //============================== 00010 00011 // Configuration file 00012 // ------------------ 00013 00014 // NOTE: 00015 // This file is for the internal use of the function parser only. 00016 // You don't need to include this file in your source files, just 00017 // include "fparser.hh". 00018 00019 /* 00020 Comment out the following line if your compiler supports the (non-standard) 00021 asinh, acosh and atanh functions and you want them to be supported. If 00022 you are not sure, just leave it (those function will then not be supported). 00023 */ 00024 #define NO_ASINH 00025 00026 00027 /* 00028 Uncomment the following line to disable the eval() function if it could 00029 be too dangerous in the target application. 00030 Note that even though the maximum recursion level of eval() is limited, 00031 it is still possible to write functions using it which take enormous 00032 amounts of time to evaluate even though the maximum recursion is never 00033 reached. This may be undesirable in some applications. 00034 */ 00035 //#define DISABLE_EVAL 00036 00037 00038 /* 00039 Maximum recursion level for eval() calls: 00040 */ 00041 #define EVAL_MAX_REC_LEVEL 1000 00042 00043 00044 /* 00045 Comment out the following lines out if you are not going to use the 00046 optimizer and want a slightly smaller library. The Optimize() method 00047 can still be called, but it will not do anything. 00048 If you are unsure, just leave it. It won't slow down the other parts of 00049 the library. 00050 */ 00051 #ifndef NO_SUPPORT_OPTIMIZER 00052 #define SUPPORT_OPTIMIZER 00053 #endif 00054 00055 00056 /* 00057 Epsilon value used with the comparison operators (must be non-negative): 00058 (Comment it out if you don't want to use epsilon in comparisons. Might 00059 lead to marginally faster evaluation of the comparison operators, but 00060 can introduce inaccuracies in comparisons.) 00061 */ 00062 #define FP_EPSILON 1e-14
|
https://sourcecodebrowser.com/scribus-ng/1.3.4.dfsgplus-psvn20071115/fpconfig_8h_source.html
|
CC-MAIN-2016-44
|
refinedweb
| 368
| 61.06
|
I was making an edit (adding leading “0”s) to a coded-value domain in an SDE database and realized that my edits were changing the order of the rows of my domain. Rows were moved to the bottom of the list when they were edited.
So I went through the process of converting my domain back to a table, made my edits in Access and exported the rows to a .dbf in the order I wanted them.
I removed the domain from the field I knew it was assigned to but when I tried to delete the domain, I received an error (The domain is used as a default domain).
The Google Machine led me to an ArcForums post by with some python code for listing all the fields with a domain.
I tweaked the original a bit, first because it was only examining feature classes in a feature dataset, not stand-alone feature datasets. And secondly, I updated it to use arcpy. I posted both the 9.3 version and the 10.0 version, but here is a quick look. The key addition is the ‘listfc(“”)’ line that is the first line of the def listds() module.
import arcpy min_workspace = r"C:\Users\mranter\AppData\Roaming\ESRI\Desktop10.0\ArcCatalog\min.minstaff.sde" infgdb=(min_workspace) arcpy.env.workspace = infgdb def listfc(inDataset): featureclasses = arcpy.ListFeatureClasses("","",inDataset) for f in featureclasses: print "feature class: ",f lfields=arcpy.ListFields(f) for lf in lfields: if lf.domain < "": print " domain",f, lf.name, lf.domain def listds(): listfc("") datasets=arcpy.ListDatasets ("","") for d in datasets: print " dataset: ",d listfc(d) listds()
|
http://milesgis.com/tag/esri/page/2/
|
CC-MAIN-2017-51
|
refinedweb
| 270
| 67.86
|
Hey, Im fairly new and Im wondering what the public class that starts a program is. The tutorial for Java was understandable but it didnt explain what exactly is public class. Public class is used in every program and it doesnt start without it. Ive also see random. (something) that may be similar to public class? Is public class simply just what your file is named?
What exactly is public class?
public class basically has two parts;
public meaning anyone on a system or network can access the file (private is also an option, but for beginners use public)
class meaning the type of file java needs for the computer to understand the code. Basically the code you write is stored in a .java file. In the browser something called a compiler is built into the “run” button. In other IDE’s or text editors you can download often times they have you compile the code first (which effictively saves it as a .java wherever on your computer) and then you can run it.
When you run the compiler (not the program), Java takes the code and turns it into a .class file. Which contains a bunch of gibberish you can’t understand. Then something called the Java Virtual Machine (or JVM) takes the .class file and reads it to the computer so it can understand what you wrote.
This occurs when you run it.
So a class is essentially a special file type that Java uses. You can type anything after “class” and it will use that as your class name.
Hope this helps. If it’s a bit too advanced just message me directly.
|
https://discuss.codecademy.com/t/what-exactly-is-public-class/393644
|
CC-MAIN-2019-47
|
refinedweb
| 276
| 75.2
|
Data Structures for Drivers
no-involuntary-power-cycles(9P)
usb_completion_reason(9S)
usb_other_speed_cfg_descr(9S)
usb_request_attributes(9S)
- STREAMS entity declaration structure
#include <sys/stream.h>
Architecture independent level 1 (DDI/DKI).
Each STREAMS driver or module must have a streamtab structure.
streamtab is made up of qinit structures for both the read and write queue portions of each module or driver. Multiplexing drivers require both upper and lower qinit structures. The qinit structure contains the entry points through which the module or driver routines are called.
Normally, the read QUEUE contains the open and close routines. Both the read and write queue can contain put and service procedures.
struct qinit *st_rdinit; /* read QUEUE */ struct qinit *st_wrinit; /* write QUEUE */ struct qinit *st_muxrinit; /* lower read QUEUE*/ struct qinit *st_muxwinit; /* lower write QUEUE*/
STREAMS Programming Guide
|
http://docs.oracle.com/cd/E23824_01/html/821-1478/streamtab-9s.html
|
CC-MAIN-2014-52
|
refinedweb
| 131
| 57.87
|
I'm trying to make a plant monitor using an Arduino and processing.
Processing writes an html file based on the sensor input by the Arduino.
WinSCP is monitoring the file created for changes and directly uploads trough FTP when the file has changed.
The Arduino is sending the following to processing via serial:
45
0
31
40
x
import processing.serial.*;
Serial myPort;
String dataReading = "";
int lol = 0;
String</h1>";
String string1 = "Moisture Level: ";
String string2 = " %<br> Motorstate: ";
String string3 = "<br> Temperature: ";
String string4 = " °C<br> Humidity: ";
String string5 = "%<br>";
void setup() {
size(500, 500);
myPort = new Serial(this, "COM4", 9600);
myPort.bufferUntil('x');
}
void draw() {
}
String [] dataOutput = {};
void serialEvent(Serial myPort) {
dataReading = myPort.readString();
if (dataReading!=null) {
dataOutput = split(dataReading, '\n');
String [] tempfile = {string0,string1,dataOutput[1],string2,dataOutput[2],string3,dataOutput[3],string4,dataOutput[4],string5 };
println("saving to html file...");
saveStrings("data/index.html",tempfile);
}
}
<h1>Jurze Plants <img src="" alt="laughing" /></h1>
Moisture Level: 46 %<br>
Motorstate: 0 <br>
Temperature:31.00 °C <br>
Humidity: 35.00% <br>
<h1>Jurze Plants <img src="" alt="laughing" /></h1>
Moisture Level: %<br>
Motorstate: 46 <br>
Temperature:0 °C <br>
Humidity: 31.00% <br>
Time to debug your code! (We can't really do this for you, since we don't have your Arduino.)
Step 1: In your
serialEvent() function, use the
println() function to print out the value of
dataReading. Is the value what you expect?
Step 2: Print out the value of
dataOutput. Is that what you expect? Print out each index. Are they all what you expect? Check for extra spaces and control characters.
Step 3: Are the indexes what you expect them to be? I see you're starting with index
1 instead of index
0. Is that what you meant to do?
The point is, you have to print out the values of every variable to make sure they're what you expect. When you find the variable with the wrong value, you can trace back through your code to figure out exactly what's happening.
|
https://codedump.io/share/OCN0AhuQVpAb/1/processing-write-html-file-from-arduino-input
|
CC-MAIN-2017-09
|
refinedweb
| 342
| 67.86
|
Recommended Level
Beginner
Prerequistes
Writing PICAXE BASIC Code - Part 1
Writing PICAXE BASIC Code - Part 2
This is the third article in a multi-part series on writing PICAXE BASIC code. It introduces the if...then, endif, gosub, and return commands. Part 1 introduced the high, low, pause, and goto commands, the #picaxe directive, and the concept of labels. Part 2 introduced the for...next, wait, and symbol commands, general purpose variables, and the #no_data directive.
Prior to continuing with this article, completion of part 1 of this series is required. Part 1 provided complete details for the construction of the PA-08M2 Coding Test Circuit, which is essential to completion of this article. The schematic diagram is shown below for reference purposes.
Pushbutton Switches
Switch SW1 is a pushbutton momentary action switch, which means that the switch is operated for only as long as the operating button is held pressed. It is also a normally open (N.O.) switch, which means that it is open until the button is pressed, at which time the contacts close, allowing current to flow. To a certain extent, the symbol for SW1 in the schematic diagram reflects these characteristics.
The function of SW1 is to connect pinC.3 of the PICAXE 08M2 to ground while the button is pressed; the function of R6 is to allow a small amount of current to flow from the +5V supply to pinC.3. If R6 were not in the circuit, pinC.3 might operate correctly...or not. This is because, without R6, pinC.3 would not be connected unless SW1 was operated, but rather would be left "floating--" that is an undetermined logic state. Thus, the µC could interpret pinC.3 to be at a logic high or logic low, depending upon whatever unintended voltage might be on pinC3. And, in case you were wondering, VR1 plays no part in the operation of SW1 despite the fact that it is nearby in the schematic diagram. VR1 will be discussed in the next article in this series.
So, the net result of all this is that when SW1 is pressed, pinC.3 will be at a logic low or 0 (zero,) and when SW1 is released, pinC.3 will be at a logic high or 1.
Lighting an LED by Pushing a Button - Program Analysis
This short program is very easy to understand. In fact, lines 15, 17, and 21 are the only three lines about which you should have any questions; every other line has been throughly explained in part 1 or part 2 of this series of articles. If you are at all unclear about any of them, you should stop and review previous lessons.
Line 15 is just another symbol command with one slight difference; the symbol "p_button" will be used in a what is called an "if...then" command, as you can see in line 17. The comment very well descibes what the command means: if p_button (that is pinC.3) is low, the microcontroller executes lines 18 and following. If pinC.3 is not low, the program moves to the endif command (skipping lines 18, 19, and 20) and line 22 sends it back to "main:" to run again.
But that doesn't really explain why assigning a symbol (p_button, in this case) to pinC.3 requires the use of the long designation instead of just C.3. The PICAXE manual says, "When using inputs the input variable (pinC.1, pinC.2 etc) must be used (not the actual pin name C.1, C.2 etc.) i.e. the line must read ‘if pinC.1 = 1 then...’, not ‘if 1 = 1 then...’," but that explanation still explains only the "what" and not the "why."
Asking the question at the PICAXE forum produced a more complete answer: "...the pin designations such as C.3 are pre-defined constants. The test in an IF...THEN command must test a variable against a constant or another variable." Don't be bothered if you don't totally get the "why:" just remember to do the "what" as it's shown in the code. Here's the file for you to download and run.
Toggling Between Two LEDs by Pushing a Button - Program Analysis
Lines 1 thorugh 15 contain nothing new, and should be completely understandable without additional explanation.
Line 16 is the standard if...then statement; its purpose is simply to monitor the status of SW1. When the switch is pressed, a ground (logic low) is applied to pinC.3, and the microcontroller recognizes that as a logic 0 (zero.) The result is that bit 16 is incremented by 1 in line 17, and because a single bit can have only two states, each time bit16 is incremented, its value toggles between 0 (zero) and 1. Line 18 contains a pause command which stops the µC for a period of 100 milliseconds to allow the contacts of SW1 to stop bouncing and come to rest.
For an excellent explanation of switch bounce and how to deal with it, read this article by Jens Christoffersen. There, you will find that introducing a short delay is not the best way to overcome bouncing switch contacts, but it is the simplest, and is sufficient for this program. Line 17 is the endif command for the if...then command in line16.
Line 20 begins another if...then command by examining the state of bit16, and line 21 introduces the gosub command; gosub is short for go subroutine. If bit16 is at a count of 1, then the gosub command sends program execution to the subroutine labeled "green:" that begins at line 26. Lines 27 through 29 turn the green led on, the yellow led off, and pause for 100 milliseconds, after which the return command in line 30 sends program execution back to the first line of code following the gosub green command.
Line 22 is the first use of the else command, which indicates what the microcontroller should do if the previous if...then statement was not true. It is followed in this case by another gosub command, which sends the program to the subroutine labeled "yellow:" in line 31. Lines 32 through 34 turn the yellow led on, the green led off, and pause 100 milliseconds, after which another return command sends the program execution back to line 24, which is the endif command for the if...then command in line 16. At this point, goto main: in line 25 starts the entire SW1 checking sequence again.
At this point, you should be able to visualize what will happen as this code runs and the button is pushed and released or pushed and held down; think it through, then download the code file, run it and see if you were correct.
Final Thoughts
In the next article in this series, you will make use of the potentiometer, VR1, to control an LED chaser. The readadc command will be introduced and& explained, and the select, case, and endselect commands will be covered. In the meanwhile, write some code of your own; you have the knowledge and the skills...use them.
Next Article in Series: Writing PICAXE BASIC Code - Part 4
|
http://www.allaboutcircuits.com/technical-articles/writing-picaxe-basic-code-part-3/
|
CC-MAIN-2016-50
|
refinedweb
| 1,201
| 72.66
|
The Zone Source Formats
Zone documents can be authored in any format that can be converted to the intermediate format. Current adapters include:
Traditional Zone document. This consists of a title line followed by the contents of the HTML body. The HTML contents should be well-formed HTML, but need not be well-formed XML; it’s run through tidy or Beautiful Soup during conversion.
In the new implementation, all zone documents are interpreted inside an implied xmlns:zone=’’ namespace. This means that title tags can be written as <zone:title/> in the source.
MarkDown with Infogami extensions. This includes the use of [[link]] to add wiki-style links and smart links to the document.
|
http://effbot.org/zone/zone-source.htm
|
CC-MAIN-2019-13
|
refinedweb
| 115
| 66.13
|
Recently I was assigned a project in my Artificial Intelligence Course that required Fuzzy Logic to solve a simple problem. The idea was to have a Soccer Playing Robot that would go after the soccer ball given some simple Fuzzy Rules.
As usual, I started the project looking for some already made implementation of a fuzzy system (I know I know, but it works!). To my surprise, I found plenty of articles on the subject, but none providing a simple framework to build your own Fuzzy System.
Hence this article. The code provided here is not intended to be a complete implementation of a Fuzzy System, but rather to be a good starting point for your own needs. As a bonus, I included the soccer playing robot as a sample of using the FuzzyLogic Namespace.
This is just a simple crash course introduction to what Fuzzy Systems are. It is not mathematical nor formal centered, but rather very technical.
We all use Logic in our programming day, but that logic is one in which things are true or false. Not in between. This works great for deterministic situations. Unfortunately, our mind doesn't work like that and rarely treats facts as completely true or completely false.
Fuzzy Logic aims at recreating how the mind works by eliminating the absolute true or false and giving degrees of membership. These allow you to have an idea of how much a variable is one value or the other.
Based on the research I had to do for the soccer playing robot, I drew these conclusions about what fuzzy systems are:
For instance the "north" linguistic value could have a Triangular Membership function with parameters a=0°, b=90° and c=180°. This would mean that a 45° angle would have a 0.5 Membership to the linguistic value "north".
(direction, 80°) :== {(north, 0.9),(west,0),(south,0),(east,0.1)}
A Fuzzy Rules Set based on the Tagaki-Sugeno lets one easily calculate a crisp output from all the fuzzy values. The Fuzzy Rules Set would have a finite number of rules, all having the same crisp variable in the decision part. The final value of the crisp variable would be a weighted average of each Rule's crisp value. The weight of each rule is determined by the multiplication of the membership degrees of each (<linguistic variable>,<linguistic value>) pair.
As you review the code, you'll see it is very simplistic. As it was developed with a specific purpose in mind, the classes lack plenty of would-be useful methods. However, I did strive to make the code as OO as I could so that other people could easily add their own code.
Let's get down to business. The Project defines a new FuzzyLogic namespace which has:
TagakiSugenoFuzzySystem
TagakiSugenoFuzzyRule
IMembershipFunction
VariableValue
IMembershipFuncition
Membership
Variable
FuzzySet
VariableValue
To get an idea of how you could work with this namespace, I'll walk you through the soccer playing robot sample.
For the sample, I'll define a Fuzzy System that steers a soccer playing robot towards the soccer ball. To do this, I define 2 linguistic variables with its associated values like this:
distance
left
center
right
angle
north
west
south
east
The angle refers to where the ball is in respect to the robots heading. The distance defines if the ball is in the left side, center or right of the robot.
In the attached project, you can find the constructor of the Form1 form. This is where I define the fuzzy system to calculate how much the robots wheels must turn.
Form1
We start the definition of the system with its variables:
distancia.addValue(new VariableValue
("left", new TriangleMembershipFunction(-4000, -10, 0)));
distancia.addValue(new VariableValue
("center", new TriangleMembershipFunction(-10, 0, 10)));
distancia.addValue(new VariableValue
("right", new TriangleMembershipFunction(0, 10, 4000)));
angulo.addValue(new VariableValue
("north", new TriangleMembershipFunction(0, 90, 180)));
angulo.addValue(new VariableValue
("west", new TriangleMembershipFunction(90, 180, 270)));
angulo.addValue(new VariableValue
("south", new TriangleMembershipFunction(180, 270, 360)));
angulo.addValue(new VariableValue
("east", new InverseTrapezoidalMembershipFunction(0, 90, 270, 360)));
Next we define the Fuzzy Rules by which our system will work. Here are the first three:
system.addRule(new TagakiSugenoFuzzyRule(15, new string[] { "north", "left" }));
system.addRule(new TagakiSugenoFuzzyRule(0, new string[] { "north", "center" }));
system.addRule(new TagakiSugenoFuzzyRule(-15, new string[] { "north", "right" }));
Let's examine the first rule. It is saying that if the angle is pointing north, and the ball is on the robots left side, the wheels should turn 15°. The same logic applies for the rest of the rules.
Once the Fuzzy system is completely defined, we can start pumping out results. To do this, we define the input FuzzySets for the system like this:
FuzzySet setDistancia = new FuzzySet(distancia, robot.getDistancia(posPelota));
FuzzySet setAngulo = new FuzzySet(angulo, robot.getAngulo(posPelota));
FuzzySet[] sets = { setAngulo, setDistancia };
Once the sets are in place, we can feed them to the Fuzzy System to get a crisp result and implement the resulting decision from the system. Here, we'll move the robot 5 units in the direction the robot is moving after turning the amount of the Crisp Output the Fuzzy system gives.
robot.angRobot += Math.PI * system.CrispOutput(sets) / 180;
robot.posRobot.X += (float)(5 * Math.Cos(robot.angRobot));
robot.posRobot.Y += (float)(5 * Math.Sin(robot.angRobot));
One serious limitation the current code implementation has is that every rule must have the exact same number of conditionals and in the exact same order. This can easily be changed, but due to time constrains was not done. If interest from the community arises, I could find the time to do it, or even better put it on SourceForge.
This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)
public double MembershipOf(double value)
{
if ((a < value) && (value <= b))
return (b - value) / (b - a);
if ((b < value) && (value <= c))
return 0;
if ((c < value) && (value < d))
return (value - c) / (d - c);
return 1;
}
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
https://www.codeproject.com/script/articles/view.aspx?aid=29930
|
CC-MAIN-2016-50
|
refinedweb
| 1,039
| 55.34
|
Opened 9 years ago
Closed 9 years ago
Last modified 7 years ago
#13444 closed (fixed)
{% cycle %} no longer works within inclusion tags and included templates
Description
Cycle only works within the template that contains the for loop -- if you include a subtemplate or inclusion tag, cycle doesn't work.
This is a regression from 1.1.1.
def test(request): return render_to_response('test.html', {'bar':range(4)}) ----- test.html {% for i in bar %} {% cycle 'alpha' 'bravo' %} Tag:{% foo %} Include:{% include 'foo.html' %} {% endfor %} -------- @register.inclusion_tag('foo.html', takes_context=True) def foo(context): return context -------- foo.html {% cycle 'alpha' 'bravo' %} ------------ output: alpha Tag:alpha Include:alpha bravo Tag:alpha Include:alpha alpha Tag:alpha Include:alpha bravo Tag:alpha Include:alpha
Change History (7)
comment:1 Changed 9 years ago by
comment:2 follow-up: 4 Changed 9 years ago by
comment:3 Changed 9 years ago by
Putting on the 1.2 milestone; Alex's comment may be right, but given that this is potentially a regression, it needs to be resolved before 1.2 gets to release candidate.
comment:4 Changed 9 years ago by
Honestly, the previous behavior sounds like a bug.
I disagree. Subtemplates within a {% for %} tag still have access to the forloop template variables (forloop.counter, for example), so it doesn't make sense that they wouldn't be able to use {% cycle %}. They're still within the for loop.
comment:5 Changed 9 years ago by
@awmcclain: After discussion with Jannis and Jacob on IRC, we've come to the conclusion that Alex is correct in saying that previous behavior is a bug.
When you use {% cycle %} in the way you describe, you're not setting a context variable. The state of the cycle tag isn't held in context, it's part of the state of the cycle tag itself. By cycling, you're updating the state of a specific node in the template tree. The only time that state reaches context is if you name the cycle (using {% cycle ... as foo %}), and that only gives you the ability to read, not modify the cycle contents.
The use case you demonstrate depends on two bugs in the v1.1 template engine:
1) The include tag didn't establish a clean environment for each template load (and each include should be a clean template load)
2) The cycle tag in v1.1 wasn't threadsafe, so multiple template loaders could access the same cycle states.
These bugs have both been corrected as part of the cleanup required to allow for cached template loaders.
Another way of looking at the point (1): Although the end user documentation isn't clear on this point, the implementation (both current and historical) makes it clear that {% include %} should be interpreted as "Render this entire template and insert the HTML", not as "insert the node hierarchy parsed from this subtemplate". Since each included template should be an independent rendering, it doesn't make sense that cycle states should leak between renderings.
One way to restore the "old" behaviour (depending on exactly how you're using cycle) relies on using the part of cycle that *is* pushed into context. If you define the cycle tag in test.html as:
{% for i in bar %} {% cycle 'alpha' 'bravo' as testvalue %} Tag:{% foo %} Include:{% include 'foo.html' %} {% endfor %}
and change your foo.html to read:
{{ testvalue }}
you will get the output you expected to see.
I'll formally accept this on the basis that extra documentation is required. In particular:
- Extra notes for the backwards compatibility guide (since it isn't immediately obvious why this is a bug, not a regression). We already have a section on tags that might be affected by the rendering changes; this is an excellent example of how those changes could affect people in practice.
- A note to the {% include %} clarifying the intention of that tag.
comment:6 Changed 9 years ago by
comment:7 Changed 7 years ago by
Milestone 1.2 deleted
Honestly, the previous behavior sounds like a bug.
|
https://code.djangoproject.com/ticket/13444
|
CC-MAIN-2019-04
|
refinedweb
| 675
| 62.98
|
jawr Grails plugin
Dependency:
compile ":jawr:3.5.1"
Summary
jawr grails plugin
Description
Jawr is a tunable packaging solution for Javascript and CSS which allows for rapid development of resources in separate module files. You can work with a large set of split javascript files in development mode, then Jawr bundles all together into one or several files in any way you define. By using a tag library, Jawr allows you to use the same, unchanged GSP pages for development and production. Jawr also minifies and compresses the files, resulting in reduced page load times. You can find all the information and detailed documentation at plugin version is 3.3.3. The version number matches the Jawr version it uses underneath.
Using this syntax, you will be able to define bundles as specified in the relevant documentation pages. Note that you are not forced to use Jawr for both js and css files. If you add none of the jawr.css.* parameters, for instance, Jawr will do no effort to serve CSS files.
Jawr uses log4j to log messages, so you can configure its tracing level along with the rest of your application. All jawr packages start with net.jawr.*, so you can use that as a key for an appender configure Jawr you must add properties to the Config.groovy file located at the /conf folder of your application. The syntax you must use is exactly the same described for the .properties file used in standard java web applications. Check the config file syntax page for details. Keep in mind that there are a few property keys that don't apply when using Jawr with Grails. Those are:
- jawr.config.reload.interval: The Jawr servlet can be configured to listen to changes to the .properies file to reload it when it changes. In Grails, Jawr will instead listen to changes to the Config.groovy script to reload its configuration. This happens automatically when you start grails in development mode (but keep in mind that the changes are applied after you refresh a page in your browser).
- jawr.charset.name: The value set for grails.views.gsp.encoding will be used for this attribute (which is 'utf-8' by default in Grails).
-, but you may want to bundle only part of your code and serve the rest normally. This is specially useful if you are adding Jawr to an existing application and you do not want to change every existing script tag. Note that Jawr handles individual files (you don't need to explicitly define a bundle for every file you want to compress and serve standalone), so that should not keep you from using this mapping method.
- You can define a URL fragment as a prefix (such as '/jawr/') to prefix every URL. Jawr will only serve requests containing this prefix. To use this you must add two special parameters to your Config.groovy file, to specify the prefixes for js and css: tag library for grails works exactly the same as the JSP version, so you will find all the details in the JSP taglib documentation page.The only difference is that in GSP pages there is no need to import the tags at all. Also, keep in mind that the namespace for the Jawr taglib is 'jawr:'.This is how you would use the tags in a typical page:
<html> <head> <jawr:script <jawr:style </head> <body> … </body> </html>
|
http://www.grails.org/plugin/jawr
|
CC-MAIN-2014-35
|
refinedweb
| 573
| 73.37
|
Creating Visual Studio ProjectTemplate VSIX package
How to create VSIX package for ProjectTemplate
If you often have projects which setup is pretty much the same you might consider creating ProjectTemplate for Visual Studio.
It speeds up development for the project setup, adding references, default configuration .config, content files...
Before you start make sure that you have installed Microsoft Visual Studio 2013 SDK () and Nuget Package Explorer ()
I also attached a small dummy project just to help understanding what is written in this article.
Skipping to hands on code is always more helpful and faster for me to, so if you are bored by reading, download the attached .7zfile and explore it.
Now for those who prefer reading :)
Create a new project of C# Project Template. You will find it in Visual C# > Extensibility section.
Project will have included Class1.cs file. Feel free to rename it, but make sure you replace the filename in .vstemplate and .csproj
In the sample attached I renamed it to MyObject.
If you open the file you will see that it is a bit different than the class files you usually add to your projects. These values, especially namespace will be changed when you create a new project using this template.
You will notice that there is .ico file included in the ProjectTemplate project. It is an icon that will appear in the project templates list after you install the template and start creating new project. You can replace it with the icon you prefer for you project template.
Project template is now pretty much done.
Now to make it distributable you need to create a new project of VSIX Project type
Newly created project will have source.extension.vsixmanifest included which contains main settings for the VSIX package. If you double click it you will get an UI for setting the values, but for fine tuning you will have to switch to XML code view.
The UI consists of 4 sections:
- Metadata (contains info about the VSIX)
- Install Targets (list of Visual Studio versions and editions VSIX will be applicable to)
- Assets (the content of VSIX)
- Dependencies (libraries VSIX depends on)
Will stick to Assets section for now. One thing you need to include here is the project of C# Project Template type we previously created.
You project template is now ready and after building VSIX project you will have .vsix file created in bin folder of VSIX project.
File .vsix is nothing more than a zip archive, and if you open it with any archive manager like 7zip you will see the content of the package which contains project template as a zip archive inside it.
You can execute VSIX file from bin folder and install the project template now to check if everything is working properly. After installing, if you have any Visual Studio instances running, close them and start Visual Studio again.
Try to create new project and you should be able to see your project type in the list.
Usually for your project you will need to reference some custom library.
Reference library can be some library from either
- Library from GAC (.NET framework library)
- NuGet.org (nuget package)
- Local library (3rd party or library developed for that specific project type)
Unfortunately, adding reference to ProjectTemplate project will not neither when VSIX is created nor when it is executed.
Creating GAC references can be done by including them outside of TemplateContent node in the configuration of the .vstemplete file in ProjectTemplate project
<References> <Reference> <Assembly> System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 </Assembly> </Reference> <Reference> <Assembly> System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 </Assembly> </Reference> <Reference> <Assembly> System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 </Assembly> </Reference> <Reference> <Assembly> System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 </Assembly> </Reference> </References>
Creating non GAC reference can be done only through NuGet package installer which needs to be invoked from VSIX during installation process.
Either reference is nuget package from nuget.org repository or localy created nuget package, you need to include reference to NuGet wizard to source.extension.vsixmanifest in VSX project.
>
If we need to reference local assembly, we need to create NuGet package locally first. For that we need to install Nuget Package Explorer first.
For the testing purposes we'll create a class library assembly with an interface which will be implemented in the ProjectTemplate class.
namespace ApplicationBase { public abstract class CustomObject { private DateTime timeCreated; public DateTime TimeCreated { get { return timeCreated; } } string instanceGuid; public string InstanceGuid { get { return instanceGuid; } } string filePath; public string FilePath { get { return filePath; } } public CustomObject(string filePath) { this.instanceGuid = Guid.NewGuid().ToString().ToUpper(); this.timeCreated = DateTime.Now; this.filePath = filePath; } } }
Inherit this class in MyObject class in ProjectTemplate project to make sure that referencing is working after you install template and create new project of it's type.
public class MyObject:ApplicationBase.CustomObject { public MyObject(string filePath):base(filePath) { //Custom code implementation } }
For this we'll need a reference to class library. To keep the reference in the project template, we need to create a nuget package using NuGet Package Explorer.
After creating .nupkg create folder packages and store .nupkg file inside it. Change property "Build Action" to True and "Include in VSIX" to True in properties pane. in ProjectTemplate change file .vstemplate file to point to package from VSIX project.
This is important because without setting these values to True, package will not be included in .vsix after compiling
Before installing newly built Project Template extension, you need to uninstall previously installed on from Tools > Extensions and Updates menu option from Visual Studio.
After installing the new VSIX you will be able to create new type of project and you should have all the refernces added to newly created project
- ApplicationBase
- System.Configuration
- System.Xml
- System.Linq
- System.Web
For more info and sample chaeckout the article attachment where this whole sample project is available for download
References
-
-
-
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
|
https://dejanstojanovic.net/aspnet/2015/february/creating-visual-studio-projecttemplate-vsix-package/
|
CC-MAIN-2019-22
|
refinedweb
| 1,039
| 54.83
|
Electrical Engineering Archive: Questions from March 28, 2012
- RustyLion900 asked0 answers
- AngryMountain2016 asked1 answer
- Anonymous asked3 answers
- Anonymous asked2 answers
- klunesamak asked//An object thrown vertically at ve... Show morePROBLEM (1)//Lab7Exercise3.c
#include <stdio.h>
#include <math.h>
//An object thrown vertically at velocity 'v' will ascend for t=v/g seconds,
// then descend for another t=v/g seconds to its original point (g is the acceleration of gravity).
double distance( double v, double degrees);//horizontal distance traveled by a projectile fired at at velocity v at angle degrees.
double radians(double degrees);//radian equivalent of angle in degrees
int main()
{
//Using the functions above plus the trig functions in math.h,
//take user inputs of projectile velocity and angle, and print
// horizontal distance traveled, ignoring air resistance and
//curvature of the earth.
}
PROBLEM (2)//Lab7Exercise2.c
double Nthroot(double val, int N); //returns positive Nth root of val
double Nthpower(double val, int N); //returns val to the Nth power
int main()
{
//use Nthpower() to verify Nthroot() over some range of argument values for Nthroot
}
PROBLEM (3)//Lab7Exercise1.c
int isprime(int n); //returns 1 if n is a prime number, 0 otherwise
int main()
{
//uses isprime() to print all the prime numbers below 10,000
} • Show less0 answers
- spencer8278 asked1 answer
- MachoStar5523 asked1 answer
- MachoStar5523 asked1 answer
- Anonymous asked2 answers
- Anonymous asked2 answers
- YouDontKnowMe asked1 answer
- YouDontKnowMe asked0 answers
- YouDontKnowMe asked1 answer
- YouDontKnowMe asked0 answers
- Anonymous askedu(t-3)] and h(t) = 5 e-... Show moreCompute and plot convolution b/w (Use conv command)
x(t) = cos(?t) [u(t+2) – u(t-3)] and h(t) = 5 e-tu(t)
second is
Determine if x(t) = t.[u(t) – u(t-8)] is an energy or power signal. • Show less0 answers
- Anonymous asked0 answers
- Anonymous asked1 answer
- GreedyTurkey8669 asked3. An electric current in a conductor varies with time according to the expression I(t) = 114 sin (61 answer
- Anonymous asked0 answers
- TheEngineer1 askedFork circuits provide equal propagation delay from Input (In) to one of the outputs (A, B). Design a... Show more
Fork!
• Show less0 answers
- RoundJelly8967 askedI have the answer but need help getting there. I keep getting different result. please give detailed... Show more
I have the answer but need help getting there. I keep getting different result. please give detailed explaination.
Answer:7.7 a. C0 = 1110010; C1 = 0111001; C2 = 1011100; C3 = 0101110; C4 = 0010111;C5 = 1001011; C6 = 1100101b. C1 output = –7; bit value = 0c. C2 output = +9; bit value = 1• Show less0 answers
- Anonymous askedt-25... Show more
Given a circuit with applied voltage v(t)=14.14cos(ωt)(V) and a resulting current i(t)=17.1cos(ωt-25)(mA). Determine and draw the complete power triangle.• Show less1 answer
- GiganticComet6541 asked0 answers
- ClumsyGhost7787 askedsolution is in... Show more
• Show less
Electrical Engineering: Principles and Applications 5th Edition proplem 53 chapter 5.
solution is in cramster but only for IR, I need to also solve for the other variables, IR, IC, I .(REST OF PROBLEM)1 answer
- Anonymous asked0 answers
- Ihaveaquestion asked1 answer
- GiganticComet6541 askeduse the Booth multiplier to compute 0101 1100 × 1000 1001. Show the output of each multiplier s... More »0 answers
- Curious4445 askedThe nMOSFET that needs to be used i... Show more
Any circuit or simulation is appreciated. Please explain too :)
The nMOSFET that needs to be used is a 2N7000.• Show less0 answers
- Phoxbwell asked0 answers
- Anonymous asked1 answer
- Anonymous asked0 answers
- GoldNUGG askedThe objective is to find the value of R so that the maximum power is dissipotated by R. All componen... Show more
• Show less
The objective is to find the value of R so that the maximum power is dissipotated by R. All components are ideal. I am not sure where to start.1 answer
- Anonymous asked0 answers
- markymark21 asked1 answer
- GullibleJourney5560 askedThe inver... Show more
Find Vout.. R1=1.2K , R2=6.2K , R3= 2K , R4= 1K , R5= 1.8K and V1=2V both op-amps ±20v "The inverting inputs of the op-amps are on top"• Show less1 answer
- FrostyCity6302 askedAny help is greatly appreciated I am confused.
Design a high-pass op amp filter with a high-frequency... Show moreAny help is greatly appreciated I am confused.
Design a high-pass op amp filter with a high-frequency gain of -100 and a cutoff frequency of 1kHz. Resistors with values of 1kohm, 10khom, and 100kohm are available. Determine the capacitance and resistance values of the filter. • Show less1 answer
- GullibleJourney5560 asked1 answer
- SpookyEel2812 asked0 answers
- SpookyEel2812 asked1 answer
- SpookyEel2812 asked0 answers
- SpookyEel2812 asked0 answers
- SpookyEel2812 asked1 answer
- FestiveTuba7438 asked1 answer
- RottenPanther7864 asked1 answer
- CapableWhale1000 askedone o... Show moreA combinational logic circuit has two control inputs, C1 and C2, two data inputs, A and B, and
one output, Z. Design a logic circuit that performs the logic operations on the two data inputs
as specified in the table below:
C1 C2 Logic Function
0 0 A'
0 1 A.B
1 0 A+B
1 1 A xor B
(a) Construct the Truth table for the output Z, in terms of the inputs C1, C2, A, and B.
(b) Derive a minimum Boolean expression for the output Z.
(c) Draw the corresponding circuit diagram (using AND and OR gates). • Show less1 answer
- pziadeh asked1 answer
- pziadeh askedfor the... Show more
Measurements on the circuit below produce labeled voltages as indicated. Find the value of β for the transistor.
• Show less1 answer
- pziadeh askedof 200. What is the dc voltage at the collector?... Show more
In the circuit shown below, the transistor has a β of 200. What is the dc voltage at the collector? Find the input resistnaces Rib and Rin and the overall voltage gain (v0/vsig). For an output signal of ± 0.4 V, what values of vsig and vb are required?
• Show less1 answer
- pziadeh askedAssume that... Show more
For the circuit shown below, find the input resistance Rin and the voltage gain v0/vsig. Assume that the source provides a small signal vsig and that β = 100.
• Show less1 answer
- pziadeh askedvalues in the rang... Show more
For the emitter-follower circuit shown below, the BJT used is specified to have β values in the range of 50 to 200 (a distressing situation for the circuit designer). For the two extreme values of β (β = 50 and β = 200), find:
a) IE, VE, and VB
b) the input resistance Rin
c) The voltage gain v0/vsig
• Show less2 answers
- pziadeh asked=... Show more
For the circuit shown below, find VB and VE for v1 = 0 V, +2 V, -2.5 V, and -5 V. The BJTs have β = 100.
• Show less1 answer
- Anonymous asked2 answers
- Anonymous asked1 answer
|
http://www.chegg.com/homework-help/questions-and-answers/electrical-engineering-archive-2012-march-28
|
CC-MAIN-2014-35
|
refinedweb
| 1,121
| 65.83
|
I am currently using .NET coding in C# and have had success reading a File GeoDatabase Table Attributes in the FeatureClasses. Ultimately I want to read a Feature Class in the File GeoDatabase and then uploaded to a registered SQL Database. Also, although I can read the data I do not know how to access the Shape information (point, polygon...)
These are the references I am currently using
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geometry;
It seems that this may be a routine operation, does anyone have any samples I can refer to?
I am not sure if this is the correct place to post this question
Hi,
The best forum for your question is ArcObjects SDK
Cheers
Mike
|
https://community.esri.com/thread/222231-update-sde-sql-database-from-file-geodatabase
|
CC-MAIN-2018-51
|
refinedweb
| 128
| 59.3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.